Bahawal Ali commited on
Commit
027076c
Β·
verified Β·
1 Parent(s): b58e2a1

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +48 -51
main.py CHANGED
@@ -5,6 +5,7 @@ import threading
5
  import random
6
  import textwrap
7
  import firebase_admin
 
8
  from firebase_admin import credentials, firestore
9
  from flask import Flask, request, jsonify
10
  from flask_cors import CORS
@@ -19,7 +20,7 @@ from google.api_core import exceptions
19
  app = Flask(__name__)
20
  CORS(app)
21
 
22
- print("--- HUGGING FACE QUIZ-BOT STARTED ---", flush=True)
23
 
24
  # ==========================================
25
  # 1. SETUP
@@ -36,13 +37,12 @@ try:
36
  except Exception as e:
37
  print(f"❌ Firebase Error: {e}", flush=True)
38
 
39
- # Google Drive Config
40
  FOLDER_ID = os.environ.get('GDRIVE_FOLDER_ID')
41
  CLIENT_ID = os.environ.get('GDRIVE_CLIENT_ID')
42
  CLIENT_SECRET = os.environ.get('GDRIVE_CLIENT_SECRET')
43
  REFRESH_TOKEN = os.environ.get('GDRIVE_REFRESH_TOKEN')
44
-
45
- # Gemini Config
46
  API_KEYS = os.environ.get('GEMINI_API_KEYS', '').split(',')
47
  current_key_index = 0
48
 
@@ -50,6 +50,25 @@ current_key_index = 0
50
  # 2. HELPER FUNCTIONS
51
  # ==========================================
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  def get_next_key():
54
  global current_key_index
55
  current_key_index = (current_key_index + 1) % len(API_KEYS)
@@ -58,7 +77,6 @@ def get_next_key():
58
  def generate_with_retry(prompt):
59
  global current_key_index
60
  max_retries = len(API_KEYS)
61
-
62
  for _ in range(max_retries):
63
  try:
64
  current_key = API_KEYS[current_key_index]
@@ -95,7 +113,6 @@ def upload_to_drive(file_path, filename):
95
  file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
96
  file_id = file.get('id')
97
 
98
- # Public Permission
99
  service.permissions().create(fileId=file_id, body={'type': 'anyone', 'role': 'reader'}).execute()
100
  result = service.files().get(fileId=file_id, fields='webViewLink').execute()
101
 
@@ -104,95 +121,76 @@ def upload_to_drive(file_path, filename):
104
  def create_pdf_from_text(text, filename, title):
105
  c = canvas.Canvas(filename, pagesize=letter)
106
  width, height = letter
 
 
 
107
 
108
- c.setFont("Helvetica-Bold", 20)
109
- c.drawCentredString(width / 2, height - 80, f"QUIZ: {title}")
110
- c.setFont("Helvetica", 12)
111
- c.drawCentredString(width / 2, height - 110, "Test Your Knowledge - Answers at the end")
112
- c.line(50, height - 130, width - 50, height - 130)
113
-
114
- text_object = c.beginText(50, height - 160)
115
- text_object.setFont("Helvetica", 11)
116
- text_object.setLeading(14)
117
-
118
- clean_text = text.replace("**", "").replace("##", "")
119
- lines = clean_text.split('\n')
120
-
121
  for line in lines:
122
  wrapped_lines = textwrap.wrap(line, width=90)
123
  for wrapped_line in wrapped_lines:
124
  if text_object.getY() < 50:
125
- c.drawText(text_object)
126
- c.showPage()
127
- text_object = c.beginText(50, height - 50)
128
- text_object.setFont("Helvetica", 11)
129
- text_object.setLeading(14)
130
  text_object.textLine(wrapped_line)
131
  text_object.textLine("")
132
  c.drawText(text_object)
133
  c.save()
134
 
135
  # ==========================================
136
- # 3. QUIZ WORKER 🧠
137
  # ==========================================
138
 
139
  def get_quiz_topic():
140
  categories = ["Physics", "Computer Science", "Biology", "Chemistry", "General Knowledge", "History"]
141
  selected_category = random.choice(categories)
142
  prompt = f"Give me ONE specific educational topic for a Hard Quiz related to '{selected_category}'. Just the Topic Name."
143
-
144
- topic_title = generate_with_retry(prompt)
145
- if topic_title: return topic_title.strip().replace('"', ''), selected_category
146
  return None, None
147
 
148
  def quiz_worker_loop():
149
  print("πŸ€– Quiz-Bot Started...", flush=True)
150
  time.sleep(10)
151
-
152
  while True:
153
  try:
154
- print("⏳ Planning new Quiz...", flush=True)
155
  title, subject = get_quiz_topic()
156
-
157
  if not title:
