shaheerawan3 commited on
Commit
2cb5adc
·
verified ·
1 Parent(s): 17f7808

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -142
app.py CHANGED
@@ -1,13 +1,57 @@
1
- # scraper.py
2
- import requests
3
- from bs4 import BeautifulSoup
4
  import random
5
  import json
6
  from pathlib import Path
 
 
7
  import time
8
- from transformers import pipeline
9
  from fake_useragent import UserAgent
10
- import pandas as pd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
  class QuoteScraper:
13
  def __init__(self):
@@ -49,64 +93,24 @@ class QuoteScraper:
49
  print(f"Error scraping BrainyQuote: {e}")
50
  return quotes
51
 
52
- class QuoteGenerator:
53
- def __init__(self):
54
- self.generator = pipeline('text-generation', model='gpt2')
55
-
56
- def generate_quote(self, category, max_length=100):
57
- prompts = {
58
- 'motivation': f"Here's an inspiring quote about success and motivation:",
59
- 'wisdom': f"Here's a profound quote about life and wisdom:",
60
- 'spiritual': f"Here's a deep spiritual teaching:",
61
- 'philosophy': f"Here's a philosophical insight about existence:",
62
- }
63
-
64
- prompt = prompts.get(category, f"Here's a quote about {category}:")
65
-
66
- try:
67
- generated_text = self.generator(prompt, max_length=max_length, num_return_sequences=1)[0]['generated_text']
68
- # Extract the quote part after the prompt
69
- quote = generated_text.split(':')[1].strip()
70
- return quote
71
- except Exception as e:
72
- print(f"Error generating quote: {e}")
73
- return None
74
-
75
- # app.py
76
- import streamlit as st
77
- import firebase_admin
78
- from firebase_admin import credentials, auth, firestore
79
- import hashlib
80
- from datetime import datetime, timedelta
81
- import pytz
82
- import base64
83
- from io import BytesIO
84
-
85
- # Initialize Firebase (in production, use environment variables)
86
- if not firebase_admin._apps:
87
- cred = credentials.Certificate("path/to/serviceAccountKey.json")
88
- firebase_admin.initialize_app(cred)
89
-
90
- db = firestore.client()
91
-
92
- def init_session_state():
93
- if 'user' not in st.session_state:
94
- st.session_state.user = None
95
- if 'favorites' not in st.session_state:
96
- st.session_state.favorites = []
97
-
98
  class QuoteManager:
99
  def __init__(self):
100
  self.scraper = QuoteScraper()
101
- self.generator = QuoteGenerator()
102
  self.quotes_file = Path('enhanced_quotes.json')
 
103
  self.categories = [
104
  'motivation', 'wisdom', 'spiritual', 'philosophy', 'success',
105
  'love', 'life', 'happiness', 'science', 'education', 'leadership',
106
  'buddhist', 'christian', 'islamic', 'hindu', 'jewish',
107
  'native-american', 'african', 'asian', 'european'
108
  ]
 
109
 
 
 
 
 
 
110
  def update_quotes_database(self):
111
  quotes_data = {}
112
 
@@ -115,13 +119,6 @@ class QuoteManager:
115
  # Scrape from multiple sources
116
  quotes.extend(self.scraper.scrape_goodreads(category))
117
  quotes.extend(self.scraper.scrape_brainyquote(category))
118
-
119
- # Generate AI quotes
120
- for _ in range(5): # Generate 5 AI quotes per category
121
- ai_quote = self.generator.generate_quote(category)
122
- if ai_quote:
123
- quotes.append(f"{ai_quote} [AI Generated]")
124
-
125
  quotes_data[category] = list(set(quotes)) # Remove duplicates
126
 
127
  with open(self.quotes_file, 'w', encoding='utf-8') as f:
@@ -135,29 +132,37 @@ class QuoteManager:
135
 
136
  with open(self.quotes_file, 'r', encoding='utf-8') as f:
137
  return json.load(f)
138
-
139
- class UserAuth:
140
- @staticmethod
141
- def signup(email, password):
142
- try:
143
- user = auth.create_user(
144
- email=email,
145
- password=password
146
- )
147
- return user
148
- except Exception as e:
149
- st.error(f"Error signing up: {e}")
150
- return None
151
-
152
- @staticmethod
153
- def login(email, password):
154
- try:
155
- user = auth.get_user_by_email(email)
156
- # In production, use proper password verification
157
- return user
158
- except Exception as e:
159
- st.error(f"Error logging in: {e}")
160
- return None
 
 
 
 
 
 
 
 
161
 
