Update app.py
Browse files
app.py
CHANGED
|
@@ -1,143 +1,87 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import json
|
| 3 |
import gradio as gr
|
| 4 |
-
from google.generativeai.types import HarmCategory, HarmBlockThreshold
|
| 5 |
import google.generativeai as genai
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
#
|
| 8 |
-
#
|
| 9 |
-
#
|
| 10 |
-
|
| 11 |
-
genai.configure(api_key=API_KEY)
|
| 12 |
-
|
| 13 |
-
# Check for a valid API key
|
| 14 |
-
if not API_KEY or API_KEY == "YOUR_API_KEY":
|
| 15 |
-
raise ValueError("API_KEY not found. Please set the GOOGLE_API_KEY environment variable or replace 'YOUR_API_KEY' in the code.")
|
| 16 |
-
|
| 17 |
-
# Create the Gemini 2.5 Flash model instance
|
| 18 |
-
model = genai.GenerativeModel(
|
| 19 |
-
"gemini-2.5-flash-preview-05-20",
|
| 20 |
-
generation_config={
|
| 21 |
-
"response_mime_type": "application/json",
|
| 22 |
-
"response_schema": {
|
| 23 |
-
"type": "ARRAY",
|
| 24 |
-
"items": {
|
| 25 |
-
"type": "OBJECT",
|
| 26 |
-
"properties": {
|
| 27 |
-
"type": {"type": "STRING", "enum": ["Topic", "Headline"]},
|
| 28 |
-
"item": {"type": "STRING"},
|
| 29 |
-
"source": {"type": "STRING"}
|
| 30 |
-
}
|
| 31 |
-
}
|
| 32 |
-
}
|
| 33 |
-
}
|
| 34 |
-
)
|
| 35 |
|
| 36 |
-
#
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
-
|
|
|
|
| 45 |
"""
|
| 46 |
-
|
| 47 |
-
|
| 48 |
"""
|
| 49 |
try:
|
| 50 |
-
#
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
prompt,
|
| 56 |
-
safety_settings={
|
| 57 |
-
HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,
|
| 58 |
-
HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
|
| 59 |
-
HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,
|
| 60 |
-
HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,
|
| 61 |
-
}
|
| 62 |
)
|
| 63 |
-
|
| 64 |
-
# Parse the JSON response
|
| 65 |
-
report_data = json.loads(response.text)
|
| 66 |
|
| 67 |
-
#
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
except Exception as e:
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
return error_message, ""
|
| 85 |
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
with gr.Row():
|
| 101 |
-
industry_input = gr.Textbox(
|
| 102 |
-
label="Industry Focus",
|
| 103 |
-
placeholder="e.g., 'sustainable fashion' or 'biomedical research'",
|
| 104 |
-
scale=2
|
| 105 |
-
)
|
| 106 |
-
num_items_slider = gr.Slider(
|
| 107 |
-
minimum=1,
|
| 108 |
-
maximum=10,
|
| 109 |
-
step=1,
|
| 110 |
-
value=5,
|
| 111 |
-
label="Number of Items",
|
| 112 |
-
info="Select the number of topics and headlines to generate.",
|
| 113 |
-
scale=1
|
| 114 |
-
)
|
| 115 |
-
|
| 116 |
-
generate_button = gr.Button("Generate Trend Report", variant="primary")
|
| 117 |
-
|
| 118 |
-
gr.Markdown("---")
|
| 119 |
-
|
| 120 |
-
with gr.Row():
|
| 121 |
-
topics_output = gr.Textbox(
|
| 122 |
-
label="Trending Topics",
|
| 123 |
-
interactive=False,
|
| 124 |
-
lines=10,
|
| 125 |
-
show_copy_button=True,
|
| 126 |
-
scale=1
|
| 127 |
-
)
|
| 128 |
-
headlines_output = gr.Textbox(
|
| 129 |
-
label="Key News Headlines",
|
| 130 |
-
interactive=False,
|
| 131 |
-
lines=10,
|
| 132 |
-
show_copy_button=True,
|
| 133 |
-
scale=1
|
| 134 |
-
)
|
| 135 |
-
|
| 136 |
-
generate_button.click(
|
| 137 |
-
fn=get_trend_report,
|
| 138 |
-
inputs=[industry_input, num_items_slider],
|
| 139 |
-
outputs=[topics_output, headlines_output]
|
| 140 |
-
)
|
| 141 |
|
|
|
|
| 142 |
if __name__ == "__main__":
|
| 143 |
demo.launch()
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
import google.generativeai as genai
|
| 3 |
+
import os
|
| 4 |
+
import json
|
| 5 |
+
import asyncio
|
| 6 |
|
| 7 |
+
# The API key is provided automatically by the platform.
|
| 8 |
+
# For local testing, you can uncomment and replace with your key.
|
| 9 |
+
# os.environ["GEMINI_API_KEY"] = "YOUR_API_KEY"
|
| 10 |
+
genai.configure(api_key=os.environ.get("GEMINI_API_KEY"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
# Define a system prompt to guide the model's persona and output format.
|
| 13 |
+
SYSTEM_PROMPT = """
|
| 14 |
+
You are a professional AI TrendSpotter. Your task is to identify and summarize recent trends for a given topic.
|
| 15 |
+
Use a conversational but informative tone. Your response should include:
|
| 16 |
+
1. A brief, engaging introduction.
|
| 17 |
+
2. A summary of 3-5 key trends, each with a short, descriptive title.
|
| 18 |
+
3. For each trend, a short paragraph explaining what it is and why it is significant.
|
| 19 |
+
4. A concluding sentence that encourages further exploration.
|
| 20 |
+
5. The information MUST be grounded in real-time search results to ensure accuracy and relevance.
|
| 21 |
+
"""
|
| 22 |
|
| 23 |
+
# The main function that handles the trend spotting request.
|
| 24 |
+
async def get_trends(topic):
|
| 25 |
"""
|
| 26 |
+
This function takes a topic as input, uses the Gemini API with Google Search grounding
|
| 27 |
+
to find and summarize recent trends, and returns the formatted response.
|
| 28 |
"""
|
| 29 |
try:
|
| 30 |
+
# Create the model with the specified system instructions.
|
| 31 |
+
model = genai.GenerativeModel(
|
| 32 |
+
model_name='gemini-2.5-flash-preview-05-20',
|
| 33 |
+
system_instruction=SYSTEM_PROMPT,
|
| 34 |
+
tools=[genai.tool_named('google_search')]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
)
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
+
# Generate content based on the user's prompt.
|
| 38 |
+
prompt = f"What are the latest trends about: {topic}?"
|
| 39 |
+
response = await model.generate_content_async(prompt)
|
| 40 |
+
|
| 41 |
+
# Process the response to extract text and sources.
|
| 42 |
+
text = response.text
|
| 43 |
|
| 44 |
+
# Grounding metadata to extract citations if available
|
| 45 |
+
sources = []
|
| 46 |
+
if response.candidates:
|
| 47 |
+
candidate = response.candidates[0]
|
| 48 |
+
if candidate.grounding_metadata:
|
| 49 |
+
grounding_metadata = candidate.grounding_metadata
|
| 50 |
+
if grounding_metadata.grounding_attributions:
|
| 51 |
+
for attribution in grounding_metadata.grounding_attributions:
|
| 52 |
+
if attribution.web and attribution.web.uri and attribution.web.title:
|
| 53 |
+
sources.append({
|
| 54 |
+
"title": attribution.web.title,
|
| 55 |
+
"uri": attribution.web.uri
|
| 56 |
+
})
|
| 57 |
+
|
| 58 |
+
# Format the output with citations.
|
| 59 |
+
citations_text = ""
|
| 60 |
+
if sources:
|
| 61 |
+
citations_text = "### Sources\n"
|
| 62 |
+
for source in sources:
|
| 63 |
+
citations_text += f"- [{source['title']}]({source['uri']})\n"
|
| 64 |
+
|
| 65 |
+
return f"{text}\n\n{citations_text}"
|
| 66 |
|
| 67 |
except Exception as e:
|
| 68 |
+
# Gracefully handle any API errors or other exceptions.
|
| 69 |
+
return f"An error occurred: {e}"
|
|
|
|
| 70 |
|
| 71 |
+
# Set up the Gradio interface.
|
| 72 |
+
# We're using gr.Interface for a simple, clean UI.
|
| 73 |
+
# The `get_trends` function is passed as the main function to run.
|
| 74 |
+
# The inputs and outputs are defined to create the UI components.
|
| 75 |
+
demo = gr.Interface(
|
| 76 |
+
fn=get_trends,
|
| 77 |
+
inputs=gr.Textbox(lines=2, label="Enter a topic to spot trends for:", placeholder="e.g., sustainable fashion, quantum computing, or remote work"),
|
| 78 |
+
outputs=gr.Markdown(label="Trends Summary"),
|
| 79 |
+
title="AI TrendSpotter",
|
| 80 |
+
description="Ask the AI to identify and summarize recent trends on any topic. Powered by the Gemini API with Google Search grounding for real-time information.",
|
| 81 |
+
allow_flagging="never",
|
| 82 |
+
theme="soft"
|
| 83 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
+
# Launch the Gradio application.
|
| 86 |
if __name__ == "__main__":
|
| 87 |
demo.launch()
|