158
- time.sleep(60)
159
- continue
160
 
161
  print(f"πŸŽ“ Generating Quiz: {title}", flush=True)
162
-
163
- # --- QUIZ SPECIFIC PROMPT ---
164
  content_prompt = (
165
- f"Create a Multiple Choice Question (MCQ) Quiz on: '{title}'.\n"
166
- "Format: CLEAN PLAIN TEXT for PDF.\n"
167
- "1. Write 15 Challenging MCQs.\n"
168
- "2. Format: Question, Options (A, B, C, D).\n"
169
- "3. At the very end of the document, provide an ANSWER KEY with short explanations.\n"
170
- "4. Do not use Markdown symbols."
171
  )
172
-
173
  content = generate_with_retry(content_prompt)
174
 
175
  if content:
176
  pdf_name = f"/tmp/{title.replace(' ', '_')}_Quiz_{int(time.time())}.pdf"
177
  create_pdf_from_text(content, pdf_name, title)
178
 
179
- # Upload to Drive
180
  link = upload_to_drive(pdf_name, f"Quiz: {title}.pdf")
181
 
182
- # Save to Firebase (With distinct Title)
183
  if link:
184
- db.collection('notes').add({
185
- 'title': f"[QUIZ] {title}", # Prefix add kar dia
 
186
  'subject': subject,
187
  'downloadUrl': link,
188
  'uploaderName': 'Quiz Master AI',
189
  'timestamp': firestore.SERVER_TIMESTAMP
190
  })
191
- print(f"πŸŽ‰ Quiz Uploaded: {title}", flush=True)
 
 
 
 
192
 
193
  if os.path.exists(pdf_name): os.remove(pdf_name)
194
 
195
- # Sleep 2 Hours (Quizzes kam hone chahiyen notes se)
196
  print("πŸ’€ Quiz-Bot Sleeping for 1 Min...", flush=True)
197
  time.sleep(60)
198
 
@@ -203,11 +201,10 @@ def quiz_worker_loop():
203
  threading.Thread(target=quiz_worker_loop, daemon=True).start()
204
 
205
  # ==========================================
206
- # 4. SERVER ROUTES
207
  # ==========================================
208
  @app.route('/')
209
- def home():
210
- return "Hugging Face Quiz-Bot Online"
211
 
212
  if __name__ == '__main__':
213
  app.run(host='0.0.0.0', port=7860)
 
5
  import random
6
  import textwrap
7
  import firebase_admin
8
+ import psycopg2 # <--- Added for Sync
9
  from firebase_admin import credentials, firestore
10
  from flask import Flask, request, jsonify
11
  from flask_cors import CORS
 
20
  app = Flask(__name__)
21
  CORS(app)
22
 
23
+ print("--- HUGGING FACE QUIZ-BOT (SYNC MODE) STARTED ---", flush=True)
24
 
25
  # ==========================================
26
  # 1. SETUP
 
37
  except Exception as e:
38
  print(f"❌ Firebase Error: {e}", flush=True)
39
 
40
+ # Secrets
41
  FOLDER_ID = os.environ.get('GDRIVE_FOLDER_ID')
42
  CLIENT_ID = os.environ.get('GDRIVE_CLIENT_ID')
43
  CLIENT_SECRET = os.environ.get('GDRIVE_CLIENT_SECRET')
44
  REFRESH_TOKEN = os.environ.get('GDRIVE_REFRESH_TOKEN')
45
+ SUPABASE_URI = os.environ.get('SUPABASE_URI') # <--- New Secret Required
 
46
  API_KEYS = os.environ.get('GEMINI_API_KEYS', '').split(',')
47
  current_key_index = 0
48
 
 
50
  # 2. HELPER FUNCTIONS
51
  # ==========================================
52
 
53
+ def save_to_supabase(note_id, title, subject, download_url):
54
+ """Syncs quiz data to Supabase for Search."""
55
+ if not SUPABASE_URI: return
56
+ try:
57
+ conn = psycopg2.connect(SUPABASE_URI)
58
+ cur = conn.cursor()
59
+ sql = """
60
+ INSERT INTO search_index (id, title, subject, download_url)
61
+ VALUES (%s, %s, %s, %s)
62
+ ON CONFLICT (id) DO NOTHING;
63
+ """
64
+ cur.execute(sql, (note_id, title, subject, download_url))
65
+ conn.commit()
66
+ cur.close()
67
+ conn.close()
68
+ print(f"βœ… Synced Quiz to Supabase: {title}", flush=True)
69
+ except Exception as e:
70
+ print(f"⚠️ Supabase Sync Failed: {e}", flush=True)
71
+
72
  def get_next_key():
73
  global current_key_index
74
  current_key_index = (current_key_index + 1) % len(API_KEYS)
 
