Spaces:
Build error
Build error
Download app.py from Student3331/chatbot: direct link, hf CLI and curl.
- Browser
- Download file 5.65 kB
-
https://huggingface.co/spaces/Student3331/chatbot/resolve/main/app.py
- Command line
-
hf download hf://spaces/Student3331/chatbot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Student3331/chatbot/resolve/main/app.py
5.65 kB
| import os | |
| import streamlit as st | |
| import wikipediaapi | |
| import random | |
| from dotenv import load_dotenv | |
| from groq import Groq | |
| # Load environment variables from the .env file | |
| load_dotenv() | |
| # Now the environment variable can be accessed | |
| api_key = os.getenv("GROQ_API_KEY") | |
| if api_key is None: | |
| raise ValueError("GROQ_API_KEY is not set. Please set the environment variable.") | |
| # Initialize Groq API client using the API key | |
| client = Groq(api_key=api_key) | |
| # Initialize Wikipedia API with a user agent | |
| wiki_wiki = wikipediaapi.Wikipedia( | |
| language='en', | |
| user_agent='StudyHelperApp/1.0 (https://yourwebsite.com; your-email@example.com)' | |
| ) | |
| # Function to fetch the summary of a Wikipedia article | |
| def fetch_summary(topic): | |
| """Fetches the summary of a Wikipedia article.""" | |
| page = wiki_wiki.page(topic) | |
| if page.exists(): | |
| return page.summary | |
| else: | |
| return f"The topic '{topic}' does not exist on Wikipedia. Please try another one or check for typos." | |
| # Function to fetch the summary of a Wikipedia article with links | |
| def fetch_summary_with_links(topic): | |
| """Fetches the summary of a Wikipedia article and provides a link for further reading.""" | |
| page = wiki_wiki.page(topic) | |
| if page.exists(): | |
| summary = page.summary | |
| url = page.fullurl # Get the full URL of the Wikipedia page | |
| return summary, url | |
| else: | |
| return "This topic does not exist on Wikipedia. Please try another one.", "" | |
| # Function to fetch related topics based on the topic | |
| def display_relationships(topic): | |
| """Displays related topics (expanding the database).""" | |
| related_topics = { | |
| "Physics": ["Quantum Mechanics", "Thermodynamics", "Relativity", "Electromagnetism", "Classical Mechanics"], | |
| "Mathematics": ["Algebra", "Calculus", "Geometry", "Statistics", "Linear Algebra"], | |
| "Biology": ["Genetics", "Evolution", "Cell Theory", "Ecology", "Human Anatomy"], | |
| "Computer Science": ["Artificial Intelligence", "Machine Learning", "Data Structures", "Algorithms", "Cybersecurity"], | |
| "Chemistry": ["Organic Chemistry", "Inorganic Chemistry", "Physical Chemistry", "Biochemistry"], | |
| "History": ["Ancient Civilizations", "World Wars", "Modern History", "Political History", "Cultural History"], | |
| "Art": ["Impressionism", "Renaissance", "Cubism", "Abstract Art", "Surrealism"], | |
| "Psychology": ["Cognitive Psychology", "Behaviorism", "Neuroscience", "Social Psychology", "Developmental Psychology"], | |
| "Economics": ["Microeconomics", "Macroeconomics", "International Trade", "Economic Theories", "Economic Policy"], | |
| "Philosophy": ["Metaphysics", "Ethics", "Logic", "Epistemology", "Political Philosophy"], | |
| "Music Theory": ["Scales", "Chords", "Harmony", "Rhythm", "Counterpoint"] | |
| } | |
| return related_topics.get(topic, ["No related topics found."]) | |
| # Function to suggest random topics | |
| def suggest_topics(): | |
| """Suggests a random list of topics.""" | |
| all_topics = [ | |
| "Physics", "Mathematics", "Biology", "Computer Science", "Chemistry", | |
| "History", "Art", "Psychology", "Economics", "Philosophy", "Music Theory" | |
| ] | |
| return random.sample(all_topics, 3) # Suggest 3 random topics | |
| # Function to fetch a random Wikipedia topic | |
| def random_topic(): | |
| """Fetches a random Wikipedia topic.""" | |
| random_topics = ["Physics", "Mathematics", "Biology", "Computer Science", "Chemistry"] | |
| return random.choice(random_topics) | |
| # Function to query Groq for a detailed explanation | |
| def query_groq(question): | |
| """Queries the Groq API to generate a response for a given question.""" | |
| try: | |
| chat_completion = client.chat.completions.create( | |
| messages=[{ | |
| "role": "user", | |
| "content": question, | |
| }], | |
| model="llama3-8b-8192", | |
| ) | |
| return chat_completion.choices[0].message.content | |
| except Exception as e: | |
| return f"Error querying Groq: {str(e)}" | |
| # Streamlit app structure | |
| st.title("Study Helper Chatbot") | |
| st.write("Welcome to the Study Helper Chatbot! Type 'exit' to quit.") | |
| # Create text input for topic query | |
| topic = st.text_input("Enter a topic to learn about:") | |
| if topic: | |
| if topic.lower() == 'exit': | |
| st.write("Goodbye! Happy studying!") | |
| elif topic.lower() == 'suggest': | |
| st.write("\nHere are some topic suggestions:") | |
| suggestions = suggest_topics() | |
| for s in suggestions: | |
| st.write(f"- {s}") | |
| elif topic.lower() == 'random': | |
| random_topic_name = random_topic() | |
| st.write(f"\nHere’s a random topic: {random_topic_name}") | |
| summary, url = fetch_summary_with_links(random_topic_name) | |
| st.write("## Summary:") | |
| st.write(summary) | |
| if url: | |
| st.write(f"For more detailed information, visit: {url}") | |
| else: | |
| # Fetch summary and related link | |
| summary, url = fetch_summary_with_links(topic) | |
| st.write("## Summary:") | |
| st.write(summary) | |
| if url: | |
| st.write(f"\nFor more detailed information, visit: {url}") | |
| # Fetch and display related topics | |
| related = display_relationships(topic) | |
| st.write("\n## Related Topics:") | |
| for related_topic in related: | |
| st.write(f"- {related_topic}") | |
| # Optionally, ask the user if they want a Groq explanation | |
| if st.button("Get Groq Explanation for This Topic"): | |
| groq_question = f"Explain the importance of {topic}." | |
| groq_response = query_groq(groq_question) | |
| st.write("\n## Groq Explanation:") | |
| st.write(groq_response) | |