ginipick commited on
Commit
2b17ff6
·
verified ·
1 Parent(s): 47115f3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +545 -353
app.py CHANGED
@@ -1,370 +1,562 @@
1
- import os
2
- import gradio as gr
3
- import json
4
- import logging
5
- import torch
6
- from PIL import Image
7
- import spaces
8
- from diffusers import DiffusionPipeline, AutoencoderTiny, AutoencoderKL
9
- from live_preview_helpers import calculate_shift, retrieve_timesteps, flux_pipe_call_that_returns_an_iterable_of_images
10
- from huggingface_hub import hf_hub_download, HfFileSystem, ModelCard, snapshot_download
11
- import copy
12
- import random
13
- import time
14
- from transformers import pipeline
15
- import sqlite3
16
- from datetime import datetime
17
-
18
- # 데이터베이스 초기화
19
- def init_db():
20
- conn = sqlite3.connect('gallery.db')
21
- c = conn.cursor()
22
- c.execute('''CREATE TABLE IF NOT EXISTS images
23
- (id INTEGER PRIMARY KEY AUTOINCREMENT,
24
- model_name TEXT,
25
- prompt TEXT,
26
- image_path TEXT,
27
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')
28
- conn.commit()
29
- conn.close()
30
-
31
- # 이미지 저장 함수
32
- def save_image(image, model_name, prompt):
33
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
34
- filename = f"gallery_{timestamp}.png"
35
- image.save(os.path.join("gallery", filename))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
- conn = sqlite3.connect('gallery.db')
38
- c = conn.cursor()
39
- c.execute("INSERT INTO images (model_name, prompt, image_path) VALUES (?, ?, ?)",
40
- (model_name, prompt, filename))
41
- conn.commit()
42
- conn.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
- # 갤러리 이미지 로드 함수
45
- def load_gallery_images():
46
- conn = sqlite3.connect('gallery.db')
47
- c = conn.cursor()
48
- c.execute("SELECT model_name, prompt, image_path FROM images ORDER BY created_at DESC")
49
- rows = c.fetchall()
50
- conn.close()
 
 
 
 
 
 
 
 
 
 
 
51
 
52
- return [(os.path.join("gallery", row[2]), f"{row[0]}: {row[1]}") for row in rows]
53
-
54
- # CPU에서 실행되는 번역기 초기화
55
- translator = pipeline("translation", model="Helsinki-NLP/opus-mt-ko-en", device=-1)
56
-
57
- # 프롬프트 처리 함수
58
- def process_prompt(prompt):
59
- if any('\u3131' <= char <= '\u3163' or '\uac00' <= char <= '\ud7a3' for char in prompt):
60
- translated = translator(prompt)[0]['translation_text']
61
- return prompt, translated
62
- return prompt, prompt
63
-
64
-
65
- KEY_JSON = os.getenv("KEY_JSON")
66
- with open(KEY_JSON, 'r') as f:
67
- loras = json.load(f)
68
-
69
- # 기본 모델 초기화
70
- dtype = torch.bfloat16
71
- device = "cuda" if torch.cuda.is_available() else "cpu"
72
- base_model = "black-forest-labs/FLUX.1-dev"
73
-
74
- taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device)
75
- good_vae = AutoencoderKL.from_pretrained(base_model, subfolder="vae", torch_dtype=dtype).to(device)
76
- pipe = DiffusionPipeline.from_pretrained(base_model, torch_dtype=dtype, vae=taef1).to(device)
77
-
78
- MAX_SEED = 2**32-1
79
-
80
- pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)
81
-
82
- class calculateDuration:
83
- def __init__(self, activity_name=""):
84
- self.activity_name = activity_name
85
-
86
- def __enter__(self):
87
- self.start_time = time.time()
88
- return self
89
 
90
- def __exit__(self, exc_type, exc_value, traceback):
91
- self.end_time = time.time()
92
- self.elapsed_time = self.end_time - self.start_time
93
- if self.activity_name:
94
- print(f"Elapsed time for {self.activity_name}: {self.elapsed_time:.6f} seconds")
95
- else:
96
- print(f"Elapsed time: {self.elapsed_time:.6f} seconds")
97
-
98
- def update_selection(evt: gr.SelectData, width, height):
99
- selected_lora = loras[evt.index]
100
- new_placeholder = f"{selected_lora['title']}를 위한 프롬프트를 입력하세요"
101
- lora_repo = selected_lora["repo"]
102
- updated_text = f"### 선택됨: [{lora_repo}](https://huggingface.co/{lora_repo}) ✨"
103
- if "aspect" in selected_lora:
104
- if selected_lora["aspect"] == "portrait":
105
- width = 768
106
- height = 1024
107
- elif selected_lora["aspect"] == "landscape":
108
- width = 1024
109
- height = 768
110
- else:
111
- width = 1024
112
- height = 1024
113
- return (
114
- gr.update(placeholder=new_placeholder),
115
- updated_text,
116
- evt.index,
117
- width,
118
- height,
119
- )
120
-
121
- @spaces.GPU(duration=70)
122
- def generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, progress):
123
- pipe.to("cuda")
124
- generator = torch.Generator(device="cuda").manual_seed(seed)
125
- with calculateDuration("이미지 생성"):
126
- # Generate image
127
- for img in pipe.flux_pipe_call_that_returns_an_iterable_of_images(
128
- prompt=prompt_mash,
129
- num_inference_steps=steps,
130
- guidance_scale=cfg_scale,
131
- width=width,
132
- height=height,
133
- generator=generator,
134
- joint_attention_kwargs={"scale": lora_scale},
135
- output_type="pil",
136
- good_vae=good_vae,
137
- ):
138
- yield img
139
-
140
- @spaces.GPU(duration=70)
141
- def run_lora(prompt, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, lora_scale, progress=gr.Progress(track_tqdm=True)):
142
- if selected_index is None:
143
- raise gr.Error("진행하기 전에 LoRA를 선택해야 합니다.")
144
 
145
- original_prompt, english_prompt = process_prompt(prompt)
 
 
 
 
 
 
 
146
 
147
- selected_lora = loras[selected_index]
148
- lora_path = selected_lora["repo"]
149
- trigger_word = selected_lora["trigger_word"]
150
- if(trigger_word):
151
- if "trigger_position" in selected_lora:
152
- if selected_lora["trigger_position"] == "prepend":
153
- prompt_mash = f"{trigger_word} {english_prompt}"
154
- else:
155
- prompt_mash = f"{english_prompt} {trigger_word}"
156
- else:
157
- prompt_mash = f"{trigger_word} {english_prompt}"
158
- else:
159
- prompt_mash = english_prompt
160
-
161
- with calculateDuration("LoRA 언로드"):
162
- pipe.unload_lora_weights()
163
-
164
- # LoRA 가중치 로드
165
- with calculateDuration(f"{selected_lora['title']}의 LoRA 가중치 로드"):
166
- if "weights" in selected_lora:
167
- pipe.load_lora_weights(lora_path, weight_name=selected_lora["weights"])
168
- else:
169
- pipe.load_lora_weights(lora_path)
170
-
171
- # 재현성을 위한 시드 설정
172
- with calculateDuration("시드 무작위화"):
173
- if randomize_seed:
174
- seed = random.randint(0, MAX_SEED)
175
-
176
- image_generator = generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, progress)
177
 
178
- # 최종 이미지를 얻기 위해 제너레이터 소비
179
- final_image = None
180
- step_counter = 0
181
- for image in image_generator:
182
- step_counter+=1
183
- final_image = image
184
- progress_bar = f'<div class="progress-container"><div class="progress-bar" style="--current: {step_counter}; --total: {steps};"></div></div>'
185
- yield image, seed, gr.update(value=progress_bar, visible=True), original_prompt, english_prompt
186
 
187
- # 갤러리에 이미지 저장
188
- save_image(final_image, selected_lora['title'], original_prompt)
189
 
190
- yield final_image, seed, gr.update(value=progress_bar, visible=False), original_prompt, english_prompt
191
-
192
- def get_huggingface_safetensors(link):
193
- split_link = link.split("/")
194
- if(len(split_link) == 2):
195
- model_card = ModelCard.load(link)
196
- base_model = model_card.data.get("base_model")
197
- print(base_model)
198
- if((base_model != "black-forest-labs/FLUX.1-dev") and (base_model != "black-forest-labs/FLUX.1-schnell")):
199
- raise Exception("Not a FLUX LoRA!")
200
- image_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None)
201
- trigger_word = model_card.data.get("instance_prompt", "")
202
- image_url = f"https://huggingface.co/{link}/resolve/main/{image_path}" if image_path else None
203
- fs = HfFileSystem()
204
- try:
205
- list_of_files = fs.ls(link, detail=False)
206
- for file in list_of_files:
207
- if(file.endswith(".safetensors")):
208
- safetensors_name = file.split("/")[-1]
209
- if (not image_url and file.lower().endswith((".jpg", ".jpeg", ".png", ".webp"))):
210
- image_elements = file.split("/")
211
- image_url = f"https://huggingface.co/{link}/resolve/main/{image_elements[-1]}"
212
- except Exception as e:
213
- print(e)
214
- gr.Warning(f"You didn't include a link neither a valid Hugging Face repository with a *.safetensors LoRA")
215
- raise Exception(f"You didn't include a link neither a valid Hugging Face repository with a *.safetensors LoRA")
216
- return split_link[1], link, safetensors_name, trigger_word, image_url
217
-
218
- def check_custom_model(link):
219
- if(link.startswith("https://")):
220
- if(link.startswith("https://huggingface.co") or link.startswith("https://www.huggingface.co")):
221
- link_split = link.split("huggingface.co/")
222
- return get_huggingface_safetensors(link_split[1])
223
- else:
224
- return get_huggingface_safetensors(link)
225
-
226
- def add_custom_lora(custom_lora):
227
- global loras
228
- if(custom_lora):
229
- try:
230
- title, repo, path, trigger_word, image = check_custom_model(custom_lora)
231
- print(f"Loaded custom LoRA: {repo}")
232
- card = f'''
233
- <div class="custom_lora_card">
234
- <span>Loaded custom LoRA:</span>
235
- <div class="card_internal">
236
- <img src="{image}" />
237
- <div>
238
- <h3>{title}</h3>
239
- <small>{"Using: <code><b>"+trigger_word+"</code></b> as the trigger word" if trigger_word else "No trigger word found. If there's a trigger word, include it in your prompt"}<br></small>
240
- </div>
241
- </div>
242
- </div>
243
- '''
244
- existing_item_index = next((index for (index, item) in enumerate(loras) if item['repo'] == repo), None)
245
- if(not existing_item_index):
246
- new_item = {
247
- "image": image,
248
- "title": title,
249
- "repo": repo,
250
- "weights": path,
251
- "trigger_word": trigger_word
252
- }
253
- print(new_item)
254
- existing_item_index = len(loras)
255
- loras.append(new_item)
256
-
257
- return gr.update(visible=True, value=card), gr.update(visible=True), gr.Gallery(selected_index=None), f"Custom: {path}", existing_item_index, trigger_word
258
- except Exception as e:
259
- gr.Warning(f"Invalid LoRA: either you entered an invalid link, or a non-FLUX LoRA")
260
- return gr.update(visible=True, value=f"Invalid LoRA: either you entered an invalid link, a non-FLUX LoRA"), gr.update(visible=True), gr.update(), "", None, ""
261
- else:
262
- return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
263
-
264
- def remove_custom_lora():
265
- return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
266
-
267
- run_lora.zerogpu = True
268
-
269
- css = """
270
- footer {
271
- visibility: hidden;
 
 
 
 
 
 
 
 
 
 
272
  }
273
- """
274
-
275
- # 갤러리 디렉토리 생성
276
- if not os.path.exists('gallery'):
277
- os.makedirs('gallery')
278
 
279
- # 데이터베이스 초기화
280
- init_db()
 
 
 
281
 
282
- with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", css=css) as app:
283
- selected_index = gr.State(None)
 
 
 
 
 
 
 
 
 
284
 
285
- with gr.Tabs():
286
- with gr.TabItem("생성"):
287
- with gr.Row():
288
- with gr.Column(scale=3):
289
- prompt = gr.Textbox(label="프롬프트", lines=1, placeholder="LoRA를 선택한 후 프롬프트를 입력하세요 (한글 또는 영어)")
290
- with gr.Column(scale=1, elem_id="gen_column"):
291
- generate_button = gr.Button("생성", variant="primary", elem_id="gen_btn")
292
- with gr.Row():
293
- with gr.Column():
294
- selected_info = gr.Markdown("")
295
- gallery = gr.Gallery(
296
- [(item["image"], item["title"]) for item in loras],
297
- label="LoRA 갤러리",
298
- allow_preview=False,
299
- columns=5,
300
- elem_id="gallery"
301
- )
302
- with gr.Group():
303
- custom_lora = gr.Textbox(label="커스텀 LoRA", info="LoRA Hugging Face 경로", placeholder="multimodalart/vintage-ads-flux")
304
- gr.Markdown("[FLUX LoRA 목록 확인](https://huggingface.co/models?other=base_model:adapter:black-forest-labs/FLUX.1-dev)", elem_id="lora_list")
305
- custom_lora_info = gr.HTML(visible=False)
306
- custom_lora_button = gr.Button("커스텀 LoRA 제거", visible=False)
307
- with gr.Column():
308
- progress_bar = gr.Markdown(elem_id="progress",visible=False)
309
- result = gr.Image(label="생성된 이미지")
310
- original_prompt_display = gr.Textbox(label="원본 프롬프트")
311
- english_prompt_display = gr.Textbox(label="영어 프롬프트")
312
-
313
- with gr.Row():
314
- with gr.Accordion("고급 설정", open=False):
315
- with gr.Column():
316
- with gr.Row():
317
- cfg_scale = gr.Slider(label="CFG 스케일", minimum=1, maximum=20, step=0.5, value=3.5)
318
- steps = gr.Slider(label="스텝", minimum=1, maximum=50, step=1, value=28)
319
-
320
- with gr.Row():
321
- width = gr.Slider(label="너비", minimum=256, maximum=1536, step=64, value=1024)
322
- height = gr.Slider(label="높이", minimum=256, maximum=1536, step=64, value=1024)
323
-
324
- with gr.Row():
325
- randomize_seed = gr.Checkbox(True, label="시드 무작위화")
326
- seed = gr.Slider(label="시드", minimum=0, maximum=MAX_SEED, step=1, value=0, randomize=True)
327
- lora_scale = gr.Slider(label="LoRA 스케일", minimum=0, maximum=3, step=0.01, value=0.95)
328
-
329
- with gr.TabItem("갤러리"):
330
- gallery_images = gr.Gallery(
331
- load_gallery_images(),
332
- label="생성된 이미지 갤러리",
333
- columns=3,
334
- rows=3,
335
- height="auto"
336
- )
337
- refresh_button = gr.Button("갤러리 새로고침")
338
-
339
- gallery.select(
340
- update_selection,
341
- inputs=[width, height],
342
- outputs=[prompt, selected_info, selected_index, width, height]
343
- )
344
 
345
- custom_lora.input(
346
- add_custom_lora,
347
- inputs=[custom_lora],
348
- outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, prompt]
349
- )
350
 
351
- custom_lora_button.click(
352
- remove_custom_lora,
353
- outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, custom_lora]
354
- )
355
-
356
- gr.on(
357
- triggers=[generate_button.click, prompt.submit],
358
- fn=run_lora,
359
- inputs=[prompt, cfg_scale, steps, selected_index, randomize_seed,
360
- seed, width, height, lora_scale],
361
- outputs=[result, seed, progress_bar, original_prompt_display, english_prompt_display]
362
- )
363
 
364
- refresh_button.click(
365
- lambda: gr.update(value=load_gallery_images()),
366
- outputs=[gallery_images]
367
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
368
 
369
- app.queue()
370
- app.launch()
 
1
+ from flask import Flask, render_template, request, jsonify
2
+ import os, re, json
3
+
4
+ app = Flask(__name__)
5
+
6
+ # ────────────────────────── 1. CONFIGURATION ──────────────────────────
7
+
8
+ # Domains that commonly block iframes
9
+ BLOCKED_DOMAINS = [
10
+ "naver.com", "daum.net", "google.com",
11
+ "facebook.com", "instagram.com", "kakao.com",
12
+ "ycombinator.com"
13
+ ]
14
+
15
+ # ────────────────────────── 2. CURATED CATEGORIES ──────────────────────────
16
+ CATEGORIES = {
17
+ "Popular": [
18
+ "https://huggingface.co/spaces/openfree/AGI-Screenplay",
19
+ "https://huggingface.co/spaces/openfree/AGI-WebNovel",
20
+ "https://huggingface.co/spaces/openfree/AGI-NOVEL",
21
+ "https://huggingface.co/spaces/fantaxy/AGI-LEADERBOARD",
22
+ "https://cutechicken-3d-airforce-simulator.static.hf.space",
23
+ "https://huggingface.co/spaces/ginipick/Private-AI",
24
+ "https://huggingface.co/spaces/fantaxy/ofai-flx-logo",
25
+ "https://huggingface.co/spaces/aiqtech/FLUX-Ghibli-Studio-LoRA",
26
+ "https://huggingface.co/spaces/seawolf2357/REALVISXL-V5",
27
+ "https://huggingface.co/spaces/fantos/flx8lora",
28
+ "https://huggingface.co/spaces/ginipick/Realtime-FLUX",
29
+ "https://huggingface.co/spaces/fantaxy/flx-pulid",
30
+ "https://huggingface.co/spaces/ginipick/FLUX-Prompt-Generator",
31
+ "https://huggingface.co/spaces/aiqtech/kofaceid",
32
+ "https://huggingface.co/spaces/aiqtech/flxgif",
33
+ "https://huggingface.co/spaces/fantos/flxfashmodel",
34
+ "https://huggingface.co/spaces/fantos/flxcontrol",
35
+ "https://huggingface.co/spaces/fantos/textcutobject",
36
+ "https://huggingface.co/spaces/seawolf2357/flxloraexp",
37
+ "https://huggingface.co/spaces/fantaxy/flxloraexp",
38
+ "https://huggingface.co/spaces/aiqtech/imaginpaint",
39
+ "https://huggingface.co/spaces/ginipick/FLUXllama",
40
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored",
41
+ "https://huggingface.co/spaces/fantaxy/flx-upscale",
42
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored-video",
43
+ "https://huggingface.co/spaces/fantos/VoiceClone",
44
+ "https://huggingface.co/spaces/fantaxy/Rolls-Royce",
45
+ "https://huggingface.co/spaces/aiqtech/FLUX-military",
46
+ "https://huggingface.co/spaces/fantaxy/FLUX-Animations",
47
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored-video2",
48
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored-photo",
49
+ "https://huggingface.co/spaces/ginipick/Time-Stream",
50
+ "https://huggingface.co/spaces/seawolf2357/sd-prompt-gen",
51
+ "https://huggingface.co/spaces/openfree/MagicFace-V3",
52
+ "https://huggingface.co/spaces/Heartsync/adult",
53
+ "https://huggingface.co/spaces/Heartsync/wan2-1-fast-security",
54
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored-REAL",
55
+ "https://huggingface.co/spaces/seawolf2357/img2vid",
56
+ "https://huggingface.co/spaces/openfree/image-to-vector",
57
+ "https://huggingface.co/spaces/openfree/DreamO-video",
58
+ "https://huggingface.co/spaces/VIDraft/FramePack_rotate_landscape",
59
+ "https://huggingface.co/spaces/fantaxy/Sound-AI-SFX",
60
+ "https://huggingface.co/spaces/ginigen/VoiceClone-TTS",
61
+ "https://huggingface.co/spaces/Heartsync/FREE-NSFW-HUB",
62
+ "https://huggingface.co/spaces/Heartsync/NSFW-image",
63
+ "https://huggingface.co/spaces/Heartsync/NSFW-detection",
64
+ "https://huggingface.co/spaces/Heartsync/VEO3-RealTime",
65
+ "https://huggingface.co/spaces/ginigen/VEO3-Free",
66
+ "https://huggingface.co/spaces/ginigen/FLUX-Text-Tree-Image",
67
+ "https://huggingface.co/spaces/ginigen/text3d-r1",
68
+ "https://huggingface.co/spaces/VIDraft/stable-diffusion-3.5-large-turboX",
69
+
70
+ ],
71
+ "BEST": [
72
+ "https://huggingface.co/spaces/MaziyarPanahi/FACTS-Leaderboard",
73
+ "https://huggingface.co/spaces/ginigen/Flux-Kontext-Style",
74
+ "https://huggingface.co/spaces/openfree/Cycle-Navigator",
75
+ "https://huggingface.co/spaces/ginigen/Flux-Kontext-FaceLORA",
76
+ "https://huggingface.co/spaces/ginigen/Seedance-Free",
77
+ "https://huggingface.co/spaces/VIDraft/SOMA-AGI",
78
+ "https://huggingface.co/spaces/aiqtech/Heatmap-Leaderboard",
79
+ "https://huggingface.co/spaces/VIDraft/DNA-CASINO",
80
+ "https://huggingface.co/spaces/aiqtech/SOMA-Oriental",
81
+ "https://huggingface.co/spaces/fantaxy/YTB-TEST",
82
+ "https://huggingface.co/spaces/aiqtech/Contributors-Leaderboard",
83
+ "https://huggingface.co/spaces/ginigen/text3d-r1",
84
+ "https://huggingface.co/spaces/VIDraft/stable-diffusion-3.5-large-turboX",
85
+ "https://huggingface.co/spaces/openfree/Korean-Leaderboard",
86
+ "https://huggingface.co/spaces/fantos/flxcontrol",
87
+ "https://huggingface.co/spaces/aiqtech/FLUX-Ghibli-Studio-LoRA",
88
+ "https://huggingface.co/spaces/openfree/AI-Podcast",
89
+ "https://huggingface.co/spaces/ginigen/Workflow-Canvas",
90
+ "https://huggingface.co/spaces/ginigen/3D-LLAMA",
91
+ "https://huggingface.co/spaces/ginigen/VoiceClone-TTS",
92
+ "https://huggingface.co/spaces/VIDraft/ACE-Singer",
93
+ "https://huggingface.co/spaces/ginipick/AI-BOOK",
94
+ "https://huggingface.co/spaces/immunobiotech/drug-discovery",
95
+ "https://huggingface.co/spaces/VIDraft/Robo-Beam",
96
+ "https://huggingface.co/spaces/fantaxy/fantasy-novel",
97
+ "https://huggingface.co/spaces/immunobiotech/Gemini-MICHELIN",
98
+ "https://huggingface.co/spaces/openfree/Chart-GPT",
99
+ "https://huggingface.co/spaces/ginipick/NH-Korea",
100
+ "https://huggingface.co/spaces/VIDraft/Voice-Clone-Podcast",
101
+ "https://huggingface.co/spaces/ginipick/Private-AI",
102
+ "https://huggingface.co/spaces/ginigen/Flux-VIDEO",
103
+ "https://huggingface.co/spaces/openfree/open-GAMMA",
104
+ "https://huggingface.co/spaces/ginipick/PharmAI-Korea",
105
+ "https://huggingface.co/spaces/ginipick/Pharmacy",
106
+ "https://huggingface.co/spaces/ginipick/PDF-EXAM",
107
+ "https://huggingface.co/spaces/ginipick/IDEA-DESIGN",
108
+ "https://huggingface.co/spaces/openfree/DreamO-video",
109
+ "https://huggingface.co/spaces/ginipick/10m-marketing",
110
+ "https://huggingface.co/spaces/VIDraft/voice-trans",
111
+ "https://huggingface.co/spaces/VIDraft/NH-Prediction",
112
+ "https://huggingface.co/spaces/fantos/flx8lora",
113
+ "https://huggingface.co/spaces/ginigen/MagicFace-V3",
114
+ "https://huggingface.co/spaces/openfree/Live-Podcast",
115
+ "https://huggingface.co/spaces/seawolf2357/ocrlatex",
116
+ "https://huggingface.co/spaces/Heartsync/VEO3-RealTime",
117
+ "https://huggingface.co/spaces/ginigen/VEO3-Free",
118
+ "https://huggingface.co/spaces/openfree/MagicFace-V3",
119
+ "https://huggingface.co/spaces/aiqtech/FLUX-military",
120
+ "https://huggingface.co/spaces/fantaxy/flxloraexp",
121
+ "https://huggingface.co/spaces/Heartsync/WAN2-1-fast-T2V-FusioniX",
122
+ "https://huggingface.co/spaces/ginigen/FLUXllama-Multilingual",
123
+ "https://huggingface.co/spaces/Heartsync/wan2-1-fast-security",
124
+ "https://huggingface.co/spaces/fantaxy/Rolls-Royce",
125
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored-REAL",
126
+ "https://huggingface.co/spaces/ginipick/Realtime-FLUX",
127
+ "https://huggingface.co/spaces/aiqtech/imaginpaint",
128
+ "https://huggingface.co/spaces/aiqtech/flxgif",
129
+ "https://huggingface.co/spaces/fantos/flxfashmodel",
130
+ "https://huggingface.co/spaces/aiqtech/kofaceid",
131
+ "https://huggingface.co/spaces/ginipick/FLUX-Prompt-Generator",
132
+ "https://huggingface.co/spaces/seawolf2357/REALVISXL-V5",
133
+ "https://huggingface.co/spaces/fantaxy/FLUX-Animations",
134
+ "https://huggingface.co/spaces/fantaxy/flx-pulid",
135
+ "https://huggingface.co/spaces/fantaxy/ofai-flx-logo",
136
+ "https://huggingface.co/spaces/openfree/image-to-vector",
137
+ "https://huggingface.co/spaces/Heartsync/FREE-NSFW-HUB",
138
+ "https://huggingface.co/spaces/seawolf2357/sd-prompt-gen",
139
+ "https://huggingface.co/spaces/VIDraft/FramePack_rotate_landscape",
140
+ "https://huggingface.co/spaces/ginipick/FLUXllama",
141
+ "https://huggingface.co/spaces/Heartsync/NSFW-image",
142
+ "https://huggingface.co/spaces/seawolf2357/img2vid",
143
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored-video2",
144
+ "https://huggingface.co/spaces/Heartsync/NSFW-detection",
145
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored-video",
146
+ "https://huggingface.co/spaces/Heartsync/adult",
147
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored",
148
+ "https://huggingface.co/spaces/fantos/VoiceClone",
149
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored-photo",
150
+ "https://huggingface.co/spaces/fantaxy/flx-upscale",
151
+ "https://huggingface.co/spaces/seawolf2357/flxloraexp",
152
+ "https://huggingface.co/spaces/ginipick/Time-Stream",
153
+ "https://huggingface.co/spaces/fantos/textcutobject",
154
 
155
+
156
+ ],
157
+ "NEW": [
158
+ "https://huggingface.co/spaces/ginigen/Flux-Kontext-Style",
159
+ "https://cutechicken-3d-airforce-simulator.static.hf.space",
160
+ "https://huggingface.co/spaces/ginipick/Private-AI",
161
+ "https://huggingface.co/spaces/VIDraft/ACE-Singer",
162
+ "https://huggingface.co/spaces/ginipick/AI-BOOK",
163
+ "https://huggingface.co/spaces/openfree/Best-AI",
164
+ "https://huggingface.co/spaces/aiqtech/Heatmap-Leaderboard",
165
+ "https://huggingface.co/spaces/VIDraft/DNA-CASINO",
166
+ "https://huggingface.co/spaces/openfree/AGI-Screenplay",
167
+ "https://huggingface.co/spaces/openfree/AGI-WebNovel",
168
+ "https://huggingface.co/spaces/openfree/AGI-NOVEL",
169
+ "https://huggingface.co/spaces/fantaxy/AGI-LEADERBOARD",
170
+ "https://huggingface.co/spaces/ginigen/Seedance-Free",
171
+ "https://huggingface.co/spaces/aiqtech/SOMA-Oriental",
172
+ "https://huggingface.co/spaces/ginigen/Flux-Kontext-FaceLORA",
173
+ "https://huggingface.co/spaces/VIDraft/SOMA-AGI",
174
+ "https://huggingface.co/spaces/Heartsync/VEO3-RealTime",
175
+ "https://huggingface.co/spaces/openfree/Open-GAMMA",
176
+ "https://huggingface.co/spaces/ginigen/VEO3-Free",
177
+ "https://huggingface.co/spaces/Heartsync/WAN2-1-fast-T2V-FusioniX",
178
+ "https://huggingface.co/spaces/VIDraft/voice-trans",
179
+ "https://huggingface.co/spaces/VIDraft/Robo-Beam",
180
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored-REAL",
181
+ "https://huggingface.co/spaces/fantaxy/fantasy-novel",
182
+ "https://huggingface.co/spaces/openfree/Chart-GPT",
183
+ "https://huggingface.co/spaces/Heartsync/Novel-NSFW",
184
+ "https://huggingface.co/spaces/ginigen/FLUX-Ghibli-LoRA2",
185
+ "https://huggingface.co/spaces/Heartsync/WAN-VIDEO-AUDIO",
186
+ "https://huggingface.co/spaces/Heartsync/wan2-1-fast-security",
187
+ "https://huggingface.co/spaces/ginigen/Flux-VIDEO",
188
+ "https://huggingface.co/spaces/aiqcamp/REMOVAL-TEXT-IMAGE",
189
+ "https://huggingface.co/spaces/VIDraft/Mistral-RAG-BitSix",
190
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored-video2",
191
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored-video",
192
+ "https://huggingface.co/spaces/fantaxy/YTB-TEST",
193
+ "https://huggingface.co/spaces/Heartsync/FREE-NSFW-HUB",
194
+ "https://huggingface.co/spaces/Heartsync/adult",
195
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored-photo",
196
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored",
197
+ "https://huggingface.co/spaces/openfree/Live-Podcast",
198
+ "https://huggingface.co/spaces/openfree/AI-Podcast",
199
+ "https://huggingface.co/spaces/ginipick/NH-Korea",
200
+ "https://huggingface.co/spaces/VIDraft/NH-Prediction",
201
+ "https://huggingface.co/spaces/VIDraft/Voice-Clone-Podcast",
202
+ "https://huggingface.co/spaces/ginipick/PDF-EXAM",
203
+ "https://huggingface.co/spaces/openfree/Game-Gallery",
204
+ "https://huggingface.co/spaces/openfree/Vibe-Game",
205
+ "https://huggingface.co/spaces/ginipick/IDEA-DESIGN",
206
+ "https://huggingface.co/spaces/openfree/Cycle-Navigator",
207
+ "https://huggingface.co/spaces/openfree/DreamO-video",
208
+ "https://huggingface.co/spaces/Heartsync/NSFW-detection",
209
+
210
+
211
+ ],
212
+ "Productivity": [
213
+ "https://huggingface.co/spaces/aiqtech/Heatmap-Leaderboard",
214
+ "https://huggingface.co/spaces/VIDraft/DNA-CASINO",
215
+ "https://huggingface.co/spaces/openfree/Open-GAMMA",
216
+ "https://huggingface.co/spaces/VIDraft/Robo-Beam",
217
+ "https://huggingface.co/spaces/VIDraft/voice-trans",
218
+ "https://huggingface.co/spaces/Heartsync/FREE-NSFW-HUB",
219
+ "https://huggingface.co/spaces/openfree/Chart-GPT",
220
+ "https://huggingface.co/spaces/ginipick/AI-BOOK",
221
+ "https://huggingface.co/spaces/VIDraft/Voice-Clone-Podcast",
222
+ "https://huggingface.co/spaces/ginipick/PDF-EXAM",
223
+ "https://huggingface.co/spaces/ginigen/perflexity-clone",
224
+ "https://huggingface.co/spaces/ginipick/IDEA-DESIGN",
225
+ "https://huggingface.co/spaces/ginipick/10m-marketing",
226
+ "https://huggingface.co/spaces/openfree/Live-Podcast",
227
+ "https://huggingface.co/spaces/openfree/AI-Podcast",
228
+ "https://huggingface.co/spaces/ginipick/QR-Canvas-plus",
229
+ "https://huggingface.co/spaces/openfree/Badge",
230
+ "https://huggingface.co/spaces/VIDraft/mouse-webgen",
231
+ "https://huggingface.co/spaces/openfree/Vibe-Game",
232
+ "https://huggingface.co/spaces/VIDraft/NH-Prediction",
233
+ "https://huggingface.co/spaces/ginipick/NH-Korea",
234
+ "https://huggingface.co/spaces/openfree/Naming",
235
+ "https://huggingface.co/spaces/ginipick/Change-Hair",
236
+ ],
237
+ "Multimodal": [
238
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored-photo",
239
+ "https://huggingface.co/spaces/fantaxy/YTB-TEST",
240
+ "https://huggingface.co/spaces/ginigen/Seedance-Free",
241
+ "https://huggingface.co/spaces/Heartsync/VEO3-RealTime",
242
+ "https://huggingface.co/spaces/ginigen/VEO3-Free",
243
+ "https://huggingface.co/spaces/ginigen/VEO3-Directors",
244
+ "https://huggingface.co/spaces/Heartsync/WAN2-1-fast-T2V-FusioniX",
245
+ "https://huggingface.co/spaces/Heartsync/adult",
246
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored",
247
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored-video2",
248
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored-video",
249
+ "https://huggingface.co/spaces/Heartsync/WAN-VIDEO-AUDIO",
250
+ "https://huggingface.co/spaces/Heartsync/wan2-1-fast-security",
251
+ "https://huggingface.co/spaces/ginigen/Flux-VIDEO",
252
+ "https://huggingface.co/spaces/ginigen/3D-LLAMA-V1",
253
+ "https://huggingface.co/spaces/ginigen/Flux-VIDEO",
254
+ "https://huggingface.co/spaces/openfree/Multilingual-TTS",
255
+ "https://huggingface.co/spaces/VIDraft/ACE-Singer",
256
+ "https://huggingface.co/spaces/openfree/DreamO-video",
257
+ "https://huggingface.co/spaces/fantaxy/Sound-AI-SFX",
258
+ "https://huggingface.co/spaces/ginigen/SFX-Sound-magic",
259
+ "https://huggingface.co/spaces/ginigen/VoiceClone-TTS",
260
+ "https://huggingface.co/spaces/aiqcamp/ENGLISH-Speaking-Scoring",
261
+ "https://huggingface.co/spaces/fantaxy/Remove-Video-Background",
262
+ ],
263
+ "Professional": [
264
+ "https://huggingface.co/spaces/Heartsync/NSFW-novels",
265
+ "https://huggingface.co/spaces/aiqtech/SOMA-Oriental",
266
+ "https://huggingface.co/spaces/VIDraft/SOMA-AGI",
267
+ "https://huggingface.co/spaces/Heartsync/Novel-NSFW",
268
+ "https://huggingface.co/spaces/fantaxy/fantasy-novel",
269
+ "https://huggingface.co/spaces/VIDraft/money-radar",
270
+ "https://huggingface.co/spaces/immunobiotech/drug-discovery",
271
+ "https://huggingface.co/spaces/immunobiotech/Gemini-MICHELIN",
272
+ "https://huggingface.co/spaces/openfree/Cycle-Navigator",
273
+ "https://huggingface.co/spaces/VIDraft/Fashion-Fit",
274
+ "https://huggingface.co/spaces/openfree/Stock-Trading-Analysis",
275
+ "https://huggingface.co/spaces/ginipick/AgentX-Papers",
276
+ "https://huggingface.co/spaces/Heartsync/Papers-Leaderboard",
277
+ "https://huggingface.co/spaces/VIDraft/PapersImpact",
278
+ "https://huggingface.co/spaces/ginigen/multimodal-chat-mbti-korea",
279
+ ],
280
+ "Image": [
281
+ "https://huggingface.co/spaces/ginigen/Flux-Kontext-FaceLORA",
282
+ "https://huggingface.co/spaces/Heartsync/NSFW-Uncensored-REAL",
283
+ "https://huggingface.co/spaces/ginigen/FLUX-Ghibli-LoRA2",
284
+ "https://huggingface.co/spaces/aiqcamp/REMOVAL-TEXT-IMAGE",
285
+ "https://huggingface.co/spaces/VIDraft/BAGEL-Websearch",
286
+ "https://huggingface.co/spaces/ginigen/Every-Text",
287
+ "https://huggingface.co/spaces/ginigen/text3d-r1",
288
+ "https://huggingface.co/spaces/ginipick/FLUXllama",
289
+ "https://huggingface.co/spaces/ginigen/Workflow-Canvas",
290
+ "https://huggingface.co/spaces/ginigen/canvas-studio",
291
+ "https://huggingface.co/spaces/VIDraft/ReSize-Image-Outpainting",
292
+ "https://huggingface.co/spaces/Heartsync/FLUX-Vision",
293
+ "https://huggingface.co/spaces/fantos/textcutobject",
294
+ "https://huggingface.co/spaces/aiqtech/imaginpaint",
295
+ "https://huggingface.co/spaces/openfree/ColorRevive",
296
+ "https://huggingface.co/spaces/openfree/ultpixgen",
297
+ "https://huggingface.co/spaces/VIDraft/Polaroid-Style",
298
+ "https://huggingface.co/spaces/ginigen/VisualCloze",
299
+ "https://huggingface.co/spaces/fantaxy/ofai-flx-logo",
300
+ "https://huggingface.co/spaces/ginigen/interior-design",
301
+ "https://huggingface.co/spaces/ginigen/MagicFace-V3",
302
+ "https://huggingface.co/spaces/fantaxy/flx-pulid",
303
+ "https://huggingface.co/spaces/seawolf2357/Ghibli-Multilingual-Text-rendering",
304
+ "https://huggingface.co/spaces/VIDraft/Open-Meme-Studio",
305
+ "https://huggingface.co/spaces/VIDraft/stable-diffusion-3.5-large-turboX",
306
+ "https://huggingface.co/spaces/aiqtech/flxgif",
307
+ "https://huggingface.co/spaces/openfree/VectorFlow",
308
+ "https://huggingface.co/spaces/ginigen/3D-LLAMA",
309
+ "https://huggingface.co/spaces/ginigen/Multi-LoRAgen",
310
+ ],
311
+ "LLM / VLM": [
312
+ "https://huggingface.co/spaces/fantaxy/fantasy-novel",
313
+ "https://huggingface.co/spaces/ginigen/deepseek-r1-0528-API",
314
+ "https://huggingface.co/spaces/aiqcamp/Mistral-Devstral-API",
315
+ "https://huggingface.co/spaces/aiqcamp/deepseek-r1-0528",
316
+ "https://huggingface.co/spaces/aiqcamp/deepseek-r1-0528-qwen3-8b",
317
+ "https://huggingface.co/spaces/aiqcamp/deepseek-r1-0528",
318
+ "https://huggingface.co/spaces/aiqcamp/Mistral-Devstral-API",
319
+ "https://huggingface.co/spaces/VIDraft/Mistral-RAG-BitSix",
320
+ "https://huggingface.co/spaces/VIDraft/Gemma-3-R1984-4B",
321
+ "https://huggingface.co/spaces/VIDraft/Gemma-3-R1984-12B",
322
+ "https://huggingface.co/spaces/ginigen/Mistral-Perflexity",
323
+ "https://huggingface.co/spaces/aiqcamp/gemini-2.5-flash-preview",
324
+ "https://huggingface.co/spaces/openfree/qwen3-30b-a3b-research",
325
+ "https://huggingface.co/spaces/openfree/qwen3-235b-a22b-research",
326
+ "https://huggingface.co/spaces/openfree/Llama-4-Maverick-17B-Research",
327
+ ],
328
+ }
329
 
330
+ # ────────────────────────── 3. URL HELPERS ──────────────────────────
331
+ def direct_url(hf_url):
332
+ m = re.match(r"https?://huggingface\.co/spaces/([^/]+)/([^/?#]+)", hf_url)
333
+ if not m:
334
+ return hf_url
335
+ owner, name = m.groups()
336
+ owner = owner.lower()
337
+ name = name.replace('.', '-').replace('_', '-').lower()
338
+ return f"https://{owner}-{name}.hf.space"
339
+
340
+ def screenshot_url(url):
341
+ return f"https://image.thum.io/get/fullpage/{url}"
342
+
343
+ def process_url_for_preview(url):
344
+ """Returns (preview_url, mode)"""
345
+ # Handle blocked domains first
346
+ if any(d for d in BLOCKED_DOMAINS if d in url):
347
+ return screenshot_url(url), "snapshot"
348
 
349
+ # Special case handling for problematic URLs
350
+ if "vibe-coding-tetris" in url or "World-of-Tank-GAME" in url or "Minesweeper-Game" in url:
351
+ return screenshot_url(url), "snapshot"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
352
 
353
+ # General HF space handling
354
+ try:
355
+ if "huggingface.co/spaces" in url:
356
+ parts = url.rstrip("/").split("/")
357
+ if len(parts) >= 5:
358
+ owner = parts[-2]
359
+ name = parts[-1]
360
+ embed_url = f"https://huggingface.co/spaces/{owner}/{name}/embed"
361
+ return embed_url, "iframe"
362
+ except Exception:
363
+ return screenshot_url(url), "snapshot"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
364
 
365
+ # Default handling
366
+ return url, "iframe"
367
+
368
+ # ────────────────────────── 4. API ROUTES ──────────────────────────
369
+ @app.route('/api/category')
370
+ def api_category():
371
+ cat = request.args.get('name', '')
372
+ urls = CATEGORIES.get(cat, [])
373
 
374
+ # Add pagination for categories
375
+ page = int(request.args.get('page', 1))
376
+ per_page = int(request.args.get('per_page', 4))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
377
 
378
+ total_pages = max(1, (len(urls) + per_page - 1) // per_page)
379
+ start = (page - 1) * per_page
380
+ end = min(start + per_page, len(urls))
 
 
 
 
 
381
 
382
+ urls_page = urls[start:end]
 
383
 
384
+ items = [
385
+ {
386
+ "title": url.split('/')[-1],
387
+ "owner": url.split('/')[-2] if '/spaces/' in url else '',
388
+ "iframe": direct_url(url),
389
+ "shot": screenshot_url(url),
390
+ "hf": url
391
+ } for url in urls_page
392
+ ]
393
+
394
+ return jsonify({
395
+ "items": items,
396
+ "page": page,
397
+ "total_pages": total_pages
398
+ })
399
+
400
+ # ────────────────────────── 5. MAIN ROUTES ──────────────────────────
401
+ @app.route('/')
402
+ def home():
403
+ os.makedirs('templates', exist_ok=True)
404
+
405
+ with open('templates/index.html', 'w', encoding='utf-8') as fp:
406
+ fp.write(r'''<!DOCTYPE html>
407
+ <html>
408
+ <head>
409
+ <meta charset="utf-8">
410
+ <meta name="viewport" content="width=device-width, initial-scale=1">
411
+ <title>Web Gallery</title>
412
+ <style>
413
+ @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@300;600&display=swap');
414
+ body{margin:0;font-family:Nunito,sans-serif;background:#f6f8fb;}
415
+ .tabs{display:flex;flex-wrap:wrap;gap:8px;padding:16px;}
416
+ .tab{padding:6px 14px;border:none;border-radius:18px;background:#e2e8f0;font-weight:600;cursor:pointer;}
417
+ .tab.active{background:#a78bfa;color:#1a202c;}
418
+ .tab.popular{background:#ff6b6b;color:white;}
419
+ .tab.popular.active{background:#fa5252;color:white;}
420
+ .tab.best{background:#4ecdc4;color:white;}
421
+ .tab.best.active{background:#38d9a9;color:white;}
422
+ .tab.new{background:#ffe066;color:#1a202c;}
423
+ .tab.new.active{background:#ffd43b;color:#1a202c;}
424
+ /* Updated grid to show 2x2 layout */
425
+ .grid{display:grid;grid-template-columns:repeat(2,1fr);gap:20px;padding:0 16px 60px;max-width:1200px;margin:0 auto;}
426
+ @media(max-width:800px){.grid{grid-template-columns:1fr;}}
427
+ /* Increased card height for larger display */
428
+ .card{background:#fff;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,.08);overflow:hidden;height:540px;display:flex;flex-direction:column;position:relative;}
429
+ .frame{flex:1;position:relative;overflow:hidden;}
430
+ .frame iframe{position:absolute;width:166.667%;height:166.667%;transform:scale(.6);transform-origin:top left;border:0;}
431
+ .frame img{width:100%;height:100%;object-fit:cover;}
432
+ .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);}
433
+ .label-live{background:linear-gradient(135deg, #00c6ff, #0072ff);color:white;}
434
+ .label-static{background:linear-gradient(135deg, #ff9a9e, #fad0c4);color:#333;}
435
+ .foot{height:44px;background:#fafafa;display:flex;align-items:center;justify-content:center;border-top:1px solid #eee;}
436
+ .foot a{font-size:.82rem;font-weight:700;color:#4a6dd8;text-decoration:none;}
437
+ .pagination{display:flex;justify-content:center;margin:20px 0;gap:10px;}
438
+ .pagination button{padding:5px 15px;border:none;border-radius:20px;background:#e2e8f0;cursor:pointer;}
439
+ .pagination button:disabled{opacity:0.5;cursor:not-allowed;}
440
+ </style>
441
+ </head>
442
+ <body>
443
+ <header style="text-align: center; padding: 20px; background: linear-gradient(135deg, #f6f8fb, #e2e8f0); border-bottom: 1px solid #ddd;">
444
+ <h1 style="margin-bottom: 10px;">🌟OPEN & Free: BEST AI Playground</h1>
445
+ <p>
446
+ <a href="https://huggingface.co/OpenFreeAI" target="_blank"><img src="https://img.shields.io/static/v1?label=Community&message=OpenFree_AI&color=%23800080&labelColor=%23000080&logo=HUGGINGFACE&logoColor=%23ffa500&style=for-the-badge" alt="badge"></a>
447
+ <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>
448
+ <a href="https://huggingface.co/spaces/openfree/Best-AI" target="_blank"><img src="https://img.shields.io/static/v1?label=OpenFree&message=BEST%20AI%20Services&color=%230000ff&labelColor=%23000080&logo=huggingface&logoColor=%23ffa500&style=for-the-badge" alt="badge"></a>
449
+ </p>
450
+ </header>
451
+ <div class="tabs" id="tabs"></div>
452
+ <div id="content"></div>
453
+
454
+ <script>
455
+ // Basic configuration
456
+ const cats = {{cats|tojson}};
457
+ const tabs = document.getElementById('tabs');
458
+ const content = document.getElementById('content');
459
+ let active = "";
460
+ let currentPage = 1;
461
+
462
+ // Simple utility functions
463
+ function makeRequest(url, method, data, callback) {
464
+ const xhr = new XMLHttpRequest();
465
+ xhr.open(method, url, true);
466
+ xhr.onreadystatechange = function() {
467
+ if (xhr.readyState === 4 && xhr.status === 200) {
468
+ callback(JSON.parse(xhr.responseText));
469
+ }
470
+ };
471
+ if (method === 'POST') {
472
+ xhr.send(data);
473
+ } else {
474
+ xhr.send();
475
+ }
476
  }
 
 
 
 
 
477
 
478
+ function updateTabs() {
479
+ Array.from(tabs.children).forEach(b => {
480
+ b.classList.toggle('active', b.dataset.c === active);
481
+ });
482
+ }
483
 
484
+ // Tab handlers
485
+ function loadCategory(cat, page) {
486
+ if(cat === active && currentPage === page) return;
487
+ active = cat;
488
+ currentPage = page || 1;
489
+ updateTabs();
490
+
491
+ content.innerHTML = '<p style="text-align:center;padding:40px">Loading…</p>';
492
+
493
+ makeRequest('/api/category?name=' + encodeURIComponent(cat) + '&page=' + currentPage + '&per_page=4', 'GET', null, function(data) {
494
+ let html = '<div class="grid">';
495
 
496
+ if(data.items.length === 0) {
497
+ html += '<p style="grid-column:1/-1;text-align:center;padding:40px">No items in this category.</p>';
498
+ } else {
499
+ data.items.forEach(item => {
500
+ html += `
501
+ <div class="card">
502
+ <div class="card-label label-live">LIVE</div>
503
+ <div class="frame">
504
+ <iframe src="${item.iframe}" loading="lazy" sandbox="allow-forms allow-modals allow-popups allow-same-origin allow-scripts allow-downloads"></iframe>
505
+ </div>
506
+ <div class="foot">
507
+ <a href="${item.hf}" target="_blank">${item.title}</a>
508
+ </div>
509
+ </div>
510
+ `;
511
+ });
512
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
513
 
514
+ html += '</div>';
 
 
 
 
515
 
516
+ // Add pagination
517
+ html += `
518
+ <div class="pagination">
519
+ <button ${currentPage <= 1 ? 'disabled' : ''} onclick="loadCategory('${cat}', ${currentPage-1})">« Previous</button>
520
+ <span>Page ${currentPage} of ${data.total_pages}</span>
521
+ <button ${currentPage >= data.total_pages ? 'disabled' : ''} onclick="loadCategory('${cat}', ${currentPage+1})">Next »</button>
522
+ </div>
523
+ `;
524
+
525
+ content.innerHTML = html;
526
+ });
527
+ }
528
 
529
+ // Create tabs
530
+ // Special tabs first (Popular, BEST, NEW)
531
+ ['Popular', 'BEST', 'NEW'].forEach(specialCat => {
532
+ const b = document.createElement('button');
533
+ b.className = 'tab ' + specialCat.toLowerCase();
534
+ b.textContent = specialCat;
535
+ b.dataset.c = specialCat;
536
+ b.onclick = function() { loadCategory(specialCat, 1); };
537
+ tabs.appendChild(b);
538
+ });
539
+
540
+ // Regular category tabs
541
+ cats.forEach(c => {
542
+ if (!['Popular', 'BEST', 'NEW'].includes(c)) {
543
+ const b = document.createElement('button');
544
+ b.className = 'tab';
545
+ b.textContent = c;
546
+ b.dataset.c = c;
547
+ b.onclick = function() { loadCategory(c, 1); };
548
+ tabs.appendChild(b);
549
+ }
550
+ });
551
+
552
+ // Start with Popular tab
553
+ loadCategory('Popular', 1);
554
+ </script>
555
+ </body>
556
+ </html>''')
557
+
558
+ # Return the rendered template
559
+ return render_template('index.html', cats=list(CATEGORIES.keys()))
560
 
561
+ if __name__ == '__main__':
562
+ app.run(host='0.0.0.0', port=7860)