Spaces:
Sleeping
Sleeping
import os | |
import gradio as gr | |
import openai | |
from langdetect import detect | |
import json | |
import requests | |
# Set up OpenAI API with your custom endpoint | |
openai.api_key = os.getenv("API_KEY") | |
openai.api_base = "https://api.groq.com/openai/v1" | |
# Import datasets from the Python files in your project | |
from company_profile import company_profile | |
from workforce import workforce | |
from financials import financials | |
from investors import investors | |
from products_services import products_services | |
from market_trends import market_trends | |
from partnerships_collaborations import partnerships_collaborations | |
from legal_compliance import legal_compliance | |
from customer_insights import customer_insights | |
from news_updates import news_updates | |
from social_media import social_media | |
from tech_stack import tech_stack | |
# Command handler for specific queries | |
def command_handler(user_input): | |
if user_input.lower().startswith("define "): | |
term = user_input[7:].strip() | |
definitions = { | |
"market analysis": ( | |
"Market analysis evaluates a business's position by studying competitors, trends, and customer behavior. " | |
"It helps in crafting strategies for growth. 📊" | |
), | |
"financials": ( | |
"Financial analysis examines profit margins, revenues, and expenses to determine fiscal health and sustainability. 💵" | |
), | |
"investors": ( | |
"Investors provide capital in exchange for equity or debt, enabling business growth and scaling. 🏦" | |
) | |
} | |
return definitions.get(term.lower(), "Definition not available. Let’s dive into your query!") | |
return None | |
# Function to get the response from OpenAI with professionalism and energy | |
def get_groq_response(message, user_language, custom_data=None): | |
try: | |
# If custom data is available, include it in the AI prompt | |
if custom_data: | |
prompt = f"Use the following information for analysis: {custom_data}. Then answer the user's query: {message}" | |
else: | |
prompt = message | |
response = openai.ChatCompletion.create( | |
model="llama-3.3-70b-versatile", | |
messages=[ | |
{ | |
"role": "system", | |
"content": ( | |
f"You are a professional and concise Private Market Analyst AI. Your task is to explain market trends, " | |
f"company insights, and investment strategies in a clear, impactful, and concise manner. " | |
f"Keep the responses brief yet informative, focusing on the key points. Always maintain professionalism. " | |
f"1. **Accuracy**: Provide reliable, data-backed insights based on market trends, company profiles, and financial data.\n" | |
f"2. **Real-Time Updates**: Continuously track and update insights from the latest company developments, financial reports, and market movements.\n" | |
f"3. **Customizable**: Offer tailored responses based on user preferences such as specific industries, risk levels, and deal types.\n" | |
f"4. **Confidentiality**: Ensure that all information and insights provided remain secure and confidential, respecting user privacy.\n" | |
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" | |
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" | |
) | |
}, | |
{"role": "user", "content": prompt} | |
] | |
) | |
return response.choices[0].message["content"] | |
except Exception as e: | |
return f"Oops, looks like something went wrong! Error: {str(e)}" | |
# Function to format the response data in a readable and highlighted form | |
def format_response(data): | |
if not data: | |
return "No data available for this query." | |
formatted_response = "" | |
if isinstance(data, dict): | |
formatted_response += "### Key Insights:\n\n" | |
for key, value in data.items(): | |
if isinstance(value, dict): | |
# For nested dictionaries, add a heading for the sub-keys | |
formatted_response += f"**{key.capitalize()}**:\n" | |
for sub_key, sub_value in value.items(): | |
formatted_response += f" - **{sub_key.capitalize()}**: {sub_value}\n" | |
elif isinstance(value, list): | |
# If the value is a list, show it as a bullet-point list | |
formatted_response += f"**{key.capitalize()}**:\n" | |
for idx, item in enumerate(value): | |
formatted_response += f" - {item}\n" | |
else: | |
# For other types of data, simply display key-value pairs | |
formatted_response += f"**{key.capitalize()}**: {value}\n" | |
elif isinstance(data, list): | |
formatted_response += "### Insights:\n\n" + "\n".join(f"{idx+1}. {item}" for idx, item in enumerate(data)) | |
else: | |
formatted_response = f"### Key Insight:\n\n{data}" | |
return formatted_response.strip() | |
def market_analysis_agent(user_input, history=None): | |
if history is None: | |
history = [] # Initialize history if it's None | |
try: | |
detected_language = detect(user_input) | |
user_language = "Hindi" if detected_language == "hi" else "English" | |
command_response = command_handler(user_input) | |
if command_response: | |
history.append((user_input, command_response)) | |
return history, history | |
# Check if the query is related to cryptocurrency | |
if "bitcoin" in user_input.lower() or "crypto" in user_input.lower(): | |
# Trigger the fetch_crypto_trends function | |
crypto_data = fetch_crypto_trends(symbol="BTC", market="EUR", api_key="G3NRIAU5OWJZXS2E") | |
formatted_response = format_response(crypto_data) | |
else: | |
# Handle other predefined market queries | |
if "company" in user_input.lower(): | |
response = company_profile | |
elif "financials" in user_input.lower(): | |
response = financials | |
elif "investors" in user_input.lower(): | |
response = investors | |
elif "products" in user_input.lower(): | |
response = products_services | |
elif "news" in user_input.lower() or "updates" in user_input.lower(): | |
response = news_updates | |
elif "legal" in user_input.lower() or "compliance" in user_input.lower(): | |
response = legal_compliance | |
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(): | |
response = social_media | |
elif "workforce" in user_input.lower(): | |
response = workforce | |
else: | |
# Get dynamic AI response if query doesn't match predefined terms | |
response = get_groq_response(user_input, user_language, custom_data=json.dumps(company_profile)) | |
# Format the response for easy readability and highlighting | |
formatted_response = format_response(response) | |
# Add some professional and engaging replies for the user | |
cool_replies = [ | |
"Insightful observation. Let’s keep the momentum going. 📊", | |
"Good question! Let’s extract deeper business insights. 📈", | |
# Add your other cool replies here | |
] | |
formatted_response += f"\n{cool_replies[hash(user_input) % len(cool_replies)]}" | |
# Add to chat history | |
history.append((user_input, formatted_response)) | |
return history, history | |
except Exception as e: | |
return [(user_input, f"Oops, something went wrong: {str(e)}")], history | |
import requests | |
def fetch_crypto_trends(symbol="BTC", market="USD", api_key="G3NRIAU5OWJZXS2E"): | |
url = f'https://www.alphavantage.co/query?function=DIGITAL_CURRENCY_DAILY&symbol={symbol}&market={market}&apikey={api_key}' | |
try: | |
response = requests.get(url) | |
response.raise_for_status() # Raise an exception for HTTP errors | |
data = response.json() | |
# Check if the expected key exists in the response | |
time_series_key = "Time Series (Digital Currency Daily)" | |
if time_series_key in data: | |
trends = data[time_series_key] | |
latest_date = max(trends.keys()) # Get the most recent date | |
latest_data = trends[latest_date] | |
# Extract data based on the market-specific key format | |
return { | |
"date": latest_date, | |
"open": latest_data.get("1. open", "N/A"), | |
"high": latest_data.get("2. high", "N/A"), | |
"low": latest_data.get("3. low", "N/A"), | |
"close": latest_data.get("4. close", "N/A"), | |
"volume": latest_data.get("5. volume", "N/A"), | |
} | |
else: | |
return "No cryptocurrency data available. Check your API key or query parameters." | |
except Exception as e: | |
return f"Error fetching cryptocurrency trends: {str(e)}" | |
# Example usage | |
crypto_data = fetch_crypto_trends(symbol="BTC", market="EUR", api_key="G3NRIAU5OWJZXS2E") | |
print(crypto_data) | |
# Gradio Interface setup | |
chat_interface = gr.Interface( | |
fn=market_analysis_agent, # Function for handling user interaction | |
inputs=["text", "state"], # Inputs: user message and chat history | |
outputs=["chatbot", "state"], # Outputs: chatbot messages and updated history | |
live=False, # Disable live responses; show after submit | |
title="MarketLens AI Analyst", # Title of the app | |
description=( | |
"Welcome to the **MarketLens AI Analyst** by **Arpit Singh** 📊\n\n" | |
"This AI-powered tool provides actionable insights into market trends, company profiles, financial analysis, investors, and much more. " | |
"With a focus on simplicity, professionalism, and data-backed decision-making, it's designed to help you navigate complex market dynamics effortlessly. \n\n" | |
"**Key Features:**\n" | |
"- Secure, user-focused interactions with precision-driven insights.\n" | |
"- In-depth exploration of industries, financials, and market trends.\n\n" | |
"Let’s simplify market complexities and empower your decisions with clarity and innovation! 🔍" | |
), | |
allow_flagging="never", # Disable flagging to keep it professional | |
css=".gradio-container { max-width: 700px; margin: auto; }" # Center the content with a max-width for a neat appearance | |
) | |
# Launch the Gradio interface | |
if __name__ == "__main__": | |
chat_interface.launch(share=True) |