Spaces:
Sleeping
Sleeping
Bahawal Ali commited on
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,7 +1,9 @@
|
|
| 1 |
import os
|
| 2 |
import json
|
| 3 |
import time
|
| 4 |
-
import
|
|
|
|
|
|
|
| 5 |
import firebase_admin
|
| 6 |
from firebase_admin import credentials, firestore
|
| 7 |
from flask import Flask, request, jsonify
|
|
@@ -9,33 +11,73 @@ from flask_cors import CORS
|
|
| 9 |
from googleapiclient.discovery import build
|
| 10 |
from googleapiclient.http import MediaFileUpload
|
| 11 |
from google.oauth2.credentials import Credentials
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
app = Flask(__name__)
|
| 14 |
CORS(app)
|
| 15 |
|
| 16 |
-
|
| 17 |
-
print("--- SYSTEM STARTUP ---", flush=True)
|
| 18 |
|
| 19 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
try:
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
| 24 |
db = firestore.client()
|
| 25 |
print("β
Firebase Connected", flush=True)
|
| 26 |
except Exception as e:
|
| 27 |
-
print(f"β Firebase
|
| 28 |
|
| 29 |
-
#
|
| 30 |
FOLDER_ID = os.environ.get('GDRIVE_FOLDER_ID')
|
| 31 |
CLIENT_ID = os.environ.get('GDRIVE_CLIENT_ID')
|
| 32 |
CLIENT_SECRET = os.environ.get('GDRIVE_CLIENT_SECRET')
|
| 33 |
REFRESH_TOKEN = os.environ.get('GDRIVE_REFRESH_TOKEN')
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
def get_drive_service():
|
| 36 |
-
# Refresh Token se Naya Access Token bana raha hai
|
| 37 |
creds = Credentials(
|
| 38 |
-
None,
|
| 39 |
refresh_token=REFRESH_TOKEN,
|
| 40 |
token_uri="https://oauth2.googleapis.com/token",
|
| 41 |
client_id=CLIENT_ID,
|
|
@@ -44,72 +86,128 @@ def get_drive_service():
|
|
| 44 |
return build('drive', 'v3', credentials=creds)
|
| 45 |
|
| 46 |
def upload_to_drive(file_path, filename):
|
| 47 |
-
print("π Uploading to Google Drive
|
| 48 |
service = get_drive_service()
|
| 49 |
|
| 50 |
-
file_metadata = {
|
| 51 |
-
'name': filename,
|
| 52 |
-
'parents': [FOLDER_ID]
|
| 53 |
-
}
|
| 54 |
-
|
| 55 |
media = MediaFileUpload(file_path, resumable=True)
|
| 56 |
|
| 57 |
-
# Upload File
|
| 58 |
file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
|
| 59 |
file_id = file.get('id')
|
| 60 |
-
print(f"β
Uploaded! File ID: {file_id}", flush=True)
|
| 61 |
-
|
| 62 |
-
# Make Public (Taake user download kar sake)
|
| 63 |
-
service.permissions().create(
|
| 64 |
-
fileId=file_id,
|
| 65 |
-
body={'type': 'anyone', 'role': 'reader'},
|
| 66 |
-
fields='id',
|
| 67 |
-
).execute()
|
| 68 |
|
| 69 |
-
#
|
|
|
|
| 70 |
result = service.files().get(fileId=file_id, fields='webViewLink').execute()
|
|
|
|
| 71 |
return result.get('webViewLink')
|
| 72 |
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
|
|
|
| 95 |
if link:
|
| 96 |
db.collection('notes').add({
|
| 97 |
-
'title': title,
|
| 98 |
'subject': subject,
|
| 99 |
'downloadUrl': link,
|
| 100 |
-
'uploaderName':
|
| 101 |
'timestamp': firestore.SERVER_TIMESTAMP
|
| 102 |
})
|
| 103 |
-
|
| 104 |
-
|
|
|
|
| 105 |
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
if __name__ == '__main__':
|
| 115 |
app.run(host='0.0.0.0', port=7860)
|
|
|
|
| 1 |
import os
|
| 2 |
import json
|
| 3 |
import time
|
| 4 |
+
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
|
|
|
|
| 11 |
from googleapiclient.discovery import build
|
| 12 |
from googleapiclient.http import MediaFileUpload
|
| 13 |
from google.oauth2.credentials import Credentials
|
| 14 |
+
from reportlab.pdfgen import canvas
|
| 15 |
+
from reportlab.lib.pagesizes import letter
|
| 16 |
+
import google.generativeai as genai
|
| 17 |
+
from google.api_core import exceptions
|
| 18 |
|
| 19 |
app = Flask(__name__)
|
| 20 |
CORS(app)
|
| 21 |
|
| 22 |
+
print("--- HUGGING FACE QUIZ-BOT STARTED ---", flush=True)
|
|
|
|
| 23 |
|
| 24 |
+
# ==========================================
|
| 25 |
+
# 1. SETUP
|
| 26 |
+
# ==========================================
|
| 27 |
+
|
| 28 |
+
# Firebase
|
| 29 |
try:
|
| 30 |
+
if not firebase_admin._apps:
|
| 31 |
+
cred_json = json.loads(os.environ.get('FIREBASE_CREDENTIALS'))
|
| 32 |
+
cred = credentials.Certificate(cred_json)
|
| 33 |
+
firebase_admin.initialize_app(cred)
|
| 34 |
db = firestore.client()
|
| 35 |
print("β
Firebase Connected", flush=True)
|
| 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 |
+
|
| 49 |
+
# ==========================================
|
| 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)
|
| 56 |
+
return API_KEYS[current_key_index]
|
| 57 |
+
|
| 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]
|
| 65 |
+
genai.configure(api_key=current_key)
|
| 66 |
+
model = genai.GenerativeModel('gemini-2.0-flash')
|
| 67 |
+
response = model.generate_content(prompt)
|
| 68 |
+
return response.text
|
| 69 |
+
except exceptions.ResourceExhausted:
|
| 70 |
+
print("β οΈ Key exhausted. Rotating...", flush=True)
|
| 71 |
+
get_next_key()
|
| 72 |
+
time.sleep(2)
|
| 73 |
+
except Exception as e:
|
| 74 |
+
print(f"β Gen Error: {e}", flush=True)
|
| 75 |
+
return None
|
| 76 |
+
return None
|
| 77 |
+
|
| 78 |
def get_drive_service():
|
|
|
|
| 79 |
creds = Credentials(
|
| 80 |
+
None,
|
| 81 |
refresh_token=REFRESH_TOKEN,
|
| 82 |
token_uri="https://oauth2.googleapis.com/token",
|
| 83 |
client_id=CLIENT_ID,
|
|
|
|
| 86 |
return build('drive', 'v3', credentials=creds)
|
| 87 |
|
| 88 |
def upload_to_drive(file_path, filename):
|
| 89 |
+
print("π Uploading Quiz to Google Drive...", flush=True)
|
| 90 |
service = get_drive_service()
|
| 91 |
|
| 92 |
+
file_metadata = {'name': filename, 'parents': [FOLDER_ID]}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
media = MediaFileUpload(file_path, resumable=True)
|
| 94 |
|
|
|
|
| 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 |
+
|
| 102 |
return result.get('webViewLink')
|
| 103 |
|
| 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 2 Hours...", flush=True)
|
| 197 |
+
time.sleep(7200)
|
| 198 |
+
|
| 199 |
+
except Exception as e:
|
| 200 |
+
print(f"β οΈ Quiz Worker Error: {e}", flush=True)
|
| 201 |
+
time.sleep(60)
|
| 202 |
|
| 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)
|