Spaces:
Sleeping
Sleeping
Bahawal Ali commited on
Update main.py
Browse files
main.py
CHANGED
|
@@ -16,13 +16,12 @@ import google.generativeai as genai
|
|
| 16 |
app = Flask(__name__)
|
| 17 |
CORS(app)
|
| 18 |
|
| 19 |
-
print("--- NOCOPYRIGHT.SPACE (
|
| 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')
|
|
@@ -31,14 +30,14 @@ 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
|
| 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
|
| 42 |
except Exception as e:
|
| 43 |
print(f"❌ Supabase Connection Failed: {e}", flush=True)
|
| 44 |
|
|
@@ -52,13 +51,12 @@ def get_next_key():
|
|
| 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}'. "
|
|
@@ -80,21 +78,33 @@ def generate_prompt_with_gemini():
|
|
| 80 |
return "A beautiful high quality stock photo of nature, 8k resolution", "Nature"
|
| 81 |
|
| 82 |
def generate_image_pollinations(prompt):
|
| 83 |
-
"""Generates image
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
|
@@ -107,7 +117,6 @@ def upload_image_to_drive(image_bytes, filename):
|
|
| 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
|
|
@@ -116,7 +125,6 @@ def upload_image_to_drive(image_bytes, filename):
|
|
| 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()
|
|
@@ -134,16 +142,16 @@ def save_metadata_to_supabase(file_id, prompt, category, download_url):
|
|
| 134 |
print(f"⚠️ Supabase Save Failed: {e}", flush=True)
|
| 135 |
|
| 136 |
# ==========================================
|
| 137 |
-
# 3. WORKER LOOP
|
| 138 |
# ==========================================
|
| 139 |
|
| 140 |
def image_worker_loop():
|
| 141 |
-
print("
|
| 142 |
time.sleep(5)
|
| 143 |
while True:
|
| 144 |
try:
|
| 145 |
full_prompt, category = generate_prompt_with_gemini()
|
| 146 |
-
print(f"🧠
|
| 147 |
|
| 148 |
img_bytes = generate_image_pollinations(full_prompt)
|
| 149 |
|
|
@@ -154,41 +162,35 @@ def image_worker_loop():
|
|
| 154 |
if link and file_id:
|
| 155 |
save_metadata_to_supabase(file_id, full_prompt, category, link)
|
| 156 |
|
| 157 |
-
|
|
|
|
| 158 |
time.sleep(120)
|
| 159 |
|
| 160 |
except Exception as e:
|
| 161 |
-
print(f"⚠️
|
| 162 |
time.sleep(60)
|
| 163 |
|
| 164 |
-
# Start Worker in Background
|
| 165 |
threading.Thread(target=image_worker_loop, daemon=True).start()
|
| 166 |
|
| 167 |
# ==========================================
|
| 168 |
-
# 4.
|
| 169 |
# ==========================================
|
| 170 |
|
| 171 |
@app.route('/')
|
| 172 |
def home():
|
| 173 |
-
return jsonify({"status": "
|
| 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({
|
|
@@ -198,11 +200,9 @@ def get_images():
|
|
| 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)
|
|
|
|
| 16 |
app = Flask(__name__)
|
| 17 |
CORS(app)
|
| 18 |
|
| 19 |
+
print("--- NOCOPYRIGHT.SPACE (UPDATED WORKER) STARTED ---", flush=True)
|
| 20 |
|
| 21 |
# ==========================================
|
| 22 |
# 1. SETUP & SECRETS
|
| 23 |
# ==========================================
|
| 24 |
|
|
|
|
| 25 |
FOLDER_ID = os.environ.get('GDRIVE_FOLDER_ID')
|
| 26 |
CLIENT_ID = os.environ.get('GDRIVE_CLIENT_ID')
|
| 27 |
CLIENT_SECRET = os.environ.get('GDRIVE_CLIENT_SECRET')
|
|
|
|
| 30 |
API_KEYS = os.environ.get('GEMINI_API_KEYS', '').split(',')
|
| 31 |
current_key_index = 0
|
| 32 |
|
| 33 |
+
# Check DB Connection
|
| 34 |
try:
|
| 35 |
if SUPABASE_URI:
|
| 36 |
conn = psycopg2.connect(SUPABASE_URI)
|
| 37 |
conn.close()
|
| 38 |
print("✅ Supabase DB Connected Successfully", flush=True)
|
| 39 |
else:
|
| 40 |
+
print("❌ Supabase URI missing!", flush=True)
|
| 41 |
except Exception as e:
|
| 42 |
print(f"❌ Supabase Connection Failed: {e}", flush=True)
|
| 43 |
|
|
|
|
| 51 |
return API_KEYS[current_key_index]
|
| 52 |
|
| 53 |
def get_db_connection():
|
|
|
|
| 54 |
return psycopg2.connect(SUPABASE_URI)
|
| 55 |
|
| 56 |
def generate_prompt_with_gemini():
|
| 57 |
+
"""Uses Gemini to brainstorm prompts (Rotates Keys)."""
|
| 58 |
global current_key_index
|
| 59 |
+
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"]
|
| 60 |
category = random.choice(categories)
|
| 61 |
|
| 62 |
prompt = (f"Write a highly detailed text-to-image prompt for a stock photo about '{category}'. "
|
|
|
|
| 78 |
return "A beautiful high quality stock photo of nature, 8k resolution", "Nature"
|
| 79 |
|
| 80 |
def generate_image_pollinations(prompt):
|
| 81 |
+
"""Generates image with Retry Logic & Longer Timeout."""
|
| 82 |
+
# 3 Baar Try karega agar fail hua to
|
| 83 |
+
for attempt in range(1, 4):
|
| 84 |
+
try:
|
| 85 |
+
seed = random.randint(1, 100000)
|
| 86 |
+
safe_prompt = requests.utils.quote(prompt)
|
| 87 |
+
# Flux model use kar rahay hain jo heavy hai
|
| 88 |
+
url = f"https://image.pollinations.ai/prompt/{safe_prompt}?width=1080&height=1920&model=flux&nologo=true&seed={seed}"
|
| 89 |
+
|
| 90 |
+
print(f"🎨 Image Gen Attempt {attempt}/3...", flush=True)
|
| 91 |
+
|
| 92 |
+
# TIMEOUT INCREASED TO 120 SECONDS (2 Minutes)
|
| 93 |
+
response = requests.get(url, timeout=120)
|
| 94 |
+
|
| 95 |
+
if response.status_code == 200:
|
| 96 |
+
return response.content
|
| 97 |
+
else:
|
| 98 |
+
print(f"⚠️ Status Code Error: {response.status_code}", flush=True)
|
| 99 |
+
|
| 100 |
+
except Exception as e:
|
| 101 |
+
print(f"⚠️ Gen Error (Attempt {attempt}): {e}", flush=True)
|
| 102 |
+
time.sleep(5) # Wait 5 sec before retry
|
| 103 |
+
|
| 104 |
+
print("❌ All 3 Attempts Failed.", flush=True)
|
| 105 |
return None
|
| 106 |
|
| 107 |
def upload_image_to_drive(image_bytes, filename):
|
|
|
|
| 108 |
print("🚀 Uploading Image to Drive...", flush=True)
|
| 109 |
try:
|
| 110 |
creds = Credentials(None, refresh_token=REFRESH_TOKEN, token_uri="https://oauth2.googleapis.com/token", client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
|
|
|
|
| 117 |
file_id = file.get('id')
|
| 118 |
|
| 119 |
service.permissions().create(fileId=file_id, body={'type': 'anyone', 'role': 'reader'}).execute()
|
|
|
|
| 120 |
result = service.files().get(fileId=file_id, fields='webContentLink').execute()
|
| 121 |
|
| 122 |
return result.get('webContentLink'), file_id
|
|
|
|
| 125 |
return None, None
|
| 126 |
|
| 127 |
def save_metadata_to_supabase(file_id, prompt, category, download_url):
|
|
|
|
| 128 |
try:
|
| 129 |
conn = get_db_connection()
|
| 130 |
cur = conn.cursor()
|
|
|
|
| 142 |
print(f"⚠️ Supabase Save Failed: {e}", flush=True)
|
| 143 |
|
| 144 |
# ==========================================
|
| 145 |
+
# 3. WORKER LOOP
|
| 146 |
# ==========================================
|
| 147 |
|
| 148 |
def image_worker_loop():
|
| 149 |
+
print("🤖 Worker Loop Initialized...", flush=True)
|
| 150 |
time.sleep(5)
|
| 151 |
while True:
|
| 152 |
try:
|
| 153 |
full_prompt, category = generate_prompt_with_gemini()
|
| 154 |
+
print(f"🧠 Prompt Ready: {category}", flush=True)
|
| 155 |
|
| 156 |
img_bytes = generate_image_pollinations(full_prompt)
|
| 157 |
|
|
|
|
| 162 |
if link and file_id:
|
| 163 |
save_metadata_to_supabase(file_id, full_prompt, category, link)
|
| 164 |
|
| 165 |
+
# Wait 2 mins before next cycle
|
| 166 |
+
print("💤 Cooling down for 2 Mins...", flush=True)
|
| 167 |
time.sleep(120)
|
| 168 |
|
| 169 |
except Exception as e:
|
| 170 |
+
print(f"⚠️ Loop Critical Error: {e}", flush=True)
|
| 171 |
time.sleep(60)
|
| 172 |
|
|
|
|
| 173 |
threading.Thread(target=image_worker_loop, daemon=True).start()
|
| 174 |
|
| 175 |
# ==========================================
|
| 176 |
+
# 4. FLASK API
|
| 177 |
# ==========================================
|
| 178 |
|
| 179 |
@app.route('/')
|
| 180 |
def home():
|
| 181 |
+
return jsonify({"status": "Worker Running with Retry Logic"})
|
| 182 |
|
| 183 |
@app.route('/api/images', methods=['GET'])
|
| 184 |
def get_images():
|
|
|
|
| 185 |
try:
|
| 186 |
limit = int(request.args.get('limit', 20))
|
|
|
|
| 187 |
conn = get_db_connection()
|
| 188 |
cur = conn.cursor(cursor_factory=RealDictCursor)
|
|
|
|
|
|
|
| 189 |
cur.execute("SELECT * FROM images ORDER BY created_at DESC LIMIT %s", (limit,))
|
| 190 |
rows = cur.fetchall()
|
|
|
|
| 191 |
cur.close()
|
| 192 |
conn.close()
|
| 193 |
|
|
|
|
| 194 |
images = []
|
| 195 |
for row in rows:
|
| 196 |
images.append({
|
|
|
|
| 200 |
'category': row['category'],
|
| 201 |
'timestamp': str(row['created_at'])
|
| 202 |
})
|
|
|
|
| 203 |
return jsonify(images)
|
| 204 |
except Exception as e:
|
| 205 |
return jsonify({"error": str(e)}), 500
|
| 206 |
|
|
|
|
| 207 |
if __name__ == '__main__':
|
| 208 |
app.run(host='0.0.0.0', port=7860)
|