Spaces:
Sleeping
Sleeping
Download main.py from notes-provider/notes-worker: direct link, hf CLI and curl.
- Browser
- Download file 7.76 kB
-
https://huggingface.co/spaces/notes-provider/notes-worker/resolve/main/main.py
- Command line
-
hf download hf://spaces/notes-provider/notes-worker/main.py
-
curl -L -o main.py https://huggingface.co/spaces/notes-provider/notes-worker/resolve/main/main.py
7.76 kB
| import os | |
| import time | |
| import threading | |
| import random | |
| import requests | |
| import io | |
| import psycopg2 | |
| from psycopg2.extras import RealDictCursor | |
| from flask import Flask, request, jsonify | |
| from flask_cors import CORS | |
| from googleapiclient.discovery import build | |
| from googleapiclient.http import MediaIoBaseUpload | |
| from google.oauth2.credentials import Credentials | |
| import google.generativeai as genai | |
| app = Flask(__name__) | |
| CORS(app) | |
| print("--- NOCOPYRIGHT.SPACE (UPDATED WORKER) STARTED ---", flush=True) | |
| # ========================================== | |
| # 1. SETUP & SECRETS | |
| # ========================================== | |
| FOLDER_ID = os.environ.get('GDRIVE_FOLDER_ID') | |
| CLIENT_ID = os.environ.get('GDRIVE_CLIENT_ID') | |
| CLIENT_SECRET = os.environ.get('GDRIVE_CLIENT_SECRET') | |
| REFRESH_TOKEN = os.environ.get('GDRIVE_REFRESH_TOKEN') | |
| SUPABASE_URI = os.environ.get('SUPABASE_URI') | |
| API_KEYS = os.environ.get('GEMINI_API_KEYS', '').split(',') | |
| current_key_index = 0 | |
| # Check DB Connection | |
| try: | |
| if SUPABASE_URI: | |
| conn = psycopg2.connect(SUPABASE_URI) | |
| conn.close() | |
| print("✅ Supabase DB Connected Successfully", flush=True) | |
| else: | |
| print("❌ Supabase URI missing!", flush=True) | |
| except Exception as e: | |
| print(f"❌ Supabase Connection Failed: {e}", flush=True) | |
| # ========================================== | |
| # 2. HELPER FUNCTIONS | |
| # ========================================== | |
| def get_next_key(): | |
| global current_key_index | |
| current_key_index = (current_key_index + 1) % len(API_KEYS) | |
| return API_KEYS[current_key_index] | |
| def get_db_connection(): | |
| return psycopg2.connect(SUPABASE_URI) | |
| def generate_prompt_with_gemini(): | |
| """Uses Gemini to brainstorm prompts (Rotates Keys).""" | |
| global current_key_index | |
| categories = ["Cyberpunk City", "Minimalist Nature", "Abstract 3D Shape", "Neon Portrait", "Futuristic Tech", "Calm Workspace", "Coffee Aesthetics", "Dark Moody Landscape", "Bright Anime Style", "Luxury Cars", "Street Photography"] | |
| category = random.choice(categories) | |
| prompt = (f"Write a highly detailed text-to-image prompt for a stock photo about '{category}'. " | |
| "Include lighting, texture, and 8k resolution details. " | |
| "Output ONLY the prompt text, no intro.") | |
| max_retries = len(API_KEYS) | |
| for _ in range(max_retries): | |
| try: | |
| current_key = API_KEYS[current_key_index] | |
| genai.configure(api_key=current_key) | |
| model = genai.GenerativeModel('gemini-2.0-flash') | |
| response = model.generate_content(prompt) | |
| return response.text.strip(), category | |
| except Exception as e: | |
| print(f"⚠️ Gemini Key Error, rotating...", flush=True) | |
| get_next_key() | |
| time.sleep(1) | |
| return "A beautiful high quality stock photo of nature, 8k resolution", "Nature" | |
| def generate_image_pollinations(prompt): | |
| """Generates image with Retry Logic & Longer Timeout.""" | |
| # 3 Baar Try karega agar fail hua to | |
| for attempt in range(1, 4): | |
| try: | |
| seed = random.randint(1, 100000) | |
| safe_prompt = requests.utils.quote(prompt) | |
| # Flux model use kar rahay hain jo heavy hai | |
| url = f"https://image.pollinations.ai/prompt/{safe_prompt}?width=1080&height=1920&model=flux&nologo=true&seed={seed}" | |
| print(f"🎨 Image Gen Attempt {attempt}/3...", flush=True) | |
| # TIMEOUT INCREASED TO 120 SECONDS (2 Minutes) | |
| response = requests.get(url, timeout=120) | |
| if response.status_code == 200: | |
| return response.content | |
| else: | |
| print(f"⚠️ Status Code Error: {response.status_code}", flush=True) | |
| except Exception as e: | |
| print(f"⚠️ Gen Error (Attempt {attempt}): {e}", flush=True) | |
| time.sleep(5) # Wait 5 sec before retry | |
| print("❌ All 3 Attempts Failed.", flush=True) | |
| return None | |
| def upload_image_to_drive(image_bytes, filename): | |
| print("🚀 Uploading Image to Drive...", flush=True) | |
| try: | |
| creds = Credentials(None, refresh_token=REFRESH_TOKEN, token_uri="https://oauth2.googleapis.com/token", client_id=CLIENT_ID, client_secret=CLIENT_SECRET) | |
| service = build('drive', 'v3', credentials=creds) | |
| file_metadata = {'name': filename, 'parents': [FOLDER_ID]} | |
| media = MediaIoBaseUpload(io.BytesIO(image_bytes), mimetype='image/jpeg', resumable=True) | |
| file = service.files().create(body=file_metadata, media_body=media, fields='id').execute() | |
| file_id = file.get('id') | |
| service.permissions().create(fileId=file_id, body={'type': 'anyone', 'role': 'reader'}).execute() | |
| result = service.files().get(fileId=file_id, fields='webContentLink').execute() | |
| return result.get('webContentLink'), file_id | |
| except Exception as e: | |
| print(f"❌ Drive Upload Error: {e}", flush=True) | |
| return None, None | |
| def save_metadata_to_supabase(file_id, prompt, category, download_url): | |
| try: | |
| conn = get_db_connection() | |
| cur = conn.cursor() | |
| sql = """ | |
| INSERT INTO images (id, prompt, category, url) | |
| VALUES (%s, %s, %s, %s) | |
| ON CONFLICT (id) DO NOTHING; | |
| """ | |
| cur.execute(sql, (file_id, prompt, category, download_url)) | |
| conn.commit() | |
| cur.close() | |
| conn.close() | |
| print(f"✅ Saved to Supabase: {category}", flush=True) | |
| except Exception as e: | |
| print(f"⚠️ Supabase Save Failed: {e}", flush=True) | |
| # ========================================== | |
| # 3. WORKER LOOP | |
| # ========================================== | |
| def image_worker_loop(): | |
| print("🤖 Worker Loop Initialized...", flush=True) | |
| time.sleep(5) | |
| while True: | |
| try: | |
| full_prompt, category = generate_prompt_with_gemini() | |
| print(f"🧠 Prompt Ready: {category}", flush=True) | |
| img_bytes = generate_image_pollinations(full_prompt) | |
| if img_bytes: | |
| filename = f"AI_Stock_{int(time.time())}.jpg" | |
| link, file_id = upload_image_to_drive(img_bytes, filename) | |
| if link and file_id: | |
| save_metadata_to_supabase(file_id, full_prompt, category, link) | |
| # Wait 2 mins before next cycle | |
| print("💤 Cooling down for 2 Mins...", flush=True) | |
| time.sleep(120) | |
| except Exception as e: | |
| print(f"⚠️ Loop Critical Error: {e}", flush=True) | |
| time.sleep(60) | |
| threading.Thread(target=image_worker_loop, daemon=True).start() | |
| # ========================================== | |
| # 4. FLASK API | |
| # ========================================== | |
| def home(): | |
| return jsonify({"status": "Worker Running with Retry Logic"}) | |
| def get_images(): | |
| try: | |
| limit = int(request.args.get('limit', 20)) | |
| conn = get_db_connection() | |
| cur = conn.cursor(cursor_factory=RealDictCursor) | |
| cur.execute("SELECT * FROM images ORDER BY created_at DESC LIMIT %s", (limit,)) | |
| rows = cur.fetchall() | |
| cur.close() | |
| conn.close() | |
| images = [] | |
| for row in rows: | |
| images.append({ | |
| 'id': row['id'], | |
| 'imageUrl': row['url'], | |
| 'prompt': row['prompt'], | |
| 'category': row['category'], | |
| 'timestamp': str(row['created_at']) | |
| }) | |
| return jsonify(images) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| if __name__ == '__main__': | |
| app.run(host='0.0.0.0', port=7860) |