TarSh8654 commited on
Commit
b46567f
·
verified ·
1 Parent(s): 5675eb7

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -0
app.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import json
4
+ import os
5
+
6
+ # --- Gemini API Configuration ---
7
+ # The API key will be automatically provided by the Canvas environment at runtime
8
+ # if left as an empty string. DO NOT hardcode your API key here.
9
+ API_KEY = "" # Leave as empty string for Canvas environment
10
+ API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent"
11
+
12
+ # --- Function to call the Gemini API ---
13
+ async def call_gemini_api(prompt: str) -> str:
14
+ """
15
+ Calls the Gemini API with the given prompt and returns the generated text.
16
+ """
17
+ headers = {
18
+ 'Content-Type': 'application/json',
19
+ }
20
+ payload = {
21
+ "contents": [{"role": "user", "parts": [{"text": prompt}]}],
22
+ }
23
+
24
+ # Append API key to URL if available, otherwise it's handled by Canvas runtime
25
+ full_api_url = f"{API_URL}?key={API_KEY}" if API_KEY else API_URL
26
+
27
+ try:
28
+ # Use requests.post for synchronous call, or aiohttp for async if needed
29
+ # For Gradio, direct requests.post within the function is usually fine.
30
+ response = requests.post(full_api_url, headers=headers, data=json.dumps(payload))
31
+ response.raise_for_status() # Raise an exception for HTTP errors
32
+
33
+ result = response.json()
34
+
35
+ if result.get("candidates") and len(result["candidates"]) > 0 and \
36
+ result["candidates"][0].get("content") and \
37
+ result["candidates"][0]["content"].get("parts") and \
38
+ len(result["candidates"][0]["content"]["parts"]) > 0:
39
+ return result["candidates"][0]["content"]["parts"][0]["text"]
40
+ else:
41
+ return "No content generated by the model."
42
+ except requests.exceptions.RequestException as e:
43
+ return f"API Call Error: {e}"
44
+ except json.JSONDecodeError:
45
+ return f"API Response Error: Could not decode JSON. Response: {response.text}"
46
+ except Exception as e:
47
+ return f"An unexpected error occurred: {e}"
48
+
49
+ # --- Gradio Interface Function ---
50
+ async def analyze_chat_conversation(chat_text: str, analysis_task: str) -> str:
51
+ """
52
+ Analyzes the chat conversation based on the selected task using an LLM.
53
+ """
54
+ if not chat_text.strip():
55
+ return "Please enter a chat conversation to analyze."
56
+
57
+ prompt = ""
58
+ if analysis_task == "Summarize":
59
+ prompt = f"Summarize the following chat conversation:\n\n{chat_text}\n\nSummary:"
60
+ elif analysis_task == "Sentiment Analysis":
61
+ prompt = f"Analyze the overall sentiment of the following chat conversation (e.g., positive, negative, neutral, mixed). Explain your reasoning briefly:\n\n{chat_text}\n\nSentiment Analysis:"
62
+ elif analysis_task == "Extract Key Points & Action Items":
63
+ prompt = f"Extract the main discussion points and any explicit action items from the following chat conversation. Present them as a bulleted list:\n\n{chat_text}\n\nKey Points and Action Items:"
64
+ else:
65
+ return "Invalid analysis task selected."
66
+
67
+ # Call the Gemini API
68
+ response_text = await call_gemini_api(prompt)
69
+ return response_text
70
+
71
+ # --- Gradio Interface Definition ---
72
+ demo = gr.Interface(
73
+ fn=analyze_chat_conversation,
74
+ inputs=[
75
+ gr.Textbox(lines=10, label="Paste Chat Conversation Here", placeholder="e.g., 'Alice: Let's meet tomorrow. Bob: Sure, 10 AM? Alice: Yes, and please bring the report. Bob: Will do.'"),
76
+ gr.Dropdown(
77
+ ["Summarize", "Sentiment Analysis", "Extract Key Points & Action Items"],
78
+ label="Select Analysis Task",
79
+ value="Summarize"
80
+ )
81
+ ],
82
+ outputs=gr.Textbox(label="Analysis Result", lines=15),
83
+ title="💬 Chat Conversation Analyzer (Powered by Gemini)",
84
+ description="Paste your chat conversation, select an analysis task, and get insights from an AI."
85
+ )
86
+
87
+ # --- Launch the Gradio App ---
88
+ if __name__ == "__main__":
89
+ # For local testing, use demo.launch()
90
+ # For Hugging Face Spaces, ensure `gradio` and `requests` are in requirements.txt
91
+ demo.launch()