162
  def main():
163
  st.set_page_config(
@@ -166,17 +171,18 @@ def main():
166
  layout="wide"
167
  )
168
 
169
- # Initialize session state and managers
170
- init_session_state()
171
  quote_manager = QuoteManager()
172
- quotes_data = quote_manager.load_quotes()
 
 
 
173
 
174
- # Custom CSS with enhanced styling
175
  st.markdown("""
176
  <style>
177
- .main {
178
- padding: 2rem;
179
- }
180
  .stButton button {
181
  width: 100%;
182
  border-radius: 20px;
@@ -217,21 +223,24 @@ def main():
217
  email = st.text_input("Email")
218
  password = st.text_input("Password", type="password")
219
  if st.button("Login"):
220
- user = UserAuth.login(email, password)
221
- if user:
222
- st.session_state.user = user
223
- st.success("Logged in successfully!")
224
  st.rerun()
225
-
 
226
  else:
227
  email = st.text_input("Email")
228
  password = st.text_input("Password", type="password")
229
  if st.button("Sign Up"):
230
- user = UserAuth.signup(email, password)
231
- if user:
232
- st.success("Account created successfully!")
 
 
233
  else:
234
- st.write(f"Welcome, {st.session_state.user.email}")
235
  if st.button("Logout"):
236
  st.session_state.user = None
237
  st.rerun()
@@ -241,6 +250,9 @@ def main():
241
  ["Home", "Quote Generator", "Browse Categories", "Search Quotes", "My Favorites"]
242
  )
243
 
 
 
 
244
  if menu == "Home":
245
  st.title("Welcome to Global QuoteVerse")
246
  st.markdown("### Discover Wisdom From All Cultures")
@@ -263,37 +275,21 @@ def main():
263
  elif menu == "Quote Generator":
264
  st.title("Generate Custom Quotes")
265
 
266
- col1, col2 = st.columns(2)
267
- with col1:
268
- category = st.selectbox("Select Category", quote_manager.categories)
269
- with col2:
270
- source = st.selectbox("Select Source", ["All", "Web Scraped", "AI Generated"])
271
 
272
  if st.button("Generate Quote"):
273
- quotes = quotes_data[category]
274
- if source == "AI Generated":
275
- quotes = [q for q in quotes if "[AI Generated]" in q]
276
- elif source == "Web Scraped":
277
- quotes = [q for q in quotes if "[AI Generated]" not in q]
278
-
279
- if quotes:
280
- quote = random.choice(quotes)
281
- st.markdown(f"""
282
- <div class='quote-box'>
283
- <p>{quote}</p>
284
- <div class='category-tag'>{category}</div>
285
- </div>
286
- """, unsafe_allow_html=True)
287
-
288
- if st.session_state.user:
289
- if st.button("Add to Favorites"):
290
- db.collection('favorites').add({
291
- 'user_id': st.session_state.user.uid,
292
- 'quote': quote,
293
- 'category': category,
294
- 'timestamp': datetime.now(pytz.UTC)
295
- })
296
- st.success("Added to favorites!")
297
 
298
  elif menu == "Search Quotes":
299
  st.title("Search Quotes")
@@ -325,30 +321,25 @@ def main():
325
  else:
326
  st.title("My Favorite Quotes")
327
 
328
- favorites_ref = db.collection('favorites').where(
329
- 'user_id', '==', st.session_state.user.uid
330
- ).order_by('timestamp', direction=firestore.Query.DESCENDING)
331
-
332
- favorites = favorites_ref.get()
333
 
334
- for fav in favorites:
335
- data = fav.to_dict()
336
  st.markdown(f"""
337
  <div class='quote-box'>
338
- <p>{data['quote']}</p>
339
- <div class='category-tag'>{data['category']}</div>
340
  </div>
341
  """, unsafe_allow_html=True)
342
 
343
  col1, col2 = st.columns(2)
344
  with col1:
345
- if st.button(f"Share {fav.id}", key=f"share_{fav.id}"):
346
- # Generate shareable link
347
- share_url = f"https://yourapp.com/quote/{fav.id}"
348
- st.code(share_url)
349
  with col2:
350
- if st.button(f"Remove {fav.id}", key=f"remove_{fav.id}"):
351
- db.collection('favorites').document(fav.id).delete()
352
  st.success("Removed from favorites!")
353
  st.rerun()
354
 
 
1
+ import streamlit as st
 
 
2
  import random
3
  import json
4
  from pathlib import Path
5
+ import requests
6
+ from bs4 import BeautifulSoup
7
  import time
 
8
  from fake_useragent import UserAgent
9
+ import hashlib
10
+ from datetime import datetime
11
+ import pytz
12
+
13
+ class SimpleAuth:
14
+ def __init__(self):
15
+ self.users_file = Path('users.json')
16
+ self.init_users_db()
17
+
18
+ def init_users_db(self):
19
+ if not self.users_file.exists():
20
+ with open(self.users_file, 'w') as f:
21
+ json.dump({'users': {}}, f)
22
+
23
+ def get_users(self):
24
+ with open(self.users_file, 'r') as f:
25
+ return json.load(f)
26
+
27
+ def save_users(self, users_data):
28
+ with open(self.users_file, 'w') as f:
29
+ json.dump(users_data, f)
30
+
31
+ def hash_password(self, password):
32
+ return hashlib.sha256(password.encode()).hexdigest()
33
+
34
+ def signup(self, email, password):
35
+ users_data = self.get_users()
36
+ if email in users_data['users']:
37
+ return False, "Email already exists"
38
+
39
+ users_data['users'][email] = {
40
+ 'password': self.hash_password(password),
41
+ 'favorites': []
42
+ }
43
+ self.save_users(users_data)
44
+ return True, "Signup successful"
45
+
46
+ def login(self, email, password):
47
+ users_data = self.get_users()
48
+ if email not in users_data['users']:
49
+ return False, "Email not found"
50
+
51
+ if users_data['users'][email]['password'] != self.hash_password(password):
52
+ return False, "Invalid password"
53
+
54
+ return True, "Login successful"
55
 
56
  class QuoteScraper:
57
  def __init__(self):
 
93
  print(f"Error scraping BrainyQuote: {e}")
94
  return quotes
95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  class QuoteManager:
97
  def __init__(self):
98
  self.scraper = QuoteScraper()
 
99
  self.quotes_file = Path('enhanced_quotes.json')
100
+ self.favorites_file = Path('favorites.json')
101
  self.categories = [
102
  'motivation', 'wisdom', 'spiritual', 'philosophy', 'success',
103
  'love', 'life', 'happiness', 'science', 'education', 'leadership',
104
  'buddhist', 'christian', 'islamic', 'hindu', 'jewish',
105
  'native-american', 'african', 'asian', 'european'
106
  ]
107
+ self.init_favorites_db()
108
 
109
+ def init_favorites_db(self):
110
+ if not self.favorites_file.exists():
111
+ with open(self.favorites_file, 'w') as f:
112
+ json.dump({}, f)
113
+
114
  def update_quotes_database(self):
115
  quotes_data = {}
116
 
 
119
  # Scrape from multiple sources
120
  quotes.extend(self.scraper.scrape_goodreads(category))
121
  quotes.extend(self.scraper.scrape_brainyquote(category))
 
 
 
 
 
 
 
122
  quotes_data[category] = list(set(quotes)) # Remove duplicates
123
 
124
  with open(self.quotes_file, 'w', encoding='utf-8') as f:
 
132
 
133
  with open(self.quotes_file, 'r', encoding='utf-8') as f:
134
  return json.load(f)
135
+
136
+ def add_to_favorites(self, email, quote, category):
137
+ with open(self.favorites_file, 'r') as f:
138
+ favorites = json.load(f)
139
+
140
+ if email not in favorites:
141
+ favorites[email] = []
142
+
143
+ favorites[email].append({
144
+ 'quote': quote,
145
+ 'category': category,
146
+ 'timestamp': datetime.now(pytz.UTC).isoformat()
147
+ })
148
+
149
+ with open(self.favorites_file, 'w') as f:
150
+ json.dump(favorites, f)
151
+
152
+ def get_favorites(self, email):
153
+ with open(self.favorites_file, 'r') as f:
154
+ favorites = json.load(f)
155
+ return favorites.get(email, [])
156
+
157
+ def remove_favorite(self, email, quote):
158
+ with open(self.favorites_file, 'r') as f:
159
+ favorites = json.load(f)
160
+
161
+ if email in favorites:
162
+ favorites[email] = [f for f in favorites[email] if f['quote'] != quote]
163
+
164
+ with open(self.favorites_file, 'w') as f:
165
+ json.dump(favorites, f)
166
 
167
  def main():
168
  st.set_page_config(
 
171
  layout="wide"
172
  )
173
 
174
+ # Initialize managers
175
+ auth_manager = SimpleAuth()
176
  quote_manager = QuoteManager()
177
+
178
+ # Initialize session state
179
+ if 'user' not in st.session_state:
180
+ st.session_state.user = None
181
 
182
+ # Custom CSS (same as before)
183
  st.markdown("""
184
  <style>
185
+ .main { padding: 2rem; }
 
 
186
  .stButton button {
187
  width: 100%;
188
  border-radius: 20px;
 
223
  email = st.text_input("Email")
224
  password = st.text_input("Password", type="password")
225
  if st.button("Login"):
226
+ success, message = auth_manager.login(email, password)
227
+ if success:
228
+ st.session_state.user = email
229
+ st.success(message)
230
  st.rerun()
231
+ else:
232
+ st.error(message)
233
  else:
234
  email = st.text_input("Email")
235
  password = st.text_input("Password", type="password")
236
  if st.button("Sign Up"):
237
+ success, message = auth_manager.signup(email, password)
238
+ if success:
239
+ st.success(message)
240
+ else:
241
+ st.error(message)
242
  else:
243
+ st.write(f"Welcome, {st.session_state.user}")
244
  if st.button("Logout"):
245
  st.session_state.user = None
246
  st.rerun()
 
250
  ["Home", "Quote Generator", "Browse Categories", "Search Quotes", "My Favorites"]
251
  )
252
 
253
+ # Load quotes
254
+ quotes_data = quote_manager.load_quotes()
255
+
256
  if menu == "Home":
257
  st.title("Welcome to Global QuoteVerse")
258
  st.markdown("### Discover Wisdom From All Cultures")
 
275
  elif menu == "Quote Generator":
276
  st.title("Generate Custom Quotes")
277
 
278
+ category = st.selectbox("Select Category", quote_manager.categories)
 
 
 
 
279
 
280
  if st.button("Generate Quote"):
281
+ quote = random.choice(quotes_data[category])
282
+ st.markdown(f"""
283
+ <div class='quote-box'>
284
+ <p>{quote}</p>
285
+ <div class='category-tag'>{category}</div>
286
+ </div>
287
+ """, unsafe_allow_html=True)
288
+
289
+ if st.session_state.user:
290
+ if st.button("Add to Favorites"):
291
+ quote_manager.add_to_favorites(st.session_state.user, quote, category)
292
+ st.success("Added to favorites!")
 
 
 
 
 
 
 
 
 
 
 
 
293
 
294
  elif menu == "Search Quotes":
295
  st.title("Search Quotes")
 
321
  else:
322
  st.title("My Favorite Quotes")
323
 
324
+ favorites = quote_manager.get_favorites(st.session_state.user)
 
 
 
 
325
 
326
+ for idx, fav in enumerate(favorites):
 
327
  st.markdown(f"""
328
  <div class='quote-box'>
329
+ <p>{fav['quote']}</p>
330
+ <div class='category-tag'>{fav['category']}</div>
331
  </div>
332
  """, unsafe_allow_html=True)
333
 
334
  col1, col2 = st.columns(2)
335
  with col1:
336
+ if st.button(f"Share", key=f"share_{idx}"):
337
+ # Generate shareable text
338
+ share_text = f""{fav['quote']}" - via Global QuoteVerse"
339
+ st.code(share_text)
340
  with col2:
341
+ if st.button(f"Remove", key=f"remove_{idx}"):
342
+ quote_manager.remove_favorite(st.session_state.user, fav['quote'])
343
  st.success("Removed from favorites!")
344
  st.rerun()
345