File size: 7,755 Bytes
3104a0e
 
7a4eddb
 
995dd1d
 
 
 
3104a0e
f8a84aa
e07743d
995dd1d
ec903c7
7a4eddb
77bf72f
3104a0e
f8a84aa
3104a0e
46f797d
ec903c7
7a4eddb
995dd1d
7a4eddb
 
e07743d
ec903c7
 
 
995dd1d
7a4eddb
 
 
46f797d
995dd1d
 
 
 
 
 
46f797d
995dd1d
 
 
7a4eddb
 
 
 
 
 
 
 
 
995dd1d
 
 
 
46f797d
7a4eddb
46f797d
995dd1d
 
 
 
 
 
7a4eddb
 
 
 
 
 
 
995dd1d
7a4eddb
995dd1d
 
 
 
 
 
46f797d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a4eddb
 
995dd1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a4eddb
 
46f797d
7a4eddb
 
995dd1d
46f797d
995dd1d
7a4eddb
 
995dd1d
46f797d
7a4eddb
995dd1d
 
 
 
 
7a4eddb
995dd1d
 
e07743d
46f797d
 
995dd1d
7a4eddb
 
46f797d
995dd1d
f8a84aa
995dd1d
7a4eddb
 
46f797d
7a4eddb
995dd1d
7a4eddb
995dd1d
46f797d
995dd1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3104a0e
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
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
# ==========================================

@app.route('/')
def home(): 
    return jsonify({"status": "Worker Running with Retry Logic"})

@app.route('/api/images', methods=['GET'])
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)