CartwrightAIproject commited on
Commit
a092bb1
·
verified ·
1 Parent(s): 96d9982

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -76
app.py CHANGED
@@ -1,92 +1,76 @@
1
  import gradio as gr
2
- import google.generativeai as genai
3
- import asyncio
4
  import os
5
- from google.generativeai.types import Tool
6
- from google.generativeai.ext import google_search as google_search_tool_ext
7
 
8
- # The API key should be set as a secret in your Hugging Face Space.
9
- # This ensures it is not hardcoded and remains secure.
10
- # If the key is not set, the app will still run but will fail on API calls.
11
- GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
12
- if GOOGLE_API_KEY:
13
- genai.configure(api_key=GOOGLE_API_KEY)
14
- else:
15
- print("Warning: GOOGLE_API_KEY environment variable not set. API calls will fail.")
16
 
17
- # Define a system prompt to guide the model's persona and output format.
18
- SYSTEM_PROMPT = """
19
- You are a professional AI TrendSpotter. Your task is to identify and summarize recent trends for a given topic.
20
- Use a conversational but informative tone. Your response should include:
21
- 1. A brief, engaging introduction.
22
- 2. A summary of 3-5 key trends, each with a short, descriptive title.
23
- 3. For each trend, a short paragraph explaining what it is and why it is significant.
24
- 4. A concluding sentence that encourages further exploration.
25
- 5. The information MUST be grounded in real-time search results to ensure accuracy and relevance.
26
- """
27
 
28
- # The main function that handles the trend spotting request.
29
- async def get_trends(topic):
 
 
 
 
 
 
 
 
30
  """
31
- This function takes a topic as input, uses the Gemini API with Google Search grounding
32
- to find and summarize recent trends, and returns the formatted response.
 
 
 
 
 
 
33
  """
34
  try:
35
- # Create the model with the specified system instructions and Google Search tool.
36
- # We use the correct syntax for including the Google Search tool.
37
- model = genai.GenerativeModel(
38
- model_name='gemini-2.5-flash-preview-05-20',
39
- system_instruction=SYSTEM_PROMPT,
40
- tools=[google_search_tool_ext.GoogleSearch.tool]
 
 
41
  )
42
 
43
- # Generate content based on the user's prompt.
44
- prompt = f"What are the latest trends about: {topic}?"
45
- response = await model.generate_content_async(prompt)
46
-
47
- # Process the response to extract text and sources.
48
- text = response.text
49
 
50
- # Grounding metadata to extract citations if available
51
- sources = []
52
- if response.candidates:
53
- candidate = response.candidates[0]
54
- if candidate.grounding_metadata and candidate.grounding_metadata.grounding_attributions:
55
- for attribution in candidate.grounding_metadata.grounding_attributions:
56
- if attribution.web and attribution.web.uri and attribution.web.title:
57
- sources.append({
58
- "title": attribution.web.title,
59
- "uri": attribution.web.uri
60
- })
61
-
62
- # Format the output with citations.
63
- citations_text = ""
64
- if sources:
65
- citations_text = "### Sources\n"
66
- for source in sources:
67
- citations_text += f"- [{source['title']}]({source['uri']})\n"
68
-
69
- return f"{text}\n\n{citations_text}"
70
-
71
  except Exception as e:
72
- # Gracefully handle any API errors or other exceptions.
73
  return f"An error occurred: {e}"
74
 
75
- # Set up the Gradio interface.
76
- # We're using gr.Interface for a simple, clean UI.
77
- # The `get_trends` function is passed as the main function to run.
78
- # The inputs and outputs are defined to create the UI components.
79
- demo = gr.Interface(
80
- fn=get_trends,
81
- inputs=gr.Textbox(lines=2, label="Enter a topic to spot trends for:", placeholder="e.g., sustainable fashion, quantum computing, or remote work"),
82
- outputs=gr.Markdown(label="Trends Summary"),
83
- title="AI TrendSpotter for PR & Marketing Insights",
84
- 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. Designed for public relations and marketing professionals.",
85
- allow_flagging="never",
86
- theme="soft"
87
- )
 
 
 
 
 
 
 
 
88
 
89
- # Launch the Gradio application.
90
- # The host and port are configured for Hugging Face Spaces.
91
  if __name__ == "__main__":
92
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
  import gradio as gr
 
 
2
  import os
3
+ import google.generativeai as genai
 
4
 
5
+ # Get the API key from a Hugging Face Space Secret
6
+ API_KEY = os.environ.get("GOOGLE_API_KEY")
 
 
 
 
 
 
7
 
8
+ if not API_KEY:
9
+ raise ValueError("GOOGLE_API_KEY environment variable not set. Please add it to your Hugging Face Space Secrets.")
 
 
 
 
 
 
 
 
10
 
11
+ # Configure the Gemini API with the key
12
+ genai.configure(api_key=API_KEY)
13
+
14
+ # Initialize the GenerativeModel with the google_search tool
15
+ model = genai.GenerativeModel(
16
+ model_name="gemini-1.5-flash-001",
17
+ tools=[genai.Tool.from_google_search()],
18
+ )
19
+
20
+ def analyze_trend(industry: str) -> str:
21
  """
22
+ Generates a report on the latest trends in a given industry using the Gemini API
23
+ with Google Search.
24
+
25
+ Args:
26
+ industry: The industry to analyze.
27
+
28
+ Returns:
29
+ A formatted report on the industry trends.
30
  """
31
  try:
32
+ # Prompt for the Gemini model with a system instruction to get a good report
33
+ prompt = f"Provide a detailed, insightful report on the top 5 emerging trends in the {industry} industry. Include a brief explanation for each trend, why it's important, and a prediction for its impact over the next 12 months."
34
+
35
+ # Use the GenerativeModel to generate content with search grounding
36
+ response = model.generate_content(
37
+ prompt,
38
+ # Stream the response for a better user experience
39
+ stream=True
40
  )
41
 
42
+ # Collect the full response text
43
+ full_response_text = ""
44
+ for chunk in response:
45
+ if chunk.text:
46
+ full_response_text += chunk.text
 
47
 
48
+ return full_response_text
49
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  except Exception as e:
 
51
  return f"An error occurred: {e}"
52
 
53
+ # Create the Gradio interface
54
+ with gr.Blocks(title="AI TrendSpotter") as demo:
55
+ gr.Markdown("# AI TrendSpotter")
56
+ gr.Markdown("An app that uses the Gemini API with Google Search to provide up-to-date reports on industry trends.")
57
+
58
+ with gr.Row():
59
+ industry_input = gr.Textbox(
60
+ label="Enter an industry to analyze:",
61
+ placeholder="e.g., sustainable fashion, virtual reality, renewable energy"
62
+ )
63
+
64
+ with gr.Row():
65
+ submit_btn = gr.Button("Generate Report")
66
+
67
+ report_output = gr.Markdown(label="Trend Report")
68
+
69
+ submit_btn.click(
70
+ fn=analyze_trend,
71
+ inputs=industry_input,
72
+ outputs=report_output
73
+ )
74
 
 
 
75
  if __name__ == "__main__":
76
+ demo.launch()