Spaces:
Sleeping
Sleeping
Bahawal Ali commited on
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,81 +1,70 @@
|
|
| 1 |
import os
|
| 2 |
-
import json
|
| 3 |
import time
|
| 4 |
import threading
|
| 5 |
import random
|
| 6 |
-
import
|
| 7 |
-
import
|
| 8 |
-
import psycopg2
|
| 9 |
-
from
|
| 10 |
from flask import Flask, request, jsonify
|
| 11 |
from flask_cors import CORS
|
| 12 |
from googleapiclient.discovery import build
|
| 13 |
-
from googleapiclient.http import
|
| 14 |
from google.oauth2.credentials import Credentials
|
| 15 |
-
from reportlab.pdfgen import canvas
|
| 16 |
-
from reportlab.lib.pagesizes import letter
|
| 17 |
import google.generativeai as genai
|
| 18 |
-
from google.api_core import exceptions
|
| 19 |
|
| 20 |
app = Flask(__name__)
|
| 21 |
CORS(app)
|
| 22 |
|
| 23 |
-
print("--- HUGGING FACE
|
| 24 |
|
| 25 |
# ==========================================
|
| 26 |
-
# 1. SETUP
|
| 27 |
# ==========================================
|
| 28 |
|
| 29 |
-
#
|
| 30 |
-
try:
|
| 31 |
-
if not firebase_admin._apps:
|
| 32 |
-
cred_json = json.loads(os.environ.get('FIREBASE_CREDENTIALS'))
|
| 33 |
-
cred = credentials.Certificate(cred_json)
|
| 34 |
-
firebase_admin.initialize_app(cred)
|
| 35 |
-
db = firestore.client()
|
| 36 |
-
print("✅ Firebase Connected", flush=True)
|
| 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')
|
| 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 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)
|
| 75 |
return API_KEYS[current_key_index]
|
| 76 |
|
| 77 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
global current_key_index
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
max_retries = len(API_KEYS)
|
| 80 |
for _ in range(max_retries):
|
| 81 |
try:
|
|
@@ -83,128 +72,137 @@ def generate_with_retry(prompt):
|
|
| 83 |
genai.configure(api_key=current_key)
|
| 84 |
model = genai.GenerativeModel('gemini-2.0-flash')
|
| 85 |
response = model.generate_content(prompt)
|
| 86 |
-
return response.text
|
| 87 |
-
except exceptions.ResourceExhausted:
|
| 88 |
-
print("⚠️ Key exhausted. Rotating...", flush=True)
|
| 89 |
-
get_next_key()
|
| 90 |
-
time.sleep(2)
|
| 91 |
except Exception as e:
|
| 92 |
-
print(f"
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
return None
|
| 95 |
|
| 96 |
-
def
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
token_uri="https://oauth2.googleapis.com/token",
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 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.
|
| 144 |
# ==========================================
|
| 145 |
|
| 146 |
-
def
|
| 147 |
-
|
| 148 |
-
|
| 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 |
-
|
| 160 |
-
|
| 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 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
link =
|
| 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
|
|
|
|
| 193 |
|
| 194 |
-
print("💤
|
| 195 |
-
time.sleep(
|
| 196 |
|
| 197 |
except Exception as e:
|
| 198 |
-
print(f"⚠️
|
| 199 |
-
time.sleep(
|
| 200 |
|
| 201 |
-
|
|
|
|
| 202 |
|
| 203 |
# ==========================================
|
| 204 |
-
# 4. ROUTES
|
| 205 |
# ==========================================
|
|
|
|
| 206 |
@app.route('/')
|
| 207 |
-
def home():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
|
|
|
|
| 209 |
if __name__ == '__main__':
|
| 210 |
app.run(host='0.0.0.0', port=7860)
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import time
|
| 3 |
import threading
|
| 4 |
import random
|
| 5 |
+
import requests
|
| 6 |
+
import io
|
| 7 |
+
import psycopg2
|
| 8 |
+
from psycopg2.extras import RealDictCursor
|
| 9 |
from flask import Flask, request, jsonify
|
| 10 |
from flask_cors import CORS
|
| 11 |
from googleapiclient.discovery import build
|
| 12 |
+
from googleapiclient.http import MediaIoBaseUpload
|
| 13 |
from google.oauth2.credentials import Credentials
|
|
|
|
|
|
|
| 14 |
import google.generativeai as genai
|
|
|
|
| 15 |
|
| 16 |
app = Flask(__name__)
|
| 17 |
CORS(app)
|
| 18 |
|
| 19 |
+
print("--- NOCOPYRIGHT.SPACE (HUGGING FACE + SUPABASE) STARTED ---", flush=True)
|
| 20 |
|
| 21 |
# ==========================================
|
| 22 |
+
# 1. SETUP & SECRETS
|
| 23 |
# ==========================================
|
| 24 |
|
| 25 |
+
# Secrets loaded directly from your Hugging Face Environment Variables
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
FOLDER_ID = os.environ.get('GDRIVE_FOLDER_ID')
|
| 27 |
CLIENT_ID = os.environ.get('GDRIVE_CLIENT_ID')
|
| 28 |
CLIENT_SECRET = os.environ.get('GDRIVE_CLIENT_SECRET')
|
| 29 |
REFRESH_TOKEN = os.environ.get('GDRIVE_REFRESH_TOKEN')
|
| 30 |
+
SUPABASE_URI = os.environ.get('SUPABASE_URI')
|
| 31 |
API_KEYS = os.environ.get('GEMINI_API_KEYS', '').split(',')
|
| 32 |
current_key_index = 0
|
| 33 |
|
| 34 |
+
# Check DB Connection on Start
|
| 35 |
+
try:
|
| 36 |
+
if SUPABASE_URI:
|
| 37 |
+
conn = psycopg2.connect(SUPABASE_URI)
|
| 38 |
+
conn.close()
|
| 39 |
+
print("✅ Supabase DB Connected Successfully", flush=True)
|
| 40 |
+
else:
|
| 41 |
+
print("❌ Supabase URI missing in Secrets!", flush=True)
|
| 42 |
+
except Exception as e:
|
| 43 |
+
print(f"❌ Supabase Connection Failed: {e}", flush=True)
|
| 44 |
+
|
| 45 |
# ==========================================
|
| 46 |
# 2. HELPER FUNCTIONS
|
| 47 |
# ==========================================
|
| 48 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
def get_next_key():
|
| 50 |
global current_key_index
|
| 51 |
current_key_index = (current_key_index + 1) % len(API_KEYS)
|
| 52 |
return API_KEYS[current_key_index]
|
| 53 |
|
| 54 |
+
def get_db_connection():
|
| 55 |
+
"""Establishes a new connection to Supabase."""
|
| 56 |
+
return psycopg2.connect(SUPABASE_URI)
|
| 57 |
+
|
| 58 |
+
def generate_prompt_with_gemini():
|
| 59 |
+
"""Uses Gemini to brainstorm prompts."""
|
| 60 |
global current_key_index
|
| 61 |
+
categories = ["Cyberpunk City", "Minimalist Nature", "Abstract 3D Shape", "Neon Portrait", "Futuristic Tech", "Calm Workspace", "Coffee Aesthetics", "Dark Moody Landscape", "Bright Anime Style"]
|
| 62 |
+
category = random.choice(categories)
|
| 63 |
+
|
| 64 |
+
prompt = (f"Write a highly detailed text-to-image prompt for a stock photo about '{category}'. "
|
| 65 |
+
"Include lighting, texture, and 8k resolution details. "
|
| 66 |
+
"Output ONLY the prompt text, no intro.")
|
| 67 |
+
|
| 68 |
max_retries = len(API_KEYS)
|
| 69 |
for _ in range(max_retries):
|
| 70 |
try:
|
|
|
|
| 72 |
genai.configure(api_key=current_key)
|
| 73 |
model = genai.GenerativeModel('gemini-2.0-flash')
|
| 74 |
response = model.generate_content(prompt)
|
| 75 |
+
return response.text.strip(), category
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
except Exception as e:
|
| 77 |
+
print(f"⚠️ Gemini Key Error, rotating...", flush=True)
|
| 78 |
+
get_next_key()
|
| 79 |
+
time.sleep(1)
|
| 80 |
+
return "A beautiful high quality stock photo of nature, 8k resolution", "Nature"
|
| 81 |
+
|
| 82 |
+
def generate_image_pollinations(prompt):
|
| 83 |
+
"""Generates image bytes using Pollinations AI."""
|
| 84 |
+
try:
|
| 85 |
+
# Random seed to ensure uniqueness
|
| 86 |
+
seed = random.randint(1, 10000)
|
| 87 |
+
safe_prompt = requests.utils.quote(prompt)
|
| 88 |
+
url = f"https://image.pollinations.ai/prompt/{safe_prompt}?width=1080&height=1920&model=flux&nologo=true&seed={seed}"
|
| 89 |
+
response = requests.get(url, timeout=60)
|
| 90 |
+
if response.status_code == 200:
|
| 91 |
+
return response.content
|
| 92 |
+
except Exception as e:
|
| 93 |
+
print(f"❌ Image Gen Error: {e}", flush=True)
|
| 94 |
return None
|
| 95 |
|
| 96 |
+
def upload_image_to_drive(image_bytes, filename):
|
| 97 |
+
"""Uploads to Google Drive and gets a public link."""
|
| 98 |
+
print("🚀 Uploading Image to Drive...", flush=True)
|
| 99 |
+
try:
|
| 100 |
+
creds = Credentials(None, refresh_token=REFRESH_TOKEN, token_uri="https://oauth2.googleapis.com/token", client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
|
| 101 |
+
service = build('drive', 'v3', credentials=creds)
|
| 102 |
+
|
| 103 |
+
file_metadata = {'name': filename, 'parents': [FOLDER_ID]}
|
| 104 |
+
media = MediaIoBaseUpload(io.BytesIO(image_bytes), mimetype='image/jpeg', resumable=True)
|
| 105 |
+
|
| 106 |
+
file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
|
| 107 |
+
file_id = file.get('id')
|
| 108 |
+
|
| 109 |
+
service.permissions().create(fileId=file_id, body={'type': 'anyone', 'role': 'reader'}).execute()
|
| 110 |
+
# webContentLink is better for direct display
|
| 111 |
+
result = service.files().get(fileId=file_id, fields='webContentLink').execute()
|
| 112 |
+
|
| 113 |
+
return result.get('webContentLink'), file_id
|
| 114 |
+
except Exception as e:
|
| 115 |
+
print(f"❌ Drive Upload Error: {e}", flush=True)
|
| 116 |
+
return None, None
|
| 117 |
+
|
| 118 |
+
def save_metadata_to_supabase(file_id, prompt, category, download_url):
|
| 119 |
+
"""Saves image details to Supabase (PostgreSQL)."""
|
| 120 |
+
try:
|
| 121 |
+
conn = get_db_connection()
|
| 122 |
+
cur = conn.cursor()
|
| 123 |
+
sql = """
|
| 124 |
+
INSERT INTO images (id, prompt, category, url)
|
| 125 |
+
VALUES (%s, %s, %s, %s)
|
| 126 |
+
ON CONFLICT (id) DO NOTHING;
|
| 127 |
+
"""
|
| 128 |
+
cur.execute(sql, (file_id, prompt, category, download_url))
|
| 129 |
+
conn.commit()
|
| 130 |
+
cur.close()
|
| 131 |
+
conn.close()
|
| 132 |
+
print(f"✅ Saved to Supabase: {category}", flush=True)
|
| 133 |
+
except Exception as e:
|
| 134 |
+
print(f"⚠️ Supabase Save Failed: {e}", flush=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
# ==========================================
|
| 137 |
+
# 3. WORKER LOOP (Background)
|
| 138 |
# ==========================================
|
| 139 |
|
| 140 |
+
def image_worker_loop():
|
| 141 |
+
print("🎨 AI Artist Worker Started...", flush=True)
|
| 142 |
+
time.sleep(5)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
while True:
|
| 144 |
try:
|
| 145 |
+
full_prompt, category = generate_prompt_with_gemini()
|
| 146 |
+
print(f"🧠 Generating: {category}", flush=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
+
img_bytes = generate_image_pollinations(full_prompt)
|
| 149 |
+
|
| 150 |
+
if img_bytes:
|
| 151 |
+
filename = f"AI_Stock_{int(time.time())}.jpg"
|
| 152 |
+
link, file_id = upload_image_to_drive(img_bytes, filename)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
+
if link and file_id:
|
| 155 |
+
save_metadata_to_supabase(file_id, full_prompt, category, link)
|
| 156 |
|
| 157 |
+
print("💤 Sleeping for 2 Mins...", flush=True)
|
| 158 |
+
time.sleep(120)
|
| 159 |
|
| 160 |
except Exception as e:
|
| 161 |
+
print(f"⚠️ Worker Error: {e}", flush=True)
|
| 162 |
+
time.sleep(60)
|
| 163 |
|
| 164 |
+
# Start Worker in Background
|
| 165 |
+
threading.Thread(target=image_worker_loop, daemon=True).start()
|
| 166 |
|
| 167 |
# ==========================================
|
| 168 |
+
# 4. API ROUTES (Flask)
|
| 169 |
# ==========================================
|
| 170 |
+
|
| 171 |
@app.route('/')
|
| 172 |
+
def home():
|
| 173 |
+
return jsonify({"status": "NoCopyright.space API (Hugging Face) Online"})
|
| 174 |
+
|
| 175 |
+
@app.route('/api/images', methods=['GET'])
|
| 176 |
+
def get_images():
|
| 177 |
+
"""Fetch images from Supabase Postgres"""
|
| 178 |
+
try:
|
| 179 |
+
limit = int(request.args.get('limit', 20))
|
| 180 |
+
|
| 181 |
+
conn = get_db_connection()
|
| 182 |
+
cur = conn.cursor(cursor_factory=RealDictCursor)
|
| 183 |
+
|
| 184 |
+
# Latest images first
|
| 185 |
+
cur.execute("SELECT * FROM images ORDER BY created_at DESC LIMIT %s", (limit,))
|
| 186 |
+
rows = cur.fetchall()
|
| 187 |
+
|
| 188 |
+
cur.close()
|
| 189 |
+
conn.close()
|
| 190 |
+
|
| 191 |
+
# Map DB columns to Frontend expected keys
|
| 192 |
+
images = []
|
| 193 |
+
for row in rows:
|
| 194 |
+
images.append({
|
| 195 |
+
'id': row['id'],
|
| 196 |
+
'imageUrl': row['url'],
|
| 197 |
+
'prompt': row['prompt'],
|
| 198 |
+
'category': row['category'],
|
| 199 |
+
'timestamp': str(row['created_at'])
|
| 200 |
+
})
|
| 201 |
+
|
| 202 |
+
return jsonify(images)
|
| 203 |
+
except Exception as e:
|
| 204 |
+
return jsonify({"error": str(e)}), 500
|
| 205 |
|
| 206 |
+
# Hugging Face runs on port 7860
|
| 207 |
if __name__ == '__main__':
|
| 208 |
app.run(host='0.0.0.0', port=7860)
|