import gradio as gr import pandas as pd from serpapi import GoogleSearch # SERP API key (replace with your actual key) SERP_API_KEY = "785988650046bf6eddbc597cbf87330e2d53f8a3bacb4bac62a90ab1ecfa2445" def search_and_answer(question): try: # Step 1: Fetch search results from Google using SERP API search_params = { "q": question, "hl": "en", "gl": "us", "api_key": SERP_API_KEY } search = GoogleSearch(search_params) results = search.get_dict() # Extract top 3 organic search results extracted_results = [] for result in results.get("organic_results", [])[:3]: extracted_results.append({ "title": result.get("title"), "link": result.get("link"), "snippet": result.get("snippet", "No description available.") }) if not extracted_results: return pd.DataFrame(columns=["Answer", "Source", "Confidence Score"]) # Step 2: Prepare final dataframe with sources and confidence scores data = [] for i, res in enumerate(extracted_results): confidence_score = round(1 - (i * 0.2), 2) # Simulated confidence score data.append({ "Answer": res["snippet"], "Source": res["link"], "Confidence Score": confidence_score }) df = pd.DataFrame(data) return df except Exception as e: return pd.DataFrame({"Error": [str(e)]}) # Step 3: Create Gradio Interface iface = gr.Interface( fn=search_and_answer, inputs=gr.Textbox(label="Ask a Question"), outputs=gr.Dataframe(headers=["Answer", "Source", "Confidence Score"]), title="AI-Powered Q&A System ", description="Enter a question and get top 3 answers from web search with confidence scores." ) # Launch the Gradio app with debug enabled iface.launch(share=True, debug=True)