77
  def generate_with_retry(prompt):
78
  global current_key_index
79
  max_retries = len(API_KEYS)
 
80
  for _ in range(max_retries):
81
  try:
82
  current_key = API_KEYS[current_key_index]
 
113
  file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
114
  file_id = file.get('id')
115
 
 
116
  service.permissions().create(fileId=file_id, body={'type': 'anyone', 'role': 'reader'}).execute()
117
  result = service.files().get(fileId=file_id, fields='webViewLink').execute()
118
 
 
121
  def create_pdf_from_text(text, filename, title):
122
  c = canvas.Canvas(filename, pagesize=letter)
123
  width, height = letter
124
+ c.setFont("Helvetica-Bold", 20); c.drawCentredString(width/2, height-80, f"QUIZ: {title}")
125
+ c.setFont("Helvetica", 12); c.drawCentredString(width/2, height-110, "Test Your Knowledge - Answers at the end")
126
+ c.line(50, height-130, width-50, height-130)
127
 
128
+ text_object = c.beginText(50, height-160)
129
+ text_object.setFont("Helvetica", 11); text_object.setLeading(14)
130
+ lines = text.replace("**", "").replace("##", "").split('\n')
 
 
 
 
 
 
 
 
 
 
131
  for line in lines:
132
  wrapped_lines = textwrap.wrap(line, width=90)
133
  for wrapped_line in wrapped_lines:
134
  if text_object.getY() < 50:
135
+ c.drawText(text_object); c.showPage();
136
+ text_object = c.beginText(50, height-50); text_object.setFont("Helvetica", 11); text_object.setLeading(14)
 
 
 
137
  text_object.textLine(wrapped_line)
138
  text_object.textLine("")
139
  c.drawText(text_object)
140
  c.save()
141
 
142
  # ==========================================
143
+ # 3. QUIZ WORKER
144
  # ==========================================
145
 
146
  def get_quiz_topic():
147
  categories = ["Physics", "Computer Science", "Biology", "Chemistry", "General Knowledge", "History"]
148
  selected_category = random.choice(categories)
149
  prompt = f"Give me ONE specific educational topic for a Hard Quiz related to '{selected_category}'. Just the Topic Name."
150
+ topic = generate_with_retry(prompt)
151
+ if topic: return topic.strip().replace('"', ''), selected_category
 
152
  return None, None
153
 
154
  def quiz_worker_loop():
155
  print("πŸ€– Quiz-Bot Started...", flush=True)
156
  time.sleep(10)
 
157
  while True:
158
  try:
 
159
  title, subject = get_quiz_topic()
 
160
  if not title:
161
+ time.sleep(60); continue
 
162
 
163
  print(f"πŸŽ“ Generating Quiz: {title}", flush=True)
 
 
164
  content_prompt = (
165
+ f"Create a MCQ Quiz on: '{title}'. CLEAN PLAIN TEXT format.\n"
166
+ "1. Write 15 MCQs with Options (A, B, C, D).\n"
167
+ "2. Provide ANSWER KEY at the end."
 
 
 
168
  )
 
169
  content = generate_with_retry(content_prompt)
170
 
171
  if content:
172
  pdf_name = f"/tmp/{title.replace(' ', '_')}_Quiz_{int(time.time())}.pdf"
173
  create_pdf_from_text(content, pdf_name, title)
174
 
 
175
  link = upload_to_drive(pdf_name, f"Quiz: {title}.pdf")
176
 
 
177
  if link:
178
+ # 1. Save to Firebase
179
+ doc_ref = db.collection('notes').add({
180
+ 'title': f"[QUIZ] {title}",
181
  'subject': subject,
182
  'downloadUrl': link,
183
  'uploaderName': 'Quiz Master AI',
184
  'timestamp': firestore.SERVER_TIMESTAMP
185
  })
186
+
187
+ # 2. Sync to Supabase
188
+ save_to_supabase(doc_ref[1].id, f"[QUIZ] {title}", subject, link)
189
+
190
+ print(f"πŸŽ‰ Quiz Uploaded & Synced: {title}", flush=True)
191
 
192
  if os.path.exists(pdf_name): os.remove(pdf_name)
193
 
 
194
  print("πŸ’€ Quiz-Bot Sleeping for 1 Min...", flush=True)
195
  time.sleep(60)
196
 
 
201
  threading.Thread(target=quiz_worker_loop, daemon=True).start()
202
 
203
  # ==========================================
204
+ # 4. ROUTES
205
  # ==========================================
206
  @app.route('/')
207
+ def home(): return "Hugging Face Quiz-Bot (Synced) Online"
 
208
 
209
  if __name__ == '__main__':
210
  app.run(host='0.0.0.0', port=7860)