Student3331 commited on
Commit
f421511
·
verified ·
1 Parent(s): 9dd5d7b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +136 -0
app.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import streamlit as st
3
+ import wikipediaapi
4
+ import random
5
+ from dotenv import load_dotenv
6
+ from groq import Groq
7
+
8
+ # Load environment variables from the .env file
9
+ load_dotenv()
10
+
11
+ # Now the environment variable can be accessed
12
+ api_key = os.getenv("GROQ_API_KEY")
13
+ if api_key is None:
14
+ raise ValueError("GROQ_API_KEY is not set. Please set the environment variable.")
15
+
16
+ # Initialize Groq API client using the API key
17
+ client = Groq(api_key=api_key)
18
+
19
+ # Initialize Wikipedia API with a user agent
20
+ wiki_wiki = wikipediaapi.Wikipedia(
21
+ language='en',
22
+ user_agent='StudyHelperApp/1.0 (https://yourwebsite.com; your-email@example.com)'
23
+ )
24
+
25
+ # Function to fetch the summary of a Wikipedia article
26
+ def fetch_summary(topic):
27
+ """Fetches the summary of a Wikipedia article."""
28
+ page = wiki_wiki.page(topic)
29
+ if page.exists():
30
+ return page.summary
31
+ else:
32
+ return f"The topic '{topic}' does not exist on Wikipedia. Please try another one or check for typos."
33
+
34
+ # Function to fetch the summary of a Wikipedia article with links
35
+ def fetch_summary_with_links(topic):
36
+ """Fetches the summary of a Wikipedia article and provides a link for further reading."""
37
+ page = wiki_wiki.page(topic)
38
+ if page.exists():
39
+ summary = page.summary
40
+ url = page.fullurl # Get the full URL of the Wikipedia page
41
+ return summary, url
42
+ else:
43
+ return "This topic does not exist on Wikipedia. Please try another one.", ""
44
+
45
+ # Function to fetch related topics based on the topic
46
+ def display_relationships(topic):
47
+ """Displays related topics (expanding the database)."""
48
+ related_topics = {
49
+ "Physics": ["Quantum Mechanics", "Thermodynamics", "Relativity", "Electromagnetism", "Classical Mechanics"],
50
+ "Mathematics": ["Algebra", "Calculus", "Geometry", "Statistics", "Linear Algebra"],
51
+ "Biology": ["Genetics", "Evolution", "Cell Theory", "Ecology", "Human Anatomy"],
52
+ "Computer Science": ["Artificial Intelligence", "Machine Learning", "Data Structures", "Algorithms", "Cybersecurity"],
53
+ "Chemistry": ["Organic Chemistry", "Inorganic Chemistry", "Physical Chemistry", "Biochemistry"],
54
+ "History": ["Ancient Civilizations", "World Wars", "Modern History", "Political History", "Cultural History"],
55
+ "Art": ["Impressionism", "Renaissance", "Cubism", "Abstract Art", "Surrealism"],
56
+ "Psychology": ["Cognitive Psychology", "Behaviorism", "Neuroscience", "Social Psychology", "Developmental Psychology"],
57
+ "Economics": ["Microeconomics", "Macroeconomics", "International Trade", "Economic Theories", "Economic Policy"],
58
+ "Philosophy": ["Metaphysics", "Ethics", "Logic", "Epistemology", "Political Philosophy"],
59
+ "Music Theory": ["Scales", "Chords", "Harmony", "Rhythm", "Counterpoint"]
60
+ }
61
+ return related_topics.get(topic, ["No related topics found."])
62
+
63
+ # Function to suggest random topics
64
+ def suggest_topics():
65
+ """Suggests a random list of topics."""
66
+ all_topics = [
67
+ "Physics", "Mathematics", "Biology", "Computer Science", "Chemistry",
68
+ "History", "Art", "Psychology", "Economics", "Philosophy", "Music Theory"
69
+ ]
70
+ return random.sample(all_topics, 3) # Suggest 3 random topics
71
+
72
+ # Function to fetch a random Wikipedia topic
73
+ def random_topic():
74
+ """Fetches a random Wikipedia topic."""
75
+ random_topics = ["Physics", "Mathematics", "Biology", "Computer Science", "Chemistry"]
76
+ return random.choice(random_topics)
77
+
78
+ # Function to query Groq for a detailed explanation
79
+ def query_groq(question):
80
+ """Queries the Groq API to generate a response for a given question."""
81
+ try:
82
+ chat_completion = client.chat.completions.create(
83
+ messages=[{
84
+ "role": "user",
85
+ "content": question,
86
+ }],
87
+ model="llama3-8b-8192",
88
+ )
89
+ return chat_completion.choices[0].message.content
90
+ except Exception as e:
91
+ return f"Error querying Groq: {str(e)}"
92
+
93
+ # Streamlit app structure
94
+ st.title("Study Helper Chatbot")
95
+ st.write("Welcome to the Study Helper Chatbot! Type 'exit' to quit.")
96
+
97
+ # Create text input for topic query
98
+ topic = st.text_input("Enter a topic to learn about:")
99
+
100
+ if topic:
101
+ if topic.lower() == 'exit':
102
+ st.write("Goodbye! Happy studying!")
103
+ elif topic.lower() == 'suggest':
104
+ st.write("\nHere are some topic suggestions:")
105
+ suggestions = suggest_topics()
106
+ for s in suggestions:
107
+ st.write(f"- {s}")
108
+ elif topic.lower() == 'random':
109
+ random_topic_name = random_topic()
110
+ st.write(f"\nHere’s a random topic: {random_topic_name}")
111
+ summary, url = fetch_summary_with_links(random_topic_name)
112
+ st.write("## Summary:")
113
+ st.write(summary)
114
+ if url:
115
+ st.write(f"For more detailed information, visit: {url}")
116
+ else:
117
+ # Fetch summary and related link
118
+ summary, url = fetch_summary_with_links(topic)
119
+ st.write("## Summary:")
120
+ st.write(summary)
121
+
122
+ if url:
123
+ st.write(f"\nFor more detailed information, visit: {url}")
124
+
125
+ # Fetch and display related topics
126
+ related = display_relationships(topic)
127
+ st.write("\n## Related Topics:")
128
+ for related_topic in related:
129
+ st.write(f"- {related_topic}")
130
+
131
+ # Optionally, ask the user if they want a Groq explanation
132
+ if st.button("Get Groq Explanation for This Topic"):
133
+ groq_question = f"Explain the importance of {topic}."
134
+ groq_response = query_groq(groq_question)
135
+ st.write("\n## Groq Explanation:")
136
+ st.write(groq_response)