arpit13 commited on
Commit
fc7a024
·
verified ·
1 Parent(s): 3f4ebab

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +217 -0
app.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import openai
4
+ from langdetect import detect
5
+ import json
6
+ import requests
7
+
8
+ # Set up OpenAI API with your custom endpoint
9
+ openai.api_key = os.getenv("API_KEY")
10
+ openai.api_base = "https://api.groq.com/openai/v1"
11
+
12
+ # Import datasets from the Python files in your project
13
+ from company_profile import company_profile
14
+ from workforce import workforce
15
+ from financials import financials
16
+ from investors import investors
17
+ from products_services import products_services
18
+ from market_trends import market_trends
19
+ from partnerships_collaborations import partnerships_collaborations
20
+ from legal_compliance import legal_compliance
21
+ from customer_insights import customer_insights
22
+ from news_updates import news_updates
23
+ from social_media import social_media
24
+ from tech_stack import tech_stack
25
+
26
+ # Command handler for specific queries
27
+ def command_handler(user_input):
28
+ if user_input.lower().startswith("define "):
29
+ term = user_input[7:].strip()
30
+ definitions = {
31
+ "market analysis": (
32
+ "Market analysis evaluates a business's position by studying competitors, trends, and customer behavior. "
33
+ "It helps in crafting strategies for growth. 📊"
34
+ ),
35
+ "financials": (
36
+ "Financial analysis examines profit margins, revenues, and expenses to determine fiscal health and sustainability. 💵"
37
+ ),
38
+ "investors": (
39
+ "Investors provide capital in exchange for equity or debt, enabling business growth and scaling. 🏦"
40
+ )
41
+ }
42
+ return definitions.get(term.lower(), "Definition not available. Let’s dive into your query!")
43
+ return None
44
+
45
+ # Function to get the response from OpenAI with professionalism and energy
46
+ def get_groq_response(message, user_language, custom_data=None):
47
+ try:
48
+ # If custom data is available, include it in the AI prompt
49
+ if custom_data:
50
+ prompt = f"Use the following information for analysis: {custom_data}. Then answer the user's query: {message}"
51
+ else:
52
+ prompt = message
53
+
54
+ response = openai.ChatCompletion.create(
55
+ model="llama-3.1-70b-versatile",
56
+ messages=[
57
+ {
58
+ "role": "system",
59
+ "content": (
60
+ f"You are a professional and concise Private Market Analyst AI. Your task is to explain market trends, "
61
+ f"company insights, and investment strategies in a clear, impactful, and concise manner. "
62
+ f"Keep the responses brief yet informative, focusing on the key points. Always maintain professionalism. "
63
+ f"1. **Accuracy**: Provide reliable, data-backed insights based on market trends, company profiles, and financial data.\n"
64
+ f"2. **Real-Time Updates**: Continuously track and update insights from the latest company developments, financial reports, and market movements.\n"
65
+ f"3. **Customizable**: Offer tailored responses based on user preferences such as specific industries, risk levels, and deal types.\n"
66
+ f"4. **Confidentiality**: Ensure that all information and insights provided remain secure and confidential, respecting user privacy.\n"
67
+ f"5. **Explainability**: Provide clear, understandable, and actionable explanations for every AI-generated insight, ensuring users can easily follow the rationale behind the analysis.\n\n"
68
+ f"Your primary goal is to assist users by providing accurate, personalized, and actionable insights related to private markets. Always maintain professionalism and conciseness. Ensure that responses are easy to interpret, and avoid jargon whenever possible.\n\n"
69
+ )
70
+ },
71
+ {"role": "user", "content": prompt}
72
+ ]
73
+ )
74
+ return response.choices[0].message["content"]
75
+ except Exception as e:
76
+ return f"Oops, looks like something went wrong! Error: {str(e)}"
77
+
78
+ # Function to format the response data in a readable and highlighted form
79
+ def format_response(data):
80
+ if not data:
81
+ return "No data available for this query."
82
+
83
+ formatted_response = ""
84
+
85
+ if isinstance(data, dict):
86
+ formatted_response += "### Key Insights:\n\n"
87
+ for key, value in data.items():
88
+ if isinstance(value, dict):
89
+ # For nested dictionaries, add a heading for the sub-keys
90
+ formatted_response += f"**{key.capitalize()}**:\n"
91
+ for sub_key, sub_value in value.items():
92
+ formatted_response += f" - **{sub_key.capitalize()}**: {sub_value}\n"
93
+ elif isinstance(value, list):
94
+ # If the value is a list, show it as a bullet-point list
95
+ formatted_response += f"**{key.capitalize()}**:\n"
96
+ for idx, item in enumerate(value):
97
+ formatted_response += f" - {item}\n"
98
+ else:
99
+ # For other types of data, simply display key-value pairs
100
+ formatted_response += f"**{key.capitalize()}**: {value}\n"
101
+
102
+ elif isinstance(data, list):
103
+ formatted_response += "### Insights:\n\n" + "\n".join(f"{idx+1}. {item}" for idx, item in enumerate(data))
104
+ else:
105
+ formatted_response = f"### Key Insight:\n\n{data}"
106
+
107
+ return formatted_response.strip()
108
+
109
+ def market_analysis_agent(user_input, history=[]):
110
+ try:
111
+ # Detect the language of the user's input
112
+ detected_language = detect(user_input)
113
+ user_language = "Hindi" if detected_language == "hi" else "English"
114
+
115
+ # Handle special commands like "Define [term]"
116
+ command_response = command_handler(user_input)
117
+ if command_response:
118
+ history.append((user_input, command_response))
119
+ return history, history
120
+
121
+ # Check if the query is related to cryptocurrency
122
+ if "bitcoin" in user_input.lower() or "crypto" in user_input.lower():
123
+ # Trigger the fetch_crypto_trends function
124
+ crypto_data = fetch_crypto_trends(symbol="BTC", market="EUR", api_key="G3NRIAU5OWJZXS2E")
125
+ formatted_response = format_response(crypto_data)
126
+ else:
127
+ # Handle other predefined market queries
128
+ if "company" in user_input.lower():
129
+ response = company_profile
130
+ elif "financials" in user_input.lower():
131
+ response = financials
132
+ elif "investors" in user_input.lower():
133
+ response = investors
134
+ elif "products" in user_input.lower():
135
+ response = products_services
136
+ elif "news" in user_input.lower() or "updates" in user_input.lower():
137
+ response = news_updates
138
+ elif "legal" in user_input.lower() or "compliance" in user_input.lower():
139
+ response = legal_compliance
140
+ elif "social media" in user_input.lower() or "instagram" in user_input.lower() or "linkedin" in user_input.lower() or "twitter" in user_input.lower():
141
+ response = social_media
142
+ elif "workforce" in user_input.lower():
143
+ response = workforce
144
+ else:
145
+ # Get dynamic AI response if query doesn't match predefined terms
146
+ response = get_groq_response(user_input, user_language, custom_data=json.dumps(company_profile))
147
+ # Format the response for easy readability and highlighting
148
+ formatted_response = format_response(response)
149
+
150
+ # Add some professional and engaging replies for the user
151
+ cool_replies = [
152
+ "Insightful observation. Let’s keep the momentum going. 📊",
153
+ "Good question! Let’s extract deeper business insights. 📈",
154
+ # Add your other cool replies here
155
+ ]
156
+ formatted_response += f"\n{cool_replies[hash(user_input) % len(cool_replies)]}"
157
+
158
+ # Add to chat history
159
+ history.append((user_input, formatted_response))
160
+ return history, history
161
+
162
+ except Exception as e:
163
+ return [(user_input, f"Oops, something went wrong: {str(e)}")], history
164
+
165
+ import requests
166
+
167
+ def fetch_crypto_trends(symbol="BTC", market="USD", api_key="G3NRIAU5OWJZXS2E"):
168
+ url = f'https://www.alphavantage.co/query?function=DIGITAL_CURRENCY_DAILY&symbol={symbol}&market={market}&apikey={api_key}'
169
+ try:
170
+ response = requests.get(url)
171
+ response.raise_for_status() # Raise an exception for HTTP errors
172
+ data = response.json()
173
+
174
+ # Check if the expected key exists in the response
175
+ time_series_key = "Time Series (Digital Currency Daily)"
176
+ if time_series_key in data:
177
+ trends = data[time_series_key]
178
+ latest_date = max(trends.keys()) # Get the most recent date
179
+ latest_data = trends[latest_date]
180
+
181
+ # Extract data based on the market-specific key format
182
+ return {
183
+ "date": latest_date,
184
+ "open": latest_data.get("1. open", "N/A"),
185
+ "high": latest_data.get("2. high", "N/A"),
186
+ "low": latest_data.get("3. low", "N/A"),
187
+ "close": latest_data.get("4. close", "N/A"),
188
+ "volume": latest_data.get("5. volume", "N/A"),
189
+ }
190
+ else:
191
+ return "No cryptocurrency data available. Check your API key or query parameters."
192
+ except Exception as e:
193
+ return f"Error fetching cryptocurrency trends: {str(e)}"
194
+
195
+ # Example usage
196
+ crypto_data = fetch_crypto_trends(symbol="BTC", market="EUR", api_key="G3NRIAU5OWJZXS2E")
197
+ print(crypto_data)
198
+ # Gradio Interface setup
199
+ chat_interface = gr.Interface(
200
+ fn=market_analysis_agent, # Function for handling user interaction
201
+ inputs=["text", "state"], # Inputs: user message and chat history
202
+ outputs=["chatbot", "state"], # Outputs: chatbot messages and updated history
203
+ live=False, # Disable live responses; show after submit
204
+ title="Private Market AI Agent", # Title of the app
205
+ description=(
206
+ "Welcome to your professional Private Market Analyst AI Agent by Satyam! 📊\n\n"
207
+ "Ask me anything about market trends, company profiles, financial analysis, investors, and more! "
208
+ "I’ll provide you with concise insights that are informative and to the point, helping you make well-informed decisions. \n\n"
209
+ "Let's break down market complexities with clarity. 🔍\n\n"
210
+ "We Transform Data into Deal"
211
+
212
+ )
213
+ )
214
+
215
+ # Launch the Gradio interface
216
+ if __name__ == "__main__":
217
+ chat_interface.launch(share=True)