Chatbot / app.py
saherPervaiz's picture
Update app.py
e19314e verified
raw
history blame
4.91 kB
import os
import requests
import streamlit as st
from deep_translator import GoogleTranslator
import asyncio
# Ensure you have the correct API URL for Groq and the key is set
GROQ_API_URL = "https://api.groq.com/v1/completions" # Replace with the actual endpoint if different
API_KEY = os.environ.get("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")
if not API_KEY:
raise ValueError("API key is missing. Make sure to set the GROQ_API_KEY environment variable.")
# Function to get recommendations from Groq API based on user input
def get_opportunities(user_query):
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
payload = {
"model": "llama-3.3-70b-versatile", # Example model, replace with the actual model you want
"messages": [{"role": "user", "content": user_query}],
}
# Send the request to the Groq API
response = requests.post(GROQ_API_URL, json=payload, headers=headers)
if response.status_code == 200:
return response.json() # Adjust as per Groq's response format
else:
raise ValueError(f"Error fetching data from Groq API: {response.status_code}, {response.text}")
# Function to translate text into the selected language (async version)
async def translate_text(text, target_language):
translated = GoogleTranslator(source='auto', target=target_language).translate(text)
return translated
# Streamlit App Interface
st.set_page_config(page_title="AI-Powered Opportunity Finder", page_icon=":bulb:", layout="wide")
st.title("AI-Powered Opportunity Finder for Youth")
# Custom CSS for improving the UI
st.markdown("""
<style>
.css-1v0mbdj {padding-top: 30px; font-size: 1.5rem;}
.css-1wa3m6h {padding: 10px; background-color: #f0f0f5;}
.css-1w4t6pm {border: 1px solid #ccc; padding: 10px; background-color: #fff;}
.css-1f4y1re {font-size: 1.2rem;}
</style>
""", unsafe_allow_html=True)
# Sidebar for input fields
st.sidebar.header("Ask the AI Chatbot for Opportunities")
# Language selection
languages = {
"English": "en",
"Spanish": "es",
"French": "fr",
"German": "de",
"Italian": "it",
"Chinese": "zh",
"Japanese": "ja",
"Urdu": "ur"
}
selected_language = st.sidebar.selectbox("Select your preferred language:", list(languages.keys()))
# Chat history
if "messages" not in st.session_state:
st.session_state.messages = []
# Display chat history
for message in st.session_state.messages:
if message["role"] == "user":
st.markdown(f"**You:** {message['content']}")
else:
st.markdown(f"**AI:** {message['content']}")
# Input box for user query
user_query = st.text_input("Ask me about scholarships, internships, or online courses:")
# Button to send message to chatbot
if st.button("Send"):
if user_query:
# Append user query to chat history
st.session_state.messages.append({"role": "user", "content": user_query})
with st.spinner("Fetching opportunities..."):
try:
# Get the opportunity details based on user query
opportunities_response = get_opportunities(user_query)
# Extract the response content, modify based on actual response format
opportunities_text = opportunities_response.get("choices", [{}])[0].get("message", {}).get("content", "No data found.")
# Run the async translate function and get the translated text
translated_opportunities = asyncio.run(translate_text(opportunities_text, languages[selected_language]))
# Append AI response to chat history
st.session_state.messages.append({"role": "ai", "content": translated_opportunities})
except Exception as e:
st.error(f"Error: {e}")
# Scroll to the latest message
st.experimental_rerun()
else:
st.error("Please enter a query.")
# Add a footer with contact info and clickable links
st.markdown("""
<footer style="text-align:center; padding: 20px; font-size: 1rem; background-color: #f0f0f5;">
<p>Powered by Groq, Google Translate (deep-translator), and Streamlit</p>
<p>For more opportunities, visit:</p>
<ul style="list-style-type:none; padding: 0;">
<li><a href="https://www.groq.com" target="_blank">Groq - AI Solutions</a></li>
<li><a href="https://www.scholarships.com" target="_blank">Scholarships.com</a></li>
<li><a href="https://www.coursera.org" target="_blank">Coursera - Online Courses</a></li>
<li><a href="https://www.linkedin.com/jobs" target="_blank">LinkedIn Jobs</a></li>
</ul>
<p>Contact: [email protected]</p>
</footer>
""", unsafe_allow_html=True)