File size: 4,428 Bytes
ddf8e65 96decc0 ddf8e65 d0d8730 e687876 d0d8730 001bb52 716fbb1 e687876 716fbb1 ddf8e65 716fbb1 e687876 716fbb1 ddf8e65 d0d8730 96decc0 d0d8730 d9fd4f3 81fef39 d9fd4f3 81fef39 d9fd4f3 81fef39 d9fd4f3 81fef39 d9fd4f3 81fef39 d9fd4f3 81fef39 d9fd4f3 81fef39 d0d8730 e687876 d0d8730 ddf8e65 5e485ff 116a905 a3d0484 116a905 96decc0 116a905 d9fd4f3 116a905 ddf8e65 1beac75 96decc0 ddf8e65 116a905 96decc0 116a905 96decc0 116a905 5e485ff 116a905 5e485ff ddf8e65 d9fd4f3 ddf8e65 716fbb1 ddf8e65 5e485ff d0d8730 96decc0 d0d8730 d9fd4f3 d0d8730 e687876 d0d8730 d9fd4f3 a3d0484 d9fd4f3 a2d2939 d9fd4f3 ddf8e65 a2d2939 d0d8730 001bb52 d0d8730 ddf8e65 001bb52 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | import os
import gradio as gr
from google import genai
from google.genai import types
from google.genai.types import GenerateContentConfig, GoogleSearch, Tool
# =========================================================
# Gemini Setup
# =========================================================
API_KEY = os.getenv("Gemini_API_Key")
if not API_KEY:
raise RuntimeError(
"β Gemini_API_Key is not set. "
"Add it in Hugging Face β Settings β Secrets."
)
client = genai.Client(api_key=API_KEY)
# β
Valid model
MODEL_ID = "gemini-2.0-flash"
# =========================================================
# Custom CSS + JS
# =========================================================
custom_css = """
#search-btn {
background-color: #4f46e5 !important;
color: white !important;
font-size: 16px;
border-radius: 10px;
padding: 10px 18px;
transition: opacity 0.6s ease, transform 0.2s ease;
}
#search-btn:active {
opacity: 0.5;
transform: scale(0.97);
}
"""
custom_js = """
() => {
const clap = new Audio("https://www.soundjay.com/human/applause-8.mp3");
clap.play();
}
"""
# =========================================================
# AI Function (BULLETPROOF)
# =========================================================
def google_search_query(question):
# ---------- 1οΈβ£ Normalize safely ----------
if question is None:
question = ""
else:
question = str(question)
question = question.strip()
if question == "":
return "Please type a question above π", ""
try:
# ---------- 2οΈβ£ Define Search Tool ----------
google_search_tool = Tool(
google_search=GoogleSearch()
)
# ---------- 3οΈβ£ Generate Response ----------
response = client.models.generate_content(
model=MODEL_ID,
contents=[
types.Content(
role="user",
parts=[types.Part.from_text(question)]
)
],
config=GenerateContentConfig(
tools=[google_search_tool]
),
)
# ---------- 4οΈβ£ Extract AI Text Safely ----------
ai_response = ""
if hasattr(response, "text") and response.text:
ai_response = response.text
elif response.candidates:
try:
ai_response = response.candidates[0].content.parts[0].text
except Exception:
ai_response = "No AI response generated."
else:
ai_response = "No AI response generated."
# ---------- 5οΈβ£ Extract Search Grounding Safely ----------
search_results = ""
try:
candidate = response.candidates[0]
if (
hasattr(candidate, "grounding_metadata")
and candidate.grounding_metadata
and candidate.grounding_metadata.search_entry_point
):
search_results = (
candidate
.grounding_metadata
.search_entry_point
.rendered_content
)
except Exception:
search_results = ""
return ai_response, search_results
except Exception as e:
return f"β Error: {str(e)}", ""
# =========================================================
# Gradio App
# =========================================================
with gr.Blocks(css=custom_css) as app:
gr.Markdown("## π Google Search with Gemini AI")
question = gr.Textbox(
lines=2,
label="Ask a Question",
placeholder="e.g. What are types of machine learning?"
)
search_btn = gr.Button("π Search", elem_id="search-btn")
ai_output = gr.Textbox(label="AI Response")
search_output = gr.HTML(label="Search Results")
# Button click
search_btn.click(
fn=google_search_query,
inputs=[question],
outputs=[ai_output, search_output],
js=custom_js
)
# Enter key submit
question.submit(
fn=google_search_query,
inputs=[question],
outputs=[ai_output, search_output],
)
# =========================================================
# Launch (HF SAFE)
# =========================================================
if __name__ == "__main__":
app.queue().launch()
|