openfree commited on
Commit
4f89350
·
verified ·
1 Parent(s): 611c463

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +831 -0
app.py ADDED
@@ -0,0 +1,831 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, request, jsonify
2
+ import os, re, json, sqlite3, logging
3
+
4
+ app = Flask(__name__)
5
+
6
+ # ────────────────────────── 1. CONFIGURATION ──────────────────────────
7
+ # Use absolute paths in the persistent directory for Hugging Face
8
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
9
+ DB_FILE = os.path.join(BASE_DIR, "favorite_sites.json") # JSON file for backward compatibility
10
+ SQLITE_DB = os.path.join(BASE_DIR, "favorite_sites.db") # SQLite database for persistence
11
+
12
+ # Setup logging
13
+ logging.basicConfig(level=logging.INFO)
14
+ logger = logging.getLogger(__name__)
15
+
16
+ # Domains that commonly block iframes
17
+ BLOCKED_DOMAINS = [
18
+ "naver.com", "daum.net", "google.com",
19
+ "facebook.com", "instagram.com", "kakao.com",
20
+ "ycombinator.com"
21
+ ]
22
+
23
+ # ────────────────────────── 2. CURATED CATEGORIES ──────────────────────────
24
+ CATEGORIES = {
25
+ "Productivity": [
26
+ "https://huggingface.co/spaces/ginigen/perflexity-clone",
27
+ "https://huggingface.co/spaces/ginipick/IDEA-DESIGN",
28
+ "https://huggingface.co/spaces/VIDraft/mouse-webgen",
29
+ "https://huggingface.co/spaces/openfree/Vibe-Game",
30
+ "https://huggingface.co/spaces/openfree/Game-Gallery",
31
+ "https://huggingface.co/spaces/aiqtech/Contributors-Leaderboard",
32
+ "https://huggingface.co/spaces/fantaxy/Model-Leaderboard",
33
+ "https://huggingface.co/spaces/fantaxy/Space-Leaderboard",
34
+ "https://huggingface.co/spaces/openfree/Korean-Leaderboard",
35
+ ],
36
+ "Multimodal": [
37
+ "https://huggingface.co/spaces/openfree/DreamO-video",
38
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored-photo",
39
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored",
40
+ "https://huggingface.co/spaces/fantaxy/Sound-AI-SFX",
41
+ "https://huggingface.co/spaces/ginigen/SFX-Sound-magic",
42
+ "https://huggingface.co/spaces/ginigen/VoiceClone-TTS",
43
+ "https://huggingface.co/spaces/aiqcamp/MCP-kokoro",
44
+ "https://huggingface.co/spaces/aiqcamp/ENGLISH-Speaking-Scoring",
45
+ ],
46
+ "Professional": [
47
+ "https://huggingface.co/spaces/ginigen/blogger",
48
+ "https://huggingface.co/spaces/VIDraft/money-radar",
49
+ "https://huggingface.co/spaces/immunobiotech/drug-discovery",
50
+ "https://huggingface.co/spaces/immunobiotech/Gemini-MICHELIN",
51
+ "https://huggingface.co/spaces/Heartsync/Papers-Leaderboard",
52
+ "https://huggingface.co/spaces/VIDraft/PapersImpact",
53
+ "https://huggingface.co/spaces/ginipick/AgentX-Papers",
54
+ "https://huggingface.co/spaces/openfree/Cycle-Navigator",
55
+ ],
56
+ "Image": [
57
+ "https://huggingface.co/spaces/ginigen/interior-design",
58
+ "https://huggingface.co/spaces/ginigen/Workflow-Canvas",
59
+ "https://huggingface.co/spaces/ginigen/Multi-LoRAgen",
60
+ "https://huggingface.co/spaces/ginigen/Every-Text",
61
+ "https://huggingface.co/spaces/ginigen/text3d-r1",
62
+ "https://huggingface.co/spaces/ginipick/FLUXllama",
63
+ "https://huggingface.co/spaces/Heartsync/FLUX-Vision",
64
+ "https://huggingface.co/spaces/ginigen/VisualCloze",
65
+ "https://huggingface.co/spaces/seawolf2357/Ghibli-Multilingual-Text-rendering",
66
+ "https://huggingface.co/spaces/ginigen/Ghibli-Meme-Studio",
67
+ "https://huggingface.co/spaces/VIDraft/Open-Meme-Studio",
68
+ "https://huggingface.co/spaces/ginigen/3D-LLAMA",
69
+ ],
70
+ "LLM / VLM": [
71
+ "https://huggingface.co/spaces/VIDraft/Gemma-3-R1984-4B",
72
+ "https://huggingface.co/spaces/VIDraft/Gemma-3-R1984-12B",
73
+ "https://huggingface.co/spaces/ginigen/Mistral-Perflexity",
74
+ "https://huggingface.co/spaces/aiqcamp/gemini-2.5-flash-preview",
75
+ "https://huggingface.co/spaces/openfree/qwen3-30b-a3b-research",
76
+ "https://huggingface.co/spaces/openfree/qwen3-235b-a22b-research",
77
+ "https://huggingface.co/spaces/openfree/Llama-4-Maverick-17B-Research",
78
+ ],
79
+ }
80
+
81
+ # ────────────────────────── 3. DATABASE FUNCTIONS ──────────────────────────
82
+ def init_db():
83
+ """Initialize both JSON and SQLite databases"""
84
+ # Log database paths for debugging
85
+ logger.info(f"JSON DB path: {DB_FILE}")
86
+ logger.info(f"SQLite DB path: {SQLITE_DB}")
87
+
88
+ # Initialize JSON file if it doesn't exist
89
+ if not os.path.exists(DB_FILE):
90
+ try:
91
+ with open(DB_FILE, "w", encoding="utf-8") as f:
92
+ json.dump([], f, ensure_ascii=False)
93
+ logger.info("Created new JSON database file")
94
+ except Exception as e:
95
+ logger.error(f"Error creating JSON file: {e}")
96
+
97
+ # Initialize SQLite database
98
+ try:
99
+ conn = sqlite3.connect(SQLITE_DB)
100
+ cursor = conn.cursor()
101
+ cursor.execute('''
102
+ CREATE TABLE IF NOT EXISTS urls (
103
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
104
+ url TEXT UNIQUE NOT NULL,
105
+ date_added TIMESTAMP DEFAULT CURRENT_TIMESTAMP
106
+ )
107
+ ''')
108
+ conn.commit()
109
+ logger.info("SQLite database initialized successfully")
110
+
111
+ # If we have data in JSON but not in SQLite (first run with new SQLite DB),
112
+ # migrate the data from JSON to SQLite
113
+ json_urls = load_json()
114
+ if json_urls:
115
+ logger.info(f"Found {len(json_urls)} URLs in JSON file")
116
+ db_urls = load_db_sqlite()
117
+ new_urls = 0
118
+ for url in json_urls:
119
+ if url not in db_urls:
120
+ add_url_to_sqlite(url)
121
+ new_urls += 1
122
+ logger.info(f"Migrated {new_urls} new URLs from JSON to SQLite")
123
+
124
+ conn.close()
125
+ except Exception as e:
126
+ logger.error(f"Error initializing SQLite database: {e}")
127
+
128
+ # Create default URLs file if none exists
129
+ if not load_db():
130
+ default_urls = [
131
+ "https://huggingface.co/spaces/ginigen/perflexity-clone",
132
+ "https://huggingface.co/spaces/openfree/Game-Gallery",
133
+ "https://www.google.com"
134
+ ]
135
+ for url in default_urls:
136
+ add_url_to_sqlite(url)
137
+ save_json(default_urls)
138
+ logger.info("Added default URLs to empty database")
139
+
140
+ def load_json():
141
+ """Load URLs from JSON file (for backward compatibility)"""
142
+ try:
143
+ if os.path.exists(DB_FILE):
144
+ with open(DB_FILE, "r", encoding="utf-8") as f:
145
+ raw = json.load(f)
146
+ return raw if isinstance(raw, list) else []
147
+ return []
148
+ except Exception as e:
149
+ logger.error(f"Error loading JSON file: {e}")
150
+ return []
151
+
152
+ def save_json(lst):
153
+ """Save URLs to JSON file (for backward compatibility)"""
154
+ try:
155
+ with open(DB_FILE, "w", encoding="utf-8") as f:
156
+ json.dump(lst, f, ensure_ascii=False, indent=2)
157
+ logger.info(f"Saved {len(lst)} URLs to JSON file")
158
+ return True
159
+ except Exception as e:
160
+ logger.error(f"Error saving to JSON file: {e}")
161
+ return False
162
+
163
+ def load_db_sqlite():
164
+ """Load URLs from SQLite database"""
165
+ try:
166
+ conn = sqlite3.connect(SQLITE_DB)
167
+ cursor = conn.cursor()
168
+ cursor.execute("SELECT url FROM urls ORDER BY date_added DESC")
169
+ urls = [row[0] for row in cursor.fetchall()]
170
+ conn.close()
171
+ logger.info(f"Loaded {len(urls)} URLs from SQLite database")
172
+ return urls
173
+ except Exception as e:
174
+ logger.error(f"Error loading from SQLite database: {e}")
175
+ return []
176
+
177
+ def add_url_to_sqlite(url):
178
+ """Add a URL to SQLite database"""
179
+ try:
180
+ conn = sqlite3.connect(SQLITE_DB)
181
+ cursor = conn.cursor()
182
+ cursor.execute("INSERT INTO urls (url) VALUES (?)", (url,))
183
+ conn.commit()
184
+ conn.close()
185
+ logger.info(f"Added URL to SQLite: {url}")
186
+ return True
187
+ except sqlite3.IntegrityError:
188
+ # URL already exists
189
+ logger.info(f"URL already exists in SQLite: {url}")
190
+ return False
191
+ except Exception as e:
192
+ logger.error(f"Error adding URL to SQLite: {e}")
193
+ return False
194
+
195
+ def update_url_in_sqlite(old_url, new_url):
196
+ """Update a URL in SQLite database"""
197
+ try:
198
+ conn = sqlite3.connect(SQLITE_DB)
199
+ cursor = conn.cursor()
200
+ cursor.execute("UPDATE urls SET url = ? WHERE url = ?", (new_url, old_url))
201
+ if cursor.rowcount > 0:
202
+ conn.commit()
203
+ logger.info(f"Updated URL in SQLite: {old_url} -> {new_url}")
204
+ success = True
205
+ else:
206
+ logger.info(f"URL not found for update in SQLite: {old_url}")
207
+ success = False
208
+ conn.close()
209
+ return success
210
+ except sqlite3.IntegrityError:
211
+ # New URL already exists
212
+ logger.error(f"New URL already exists in SQLite: {new_url}")
213
+ return False
214
+ except Exception as e:
215
+ logger.error(f"Error updating URL in SQLite: {e}")
216
+ return False
217
+
218
+ def delete_url_from_sqlite(url):
219
+ """Delete a URL from SQLite database"""
220
+ try:
221
+ conn = sqlite3.connect(SQLITE_DB)
222
+ cursor = conn.cursor()
223
+ cursor.execute("DELETE FROM urls WHERE url = ?", (url,))
224
+ if cursor.rowcount > 0:
225
+ conn.commit()
226
+ logger.info(f"Deleted URL from SQLite: {url}")
227
+ success = True
228
+ else:
229
+ logger.info(f"URL not found for deletion in SQLite: {url}")
230
+ success = False
231
+ conn.close()
232
+ return success
233
+ except Exception as e:
234
+ logger.error(f"Error deleting URL from SQLite: {e}")
235
+ return False
236
+
237
+ def load_db():
238
+ """Primary function to load URLs - prioritizes SQLite DB but falls back to JSON"""
239
+ sqlite_urls = load_db_sqlite()
240
+
241
+ # If SQLite DB is empty, try loading from JSON
242
+ if not sqlite_urls:
243
+ logger.info("SQLite database empty, trying JSON file")
244
+ json_urls = load_json()
245
+
246
+ # If we found URLs in JSON, migrate them to SQLite
247
+ if json_urls:
248
+ logger.info(f"Migrating {len(json_urls)} URLs from JSON to SQLite")
249
+ for url in json_urls:
250
+ add_url_to_sqlite(url)
251
+ return json_urls
252
+
253
+ return sqlite_urls
254
+
255
+ def save_db(lst):
256
+ """Save URLs to both SQLite and JSON"""
257
+ logger.info(f"Saving {len(lst)} URLs to database")
258
+
259
+ # Clear all URLs from SQLite and add the new list
260
+ try:
261
+ conn = sqlite3.connect(SQLITE_DB)
262
+ cursor = conn.cursor()
263
+ cursor.execute("DELETE FROM urls")
264
+ for url in lst:
265
+ cursor.execute("INSERT INTO urls (url) VALUES (?)", (url,))
266
+ conn.commit()
267
+ conn.close()
268
+ logger.info("Successfully saved to SQLite database")
269
+ except Exception as e:
270
+ logger.error(f"Error saving to SQLite database: {e}")
271
+
272
+ # Also save to JSON for backward compatibility
273
+ return save_json(lst)
274
+
275
+ # ────────────────────────── 4. URL HELPERS ──────────────────────────
276
+ def direct_url(hf_url):
277
+ m = re.match(r"https?://huggingface\.co/spaces/([^/]+)/([^/?#]+)", hf_url)
278
+ if not m:
279
+ return hf_url
280
+ owner, name = m.groups()
281
+ owner = owner.lower()
282
+ name = name.replace('.', '-').replace('_', '-').lower()
283
+ return f"https://{owner}-{name}.hf.space"
284
+
285
+ def screenshot_url(url):
286
+ return f"https://image.thum.io/get/fullpage/{url}"
287
+
288
+ def process_url_for_preview(url):
289
+ """Returns (preview_url, mode)"""
290
+ # Handle blocked domains first
291
+ if any(d for d in BLOCKED_DOMAINS if d in url):
292
+ return screenshot_url(url), "snapshot"
293
+
294
+ # Special case handling for problematic URLs
295
+ if "vibe-coding-tetris" in url or "World-of-Tank-GAME" in url or "Minesweeper-Game" in url:
296
+ return screenshot_url(url), "snapshot"
297
+
298
+ # General HF space handling
299
+ try:
300
+ if "huggingface.co/spaces" in url:
301
+ parts = url.rstrip("/").split("/")
302
+ if len(parts) >= 5:
303
+ owner = parts[-2]
304
+ name = parts[-1]
305
+ embed_url = f"https://huggingface.co/spaces/{owner}/{name}/embed"
306
+ return embed_url, "iframe"
307
+ except Exception:
308
+ return screenshot_url(url), "snapshot"
309
+
310
+ # Default handling
311
+ return url, "iframe"
312
+
313
+ # ────────────────────────── 5. API ROUTES ──────────────────────────
314
+ @app.route('/api/category')
315
+ def api_category():
316
+ cat = request.args.get('name', '')
317
+ urls = CATEGORIES.get(cat, [])
318
+ return jsonify([
319
+ {
320
+ "title": url.split('/')[-1],
321
+ "owner": url.split('/')[-2] if '/spaces/' in url else '',
322
+ "iframe": direct_url(url),
323
+ "shot": screenshot_url(url),
324
+ "hf": url
325
+ } for url in urls
326
+ ])
327
+
328
+ @app.route('/api/favorites')
329
+ def api_favorites():
330
+ # Load URLs from SQLite database
331
+ urls = load_db()
332
+
333
+ page = int(request.args.get('page', 1))
334
+ per_page = int(request.args.get('per_page', 9))
335
+
336
+ total_pages = max(1, (len(urls) + per_page - 1) // per_page)
337
+ start = (page - 1) * per_page
338
+ end = min(start + per_page, len(urls))
339
+
340
+ urls_page = urls[start:end]
341
+
342
+ result = []
343
+ for url in urls_page:
344
+ try:
345
+ preview_url, mode = process_url_for_preview(url)
346
+ result.append({
347
+ "title": url.split('/')[-1],
348
+ "url": url,
349
+ "preview_url": preview_url,
350
+ "mode": mode
351
+ })
352
+ except Exception:
353
+ # Fallback to screenshot mode
354
+ result.append({
355
+ "title": url.split('/')[-1],
356
+ "url": url,
357
+ "preview_url": screenshot_url(url),
358
+ "mode": "snapshot"
359
+ })
360
+
361
+ return jsonify({
362
+ "items": result,
363
+ "page": page,
364
+ "total_pages": total_pages
365
+ })
366
+
367
+ @app.route('/api/url/add', methods=['POST'])
368
+ def add_url():
369
+ url = request.form.get('url', '').strip()
370
+ if not url:
371
+ return jsonify({"success": False, "message": "URL is required"})
372
+
373
+ # Check if URL already exists in database
374
+ if not add_url_to_sqlite(url):
375
+ return jsonify({"success": False, "message": "URL already exists"})
376
+
377
+ # Also update JSON file for backward compatibility
378
+ data = load_json()
379
+ if url not in data:
380
+ data.insert(0, url)
381
+ save_json(data)
382
+
383
+ return jsonify({"success": True, "message": "URL added successfully"})
384
+
385
+ @app.route('/api/url/update', methods=['POST'])
386
+ def update_url():
387
+ old = request.form.get('old', '')
388
+ new = request.form.get('new', '').strip()
389
+
390
+ if not new:
391
+ return jsonify({"success": False, "message": "New URL is required"})
392
+
393
+ # Update in SQLite DB
394
+ if not update_url_in_sqlite(old, new):
395
+ return jsonify({"success": False, "message": "URL not found or new URL already exists"})
396
+
397
+ # Also update JSON file for backward compatibility
398
+ data = load_json()
399
+ try:
400
+ idx = data.index(old)
401
+ data[idx] = new
402
+ save_json(data)
403
+ except ValueError:
404
+ # If URL not in JSON, add it
405
+ data.append(new)
406
+ save_json(data)
407
+
408
+ return jsonify({"success": True, "message": "URL updated successfully"})
409
+
410
+ @app.route('/api/url/delete', methods=['POST'])
411
+ def delete_url():
412
+ url = request.form.get('url', '')
413
+
414
+ # Delete from SQLite DB
415
+ if not delete_url_from_sqlite(url):
416
+ return jsonify({"success": False, "message": "URL not found"})
417
+
418
+ # Also update JSON file for backward compatibility
419
+ data = load_json()
420
+ try:
421
+ data.remove(url)
422
+ save_json(data)
423
+ except ValueError:
424
+ pass
425
+
426
+ return jsonify({"success": True, "message": "URL deleted successfully"})
427
+
428
+ # ────────────────────────── 6. MAIN ROUTES ──────────────────────────
429
+ @app.route('/')
430
+ def home():
431
+ os.makedirs('templates', exist_ok=True)
432
+
433
+ with open('templates/index.html', 'w', encoding='utf-8') as fp:
434
+ fp.write(r'''<!DOCTYPE html>
435
+ <html>
436
+ <head>
437
+ <meta charset="utf-8">
438
+ <meta name="viewport" content="width=device-width, initial-scale=1">
439
+ <title>Web Gallery</title>
440
+ <style>
441
+ @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@300;600&display=swap');
442
+ body{margin:0;font-family:Nunito,sans-serif;background:#f6f8fb;}
443
+ .tabs{display:flex;flex-wrap:wrap;gap:8px;padding:16px;}
444
+ .tab{padding:6px 14px;border:none;border-radius:18px;background:#e2e8f0;font-weight:600;cursor:pointer;}
445
+ .tab.active{background:#a78bfa;color:#1a202c;}
446
+ .tab.manage{background:#ff6e91;color:white;}
447
+ .tab.manage.active{background:#ff2d62;color:white;}
448
+ .grid{display:grid;grid-template-columns:repeat(3,1fr);gap:14px;padding:0 16px 60px;}
449
+ @media(max-width:800px){.grid{grid-template-columns:1fr;}}
450
+ .card{background:#fff;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,.08);overflow:hidden;height:420px;display:flex;flex-direction:column;position:relative;}
451
+ .frame{flex:1;position:relative;overflow:hidden;}
452
+ .frame iframe{position:absolute;width:166.667%;height:166.667%;transform:scale(.6);transform-origin:top left;border:0;}
453
+ .frame img{width:100%;height:100%;object-fit:cover;}
454
+ .card-label{position:absolute;top:10px;left:10px;padding:4px 8px;border-radius:4px;font-size:11px;font-weight:bold;z-index:100;text-transform:uppercase;letter-spacing:0.5px;box-shadow:0 2px 4px rgba(0,0,0,0.2);}
455
+ .label-live{background:linear-gradient(135deg, #00c6ff, #0072ff);color:white;}
456
+ .label-static{background:linear-gradient(135deg, #ff9a9e, #fad0c4);color:#333;}
457
+ .foot{height:44px;background:#fafafa;display:flex;align-items:center;justify-content:center;border-top:1px solid #eee;}
458
+ .foot a{font-size:.82rem;font-weight:700;color:#4a6dd8;text-decoration:none;}
459
+ .pagination{display:flex;justify-content:center;margin:20px 0;gap:10px;}
460
+ .pagination button{padding:5px 15px;border:none;border-radius:20px;background:#e2e8f0;cursor:pointer;}
461
+ .pagination button:disabled{opacity:0.5;cursor:not-allowed;}
462
+ .manage-panel{background:white;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,.08);margin:16px;padding:20px;}
463
+ .form-group{margin-bottom:15px;}
464
+ .form-group label{display:block;margin-bottom:5px;font-weight:600;}
465
+ .form-control{width:100%;padding:8px;border:1px solid #ddd;border-radius:4px;box-sizing:border-box;}
466
+ .btn{padding:8px 15px;border:none;border-radius:4px;cursor:pointer;font-weight:600;}
467
+ .btn-primary{background:#4a6dd8;color:white;}
468
+ .btn-danger{background:#e53e3e;color:white;}
469
+ .btn-success{background:#38a169;color:white;}
470
+ .status{padding:10px;margin:10px 0;border-radius:4px;display:none;}
471
+ .status.success{display:block;background:#c6f6d5;color:#22543d;}
472
+ .status.error{display:block;background:#fed7d7;color:#822727;}
473
+ .url-list{margin:20px 0;border:1px solid #eee;border-radius:4px;max-height:300px;overflow-y:auto;}
474
+ .url-item{padding:10px;border-bottom:1px solid #eee;display:flex;justify-content:space-between;align-items:center;}
475
+ .url-item:last-child{border-bottom:none;}
476
+ .url-controls{display:flex;gap:5px;}
477
+ </style>
478
+ </head>
479
+ <body>
480
+ <header style="text-align: center; padding: 20px; background: linear-gradient(135deg, #f6f8fb, #e2e8f0); border-bottom: 1px solid #ddd;">
481
+ <h1 style="margin-bottom: 10px;">🌟 AI Favorite Sites</h1>
482
+ <p class="description" style="margin-bottom: 15px;">
483
+ 🚀 <strong>Free AI Spaces & Website Gallery</strong> ✨ Save and manage your favorite sites! Supports <span style="background: linear-gradient(135deg, #00c6ff, #0072ff); color: white; padding: 2px 6px; border-radius: 4px; font-size: 12px;">LIVE</span> and <span style="background: linear-gradient(135deg, #ff9a9e, #fad0c4); color: #333; padding: 2px 6px; border-radius: 4px; font-size: 12px;">Static</span> preview modes.
484
+ </p>
485
+ <p>
486
+ <a href="https://discord.gg/openfreeai" target="_blank"><img src="https://img.shields.io/static/v1?label=Discord&message=Openfree%20AI&color=%230000ff&labelColor=%23800080&logo=discord&logoColor=white&style=for-the-badge" alt="badge"></a>
487
+ </p>
488
+ </header>
489
+ <div class="tabs" id="tabs"></div>
490
+ <div id="content"></div>
491
+
492
+ <script>
493
+ // Basic configuration
494
+ const cats = {{cats|tojson}};
495
+ const tabs = document.getElementById('tabs');
496
+ const content = document.getElementById('content');
497
+ let active = "";
498
+ let currentPage = 1;
499
+
500
+ // Simple utility functions
501
+ function loadHTML(url, callback) {
502
+ const xhr = new XMLHttpRequest();
503
+ xhr.open('GET', url, true);
504
+ xhr.onreadystatechange = function() {
505
+ if (xhr.readyState === 4 && xhr.status === 200) {
506
+ callback(xhr.responseText);
507
+ }
508
+ };
509
+ xhr.send();
510
+ }
511
+
512
+ function makeRequest(url, method, data, callback) {
513
+ const xhr = new XMLHttpRequest();
514
+ xhr.open(method, url, true);
515
+ xhr.onreadystatechange = function() {
516
+ if (xhr.readyState === 4 && xhr.status === 200) {
517
+ callback(JSON.parse(xhr.responseText));
518
+ }
519
+ };
520
+ if (method === 'POST') {
521
+ xhr.send(data);
522
+ } else {
523
+ xhr.send();
524
+ }
525
+ }
526
+
527
+ function updateTabs() {
528
+ Array.from(tabs.children).forEach(b => {
529
+ b.classList.toggle('active', b.dataset.c === active);
530
+ });
531
+ }
532
+
533
+ // Tab handlers
534
+ function loadCategory(cat) {
535
+ if(cat === active) return;
536
+ active = cat;
537
+ updateTabs();
538
+
539
+ content.innerHTML = '<p style="text-align:center;padding:40px">Loading…</p>';
540
+
541
+ makeRequest('/api/category?name=' + encodeURIComponent(cat), 'GET', null, function(data) {
542
+ let html = '<div class="grid">';
543
+
544
+ data.forEach(item => {
545
+ html += `
546
+ <div class="card">
547
+ <div class="card-label label-live">LIVE</div>
548
+ <div class="frame">
549
+ <iframe src="${item.iframe}" loading="lazy" sandbox="allow-forms allow-modals allow-popups allow-same-origin allow-scripts allow-downloads"></iframe>
550
+ </div>
551
+ <div class="foot">
552
+ <a href="${item.hf}" target="_blank">${item.title}</a>
553
+ </div>
554
+ </div>
555
+ `;
556
+ });
557
+
558
+ html += '</div>';
559
+ content.innerHTML = html;
560
+ });
561
+ }
562
+
563
+ function loadFavorites(page) {
564
+ if(active === 'Favorites' && currentPage === page) return;
565
+ active = 'Favorites';
566
+ currentPage = page || 1;
567
+ updateTabs();
568
+
569
+ content.innerHTML = '<p style="text-align:center;padding:40px">Loading…</p>';
570
+
571
+ makeRequest('/api/favorites?page=' + currentPage, 'GET', null, function(data) {
572
+ let html = '<div class="grid">';
573
+
574
+ if(data.items.length === 0) {
575
+ html += '<p style="grid-column:1/-1;text-align:center;padding:40px">No favorites saved yet.</p>';
576
+ } else {
577
+ data.items.forEach(item => {
578
+ if(item.mode === 'snapshot') {
579
+ html += `
580
+ <div class="card">
581
+ <div class="card-label label-static">Static</div>
582
+ <div class="frame">
583
+ <img src="${item.preview_url}" loading="lazy">
584
+ </div>
585
+ <div class="foot">
586
+ <a href="${item.url}" target="_blank">${item.title}</a>
587
+ </div>
588
+ </div>
589
+ `;
590
+ } else {
591
+ html += `
592
+ <div class="card">
593
+ <div class="card-label label-live">LIVE</div>
594
+ <div class="frame">
595
+ <iframe src="${item.preview_url}" loading="lazy" sandbox="allow-forms allow-modals allow-popups allow-same-origin allow-scripts allow-downloads"></iframe>
596
+ </div>
597
+ <div class="foot">
598
+ <a href="${item.url}" target="_blank">${item.title}</a>
599
+ </div>
600
+ </div>
601
+ `;
602
+ }
603
+ });
604
+ }
605
+
606
+ html += '</div>';
607
+
608
+ // Add pagination
609
+ html += `
610
+ <div class="pagination">
611
+ <button ${currentPage <= 1 ? 'disabled' : ''} onclick="loadFavorites(${currentPage-1})">« Previous</button>
612
+ <span>Page ${currentPage} of ${data.total_pages}</span>
613
+ <button ${currentPage >= data.total_pages ? 'disabled' : ''} onclick="loadFavorites(${currentPage+1})">Next »</button>
614
+ </div>
615
+ `;
616
+
617
+ content.innerHTML = html;
618
+ });
619
+ }
620
+
621
+ function loadManage() {
622
+ if(active === 'Manage') return;
623
+ active = 'Manage';
624
+ updateTabs();
625
+
626
+ content.innerHTML = `
627
+ <div class="manage-panel">
628
+ <h2>Add New URL</h2>
629
+ <div class="form-group">
630
+ <label for="new-url">URL</label>
631
+ <input type="text" id="new-url" class="form-control" placeholder="https://example.com">
632
+ </div>
633
+ <button onclick="addUrl()" class="btn btn-primary">Add URL</button>
634
+ <div id="add-status" class="status"></div>
635
+
636
+ <h2>Manage Saved URLs</h2>
637
+ <div id="url-list" class="url-list">Loading...</div>
638
+ </div>
639
+ `;
640
+
641
+ loadUrlList();
642
+ }
643
+
644
+ // URL management functions
645
+ function loadUrlList() {
646
+ makeRequest('/api/favorites?per_page=100', 'GET', null, function(data) {
647
+ const urlList = document.getElementById('url-list');
648
+
649
+ if(data.items.length === 0) {
650
+ urlList.innerHTML = '<p style="text-align:center;padding:20px">No URLs saved yet.</p>';
651
+ return;
652
+ }
653
+
654
+ let html = '';
655
+ data.items.forEach(item => {
656
+ // Escape the URL to prevent JavaScript injection when used in onclick handlers
657
+ const escapedUrl = item.url.replace(/'/g, "\\'");
658
+
659
+ html += `
660
+ <div class="url-item">
661
+ <div>${item.url}</div>
662
+ <div class="url-controls">
663
+ <button class="btn" onclick="editUrl('${escapedUrl}')">Edit</button>
664
+ <button class="btn btn-danger" onclick="deleteUrl('${escapedUrl}')">Delete</button>
665
+ </div>
666
+ </div>
667
+ `;
668
+ });
669
+
670
+ urlList.innerHTML = html;
671
+ });
672
+ }
673
+
674
+ function addUrl() {
675
+ const url = document.getElementById('new-url').value.trim();
676
+
677
+ if(!url) {
678
+ showStatus('add-status', 'Please enter a URL', false);
679
+ return;
680
+ }
681
+
682
+ const formData = new FormData();
683
+ formData.append('url', url);
684
+
685
+ makeRequest('/api/url/add', 'POST', formData, function(data) {
686
+ showStatus('add-status', data.message, data.success);
687
+ if(data.success) {
688
+ document.getElementById('new-url').value = '';
689
+ loadUrlList();
690
+ // If currently in Favorites tab, reload to see changes immediately
691
+ if(active === 'Favorites') {
692
+ loadFavorites(currentPage);
693
+ }
694
+ }
695
+ });
696
+ }
697
+
698
+ function editUrl(url) {
699
+ // Decode URL if it was previously escaped
700
+ const decodedUrl = url.replace(/\\'/g, "'");
701
+ const newUrl = prompt('Edit URL:', decodedUrl);
702
+
703
+ if(!newUrl || newUrl === decodedUrl) return;
704
+
705
+ const formData = new FormData();
706
+ formData.append('old', decodedUrl);
707
+ formData.append('new', newUrl);
708
+
709
+ makeRequest('/api/url/update', 'POST', formData, function(data) {
710
+ if(data.success) {
711
+ loadUrlList();
712
+ // If currently in Favorites tab, reload to see changes immediately
713
+ if(active === 'Favorites') {
714
+ loadFavorites(currentPage);
715
+ }
716
+ } else {
717
+ alert(data.message);
718
+ }
719
+ });
720
+ }
721
+
722
+ function deleteUrl(url) {
723
+ // Decode URL if it was previously escaped
724
+ const decodedUrl = url.replace(/\\'/g, "'");
725
+ if(!confirm('Are you sure you want to delete this URL?')) return;
726
+
727
+ const formData = new FormData();
728
+ formData.append('url', decodedUrl);
729
+
730
+ makeRequest('/api/url/delete', 'POST', formData, function(data) {
731
+ if(data.success) {
732
+ loadUrlList();
733
+ // If currently in Favorites tab, reload to see changes immediately
734
+ if(active === 'Favorites') {
735
+ loadFavorites(currentPage);
736
+ }
737
+ } else {
738
+ alert(data.message);
739
+ }
740
+ });
741
+ }
742
+
743
+ function showStatus(id, message, success) {
744
+ const status = document.getElementById(id);
745
+ status.textContent = message;
746
+ status.className = success ? 'status success' : 'status error';
747
+ setTimeout(() => {
748
+ status.className = 'status';
749
+ }, 3000);
750
+ }
751
+
752
+ // Create tabs
753
+ // Favorites tab first
754
+ const favTab = document.createElement('button');
755
+ favTab.className = 'tab';
756
+ favTab.textContent = 'Favorites';
757
+ favTab.dataset.c = 'Favorites';
758
+ favTab.onclick = function() { loadFavorites(1); };
759
+ tabs.appendChild(favTab);
760
+
761
+ // Category tabs
762
+ cats.forEach(c => {
763
+ const b = document.createElement('button');
764
+ b.className = 'tab';
765
+ b.textContent = c;
766
+ b.dataset.c = c;
767
+ b.onclick = function() { loadCategory(c); };
768
+ tabs.appendChild(b);
769
+ });
770
+
771
+ // Manage tab last
772
+ const manageTab = document.createElement('button');
773
+ manageTab.className = 'tab manage';
774
+ manageTab.textContent = 'Manage';
775
+ manageTab.dataset.c = 'Manage';
776
+ manageTab.onclick = function() { loadManage(); };
777
+ tabs.appendChild(manageTab);
778
+
779
+ // Start with Favorites tab
780
+ loadFavorites(1);
781
+ </script>
782
+ </body>
783
+ </html>''')
784
+
785
+ # Return the rendered template
786
+ return render_template('index.html', cats=list(CATEGORIES.keys()))
787
+
788
+ # Initialize database on startup
789
+ init_db()
790
+
791
+ # Define a function to ensure database consistency
792
+ def ensure_db_consistency():
793
+ """Make sure both databases are in sync"""
794
+ try:
795
+ # Get URLs from both sources
796
+ sqlite_urls = load_db_sqlite()
797
+ json_urls = load_json()
798
+
799
+ # Combine and deduplicate
800
+ all_urls = list(set(sqlite_urls + json_urls))
801
+
802
+ # If there are differences, update both databases
803
+ if len(all_urls) != len(sqlite_urls) or len(all_urls) != len(json_urls):
804
+ logger.info("Database inconsistency detected, synchronizing...")
805
+ # Save to both databases
806
+ save_db(all_urls)
807
+
808
+ # Double-check if save was successful
809
+ sqlite_check = load_db_sqlite()
810
+ json_check = load_json()
811
+
812
+ if len(sqlite_check) != len(all_urls) or len(json_check) != len(all_urls):
813
+ logger.error(f"Database synchronization failed! SQLite: {len(sqlite_check)}, JSON: {len(json_check)}, Expected: {len(all_urls)}")
814
+ else:
815
+ logger.info("Database synchronization successful")
816
+ except Exception as e:
817
+ logger.error(f"Error during database consistency check: {e}")
818
+
819
+ # For Flask 2.0+ compatibility
820
+ @app.before_request
821
+ def before_request_func():
822
+ # Use a flag to run this only once
823
+ if not hasattr(app, '_got_first_request'):
824
+ ensure_db_consistency()
825
+ app._got_first_request = True
826
+
827
+ # Log database status
828
+ logger.info(f"Database status - SQLite: {len(load_db_sqlite())} URLs, JSON: {len(load_json())} URLs")
829
+
830
+ if __name__ == '__main__':
831
+ app.run(host='0.0.0.0', port=7860)