CartwrightAIproject commited on
Commit
b7a54e9
·
verified ·
1 Parent(s): 7a6f8aa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -126
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
- # Configure your Google API key
8
- # Replace with your actual API key or set as an environment variable
9
- # If running in a notebook, you can paste the key directly here.
10
- API_KEY = os.environ.get("GOOGLE_API_KEY") or "YOUR_API_KEY"
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
- # Custom Gradio theme
37
- my_brand_theme = gr.themes.Default(
38
- primary_hue="#3660EB",
39
- secondary_hue="#FFBF33",
40
- neutral_hue="#16181b",
41
- font=gr.themes.GoogleFont("DM Sans")
42
- )
 
 
 
43
 
44
- def get_trend_report(industry_focus, num_items):
 
45
  """
46
- Generates a trend report based on a given industry and number of items.
47
- The function calls the Gemini API to get a JSON response.
48
  """
49
  try:
50
- # Define the new prompt with f-string formatting
51
- prompt = f""" You are an expert media monitoring analyst specializing in the '{industry_focus}' sector. For the past week, identify {num_items} distinct, plausible trending topics and {num_items} key news headlines. These should reflect current challenges, innovations, legislation changes, or significant events relevant to the {industry_focus} sector. This is for our marketing agency to use to help create relevant PR and marketing ideas for our clients in {industry_focus}. Provide the output as a JSON array of objects, where each object has: - "type": "Topic" or "Headline" - "item": The trending topic or headline text - "source": A plausible, simulated source (e.g., "Industry Report", "Major News Outlet", "Social Media Discussion", "Government Announcement")"""
52
-
53
- # Call the Gemini API with the new prompt
54
- response = model.generate_content(
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
- # Organize data for display
68
- topics = [item for item in report_data if item['type'] == 'Topic']
69
- headlines = [item for item in report_data if item['type'] == 'Headline']
 
 
 
70
 
71
- topics_str = ""
72
- for topic in topics:
73
- topics_str += f"- {topic['item']} (Source: {topic['source']})\n"
74
-
75
- headlines_str = ""
76
- for headline in headlines:
77
- headlines_str += f"- {headline['item']} (Source: {headline['source']})\n"
78
-
79
- return topics_str, headlines_str
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
  except Exception as e:
82
- error_message = f"An error occurred: {e}"
83
- # Return empty strings for display in case of an error
84
- return error_message, ""
85
 
86
- with gr.Blocks(theme=my_brand_theme, title="AI TrendSpotter") as demo:
87
- gr.Markdown(
88
- """
89
- <div style="text-align: center;">
90
- <h1 style="font-size: 2.5rem; font-weight: bold; color: #3660EB;">
91
- AI TrendSpotter
92
- </h1>
93
- <p style="font-size: 1rem; color: #FFBF33;">
94
- Generate the latest trends and headlines for any industry.
95
- </p>
96
- </div>
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()