File size: 13,541 Bytes
834bcf3
e8ea372
 
a101d9b
 
e8ea372
8964ef4
 
 
 
e082b4b
8964ef4
 
a101d9b
a4b71bb
a101d9b
8964ef4
a101d9b
67008b9
 
e8ea372
a4b71bb
8964ef4
67008b9
a101d9b
e8ea372
03258aa
 
 
8964ef4
 
a101d9b
e8ea372
8964ef4
a4b71bb
 
 
03258aa
 
 
42e31b9
 
 
03258aa
 
 
 
 
a4b71bb
8964ef4
cf41b19
 
 
 
 
 
 
a4b71bb
 
e8ea372
 
8964ef4
 
650a247
 
03258aa
 
 
 
 
650a247
 
 
 
 
03258aa
 
 
 
 
 
 
 
 
 
650a247
 
b648312
650a247
a101d9b
 
 
 
03258aa
 
a101d9b
 
03258aa
 
 
 
a101d9b
 
 
42e31b9
03258aa
a101d9b
 
 
03258aa
e082b4b
03258aa
 
 
 
 
 
 
 
 
 
e082b4b
8964ef4
03258aa
a101d9b
8964ef4
 
a101d9b
8964ef4
03258aa
 
 
 
8964ef4
a101d9b
 
42e31b9
 
 
 
 
03258aa
 
 
 
 
 
 
 
 
 
 
e8ea372
42e31b9
03258aa
 
e8ea372
42e31b9
 
 
 
a101d9b
42e31b9
 
8964ef4
03258aa
a101d9b
8964ef4
03258aa
 
a101d9b
 
 
42e31b9
a101d9b
 
 
03258aa
42e31b9
a101d9b
6adeb37
a101d9b
8964ef4
d315723
dabf25e
 
42e31b9
8964ef4
dabf25e
8964ef4
42e31b9
 
03258aa
42e31b9
 
a101d9b
 
42e31b9
03258aa
42e31b9
 
03258aa
42e31b9
 
 
03258aa
 
 
 
 
42e31b9
03258aa
24ca8de
03258aa
42e31b9
b648312
42e31b9
b648312
42e31b9
 
 
03258aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dabf25e
03258aa
650a247
 
03258aa
f69954f
5f2948a
f69954f
03258aa
 
5f2948a
 
 
 
650a247
03258aa
 
 
650a247
03258aa
e082b4b
03258aa
650a247
 
03258aa
 
 
650a247
 
 
03258aa
 
 
 
650a247
 
dabf25e
 
03258aa
 
 
dabf25e
 
03258aa
 
 
 
42e31b9
834bcf3
14a7251
d315723
67008b9
 
dff981d
14a7251
a101d9b
 
a4b71bb
 
 
 
 
 
 
e8ea372
 
fe95fdf
 
42e31b9
fe95fdf
e8ea372
 
a101d9b
 
 
834bcf3
 
 
 
 
 
0708a05
 
 
 
 
 
 
 
03258aa
 
 
 
a101d9b
834bcf3
8e9514a
834bcf3
 
 
dabf25e
8e9514a
0708a05
8e9514a
0708a05
 
 
 
 
 
 
 
834bcf3
a101d9b
 
03258aa
 
235f820
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03258aa
 
 
a101d9b
03258aa
a101d9b
dabf25e
 
03258aa
 
06e8b3b
 
03258aa
dabf25e
03258aa
 
 
dabf25e
a101d9b
03258aa
a101d9b
 
a4b71bb
 
67008b9
03258aa
 
67008b9
e082b4b
03258aa
 
a101d9b
8964ef4
dabf25e
0cfd08a
dabf25e
 
 
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
from enum import Enum
import os
import re
import aiohttp
import requests
import json
import subprocess
import asyncio
from io import BytesIO
import uuid
import yaml

from math import ceil
from tqdm import tqdm
from pathlib import Path
from huggingface_hub import Repository
from PIL import Image, ImageOps
from fastapi import FastAPI, BackgroundTasks
from fastapi.responses import HTMLResponse

from fastapi_utils.tasks import repeat_every
from fastapi.middleware.cors import CORSMiddleware
import boto3
from datetime import datetime
from db import Database

AWS_ACCESS_KEY_ID = os.getenv("MY_AWS_ACCESS_KEY_ID")
AWS_SECRET_KEY = os.getenv("MY_AWS_SECRET_KEY")
AWS_S3_BUCKET_NAME = os.getenv("MY_AWS_S3_BUCKET_NAME")


HF_TOKEN = os.environ.get("HF_TOKEN")

S3_DATA_FOLDER = Path("sd-multiplayer-data")

DB_FOLDER = Path("diffusers-gallery-data")

CLASSIFIER_URL = (
    "https://radames-aesthetic-style-nsfw-classifier.hf.space/run/inference"
)
ASSETS_URL = "https://d26smi9133w0oo.cloudfront.net/diffusers-gallery/"


s3 = boto3.client(
    service_name="s3",
    aws_access_key_id=AWS_ACCESS_KEY_ID,
    aws_secret_access_key=AWS_SECRET_KEY,
)


repo = Repository(
    local_dir=DB_FOLDER,
    repo_type="dataset",
    clone_from="huggingface-projects/diffusers-gallery-data",
    use_auth_token=True,
)
repo.git_pull()

database = Database(DB_FOLDER)


async def upload_resize_image_url(session, image_url):
    print(f"Uploading image {image_url}")
    try:
        async with session.get(image_url) as response:
            if response.status == 200 and (
                response.headers["content-type"].startswith("image")
                or response.headers["content-type"].startswith("application")
            ):
                image = Image.open(BytesIO(await response.read())).convert("RGB")
                # resize image proportional
                image = ImageOps.fit(image, (400, 400), Image.LANCZOS)
                image_bytes = BytesIO()
                image.save(image_bytes, format="JPEG")
                image_bytes.seek(0)
                fname = f"{uuid.uuid4()}.jpg"
                s3.upload_fileobj(
                    Fileobj=image_bytes,
                    Bucket=AWS_S3_BUCKET_NAME,
                    Key="diffusers-gallery/" + fname,
                    ExtraArgs={
                        "ContentType": "image/jpeg",
                        "CacheControl": "max-age=31536000",
                    },
                )
                return fname
    except Exception as e:
        print(f"Error uploading image {image_url}: {e}")
        return None


def fetch_models(page=0):
    response = requests.get(
        f"https://huggingface.co/models-json?pipeline_tag=text-to-image&p={page}"
    )
    data = response.json()
    return {
        "models": [model for model in data["models"] if not model["private"]],
        "numItemsPerPage": data["numItemsPerPage"],
        "numTotalItems": data["numTotalItems"],
        "pageIndex": data["pageIndex"],
    }


def fetch_model_card(model_id):
    response = requests.get(f"https://huggingface.co/{model_id}/raw/main/README.md")
    return response.text


REGEX = re.compile(r'---(.*?)---', re.DOTALL)

def get_yaml_data(text_content):
    matches = REGEX.findall(text_content)
    yaml_block = matches[0].strip() if matches else None
    if yaml_block:
        try: 
            data_dict = yaml.safe_load(yaml_block)
            return data_dict
        except yaml.YAMLError as exc:
            print(exc)
    return {}

async def find_image_in_model_card(text):
    image_regex = re.compile(r"https?://\S+(?:png|jpg|jpeg|webp)")
    urls = re.findall(image_regex, text)
    if not urls:
        return []

    async with aiohttp.ClientSession() as session:
        tasks = [
            asyncio.ensure_future(upload_resize_image_url(session, image_url))
            for image_url in urls[0:3]
        ]
        return await asyncio.gather(*tasks)


def run_classifier(images):
    images = [i for i in images if i is not None]
    if len(images) > 0:
        # classifying only the first image
        images_urls = [ASSETS_URL + images[0]]
        response = requests.post(
            CLASSIFIER_URL,
            json={
                "data": [
                    {"urls": images_urls},  # json urls: list of images urls
                    False,  # enable/disable gallery image output
                    None,  # single image input
                    None,  # files input
                ]
            },
        ).json()

        # data response is array data:[[{img0}, {img1}, {img2}...], Label, Gallery],
        class_data = response["data"][0][0]
        class_data_parsed = {row["label"]: round(row["score"], 3) for row in class_data}

        # update row data with classificator data
        return class_data_parsed
    else:
        return {}


async def get_all_new_models():
    initial = fetch_models(0)
    num_pages = ceil(initial["numTotalItems"] / initial["numItemsPerPage"])

    print(
        f"Total items: {initial['numTotalItems']} - Items per page: {initial['numItemsPerPage']}"
    )
    print(f"Found {num_pages} pages")

    # fetch all models
    new_models = []
    for page in tqdm(range(0, num_pages)):
        print(f"Fetching page {page} of {num_pages}")
        page_models = fetch_models(page)
        new_models += page_models["models"]
    return new_models


async def sync_data():
    print("Fetching models")
    repo.git_pull()
    all_models = await get_all_new_models()
    print(f"Found {len(all_models)} models")
    # save list of all models for ids
    with open(DB_FOLDER / "models.json", "w") as f:
        json.dump(all_models, f)
    # with open(DB_FOLDER / "models.json", "r") as f:
    #     new_models = json.load(f)

    new_models_ids = [model["id"] for model in all_models]

    # get existing models
    with database.get_db() as db:
        cursor = db.cursor()
        cursor.execute("SELECT id FROM models")
        existing_models = [row["id"] for row in cursor.fetchall()]
    models_ids_to_add = list(set(new_models_ids) - set(existing_models))
    # find all models id to add from new_models
    models = [model for model in all_models if model["id"] in models_ids_to_add]

    print(f"Found {len(models)} new models")
    for model in tqdm(models):
        model_id = model["id"]
        print(f"\n\nFetching model {model_id}")
        likes = model["likes"]
        downloads = model["downloads"]
        print("Fetching model card")
        model_card = fetch_model_card(model_id)
        print("Parsing model card")
        model_card_data = get_yaml_data(model_card)
        print("Finding images in model card")
        images = await find_image_in_model_card(model_card)

        classifier = run_classifier(images)
        print(images, classifier)
        # update model row with image and classifier data
        with database.get_db() as db:
            cursor = db.cursor()
            cursor.execute(
                "INSERT INTO models(id, data, likes, downloads) VALUES (?, ?, ?, ?)",
                [
                    model_id,
                    json.dumps(
                        {
                            **model,
                            "meta": model_card_data,
                            "images": images,
                            "class": classifier,
                        }
                    ),
                    likes,
                    downloads,
                ],
            )
            db.commit()
    print("\n\n\n\nTry to update images again\n\n\n")
    with database.get_db() as db:
        cursor = db.cursor()
        cursor.execute("SELECT * from models")
        to_all_models = list(cursor.fetchall())
        models_no_images = []
        for model in to_all_models:
            model_data = json.loads(model["data"])
            images = model_data["images"]
            filtered_images = [x for x in images if x is not None]
            if len(filtered_images) == 0:
                models_no_images.append(model)

        for model in tqdm(models_no_images):
            model_id = model["id"]
            model_data = json.loads(model["data"])
            print(f"\n\nFetching model {model_id}")
            model_card = fetch_model_card(model_id)
            print("Parsing model card")
            model_card_data = get_yaml_data(model_card)
            print("Finding images in model card")
            images = await find_image_in_model_card(model_card)
            classifier = run_classifier(images)
            model_data["images"] = images
            model_data["class"] = classifier
            model_data["meta"] = model_card_data
            # update model row with image and classifier data
            with database.get_db() as db:
                cursor = db.cursor()
                cursor.execute(
                    "UPDATE models SET data = ? WHERE id = ?",
                    [json.dumps(model_data), model_id],
                )
                db.commit()

    print("Update likes and downloads")
    for model in tqdm(all_models):
        model_id = model["id"]
        likes = model["likes"]
        downloads = model["downloads"]
        with database.get_db() as db:
            cursor = db.cursor()
            cursor.execute(
                "UPDATE models SET likes = ?, downloads = ? WHERE id = ?",
                [likes, downloads, model_id],
            )
            db.commit()

    print("Updating DB repository")
    time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    cmd = f"git add . && git commit --amend -m 'update at {time}' && git push --force"
    print(cmd)
    subprocess.Popen(cmd, cwd=DB_FOLDER, shell=True)


app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# @ app.get("/sync")
# async def sync(background_tasks: BackgroundTasks):
#     await sync_data()
#     return "Synced data to huggingface datasets"


MAX_PAGE_SIZE = 30


class Sort(str, Enum):
    trending = "trending"
    recent = "recent"
    likes = "likes"


class Style(str, Enum):
    all = "all"
    anime = "anime"
    s3D = "3d"
    realistic = "realistic"
    nsfw = "nsfw"


@app.get("/api/models")
def get_page(
    page: int = 1, sort: Sort = Sort.trending, style: Style = Style.all, tag: str = None
):
    page = page if page > 0 else 1
    if sort == Sort.trending:
        sort_query = "likes / MYPOWER((JULIANDAY('now') - JULIANDAY(datetime(json_extract(data, '$.lastModified')))) + 2, 2) DESC"
    elif sort == Sort.recent:
        sort_query = "datetime(json_extract(data, '$.lastModified')) DESC"
    elif sort == Sort.likes:
        sort_query = "likes DESC"

    if style == Style.all:
        style_query = "isNFSW = false"
    elif style == Style.anime:
        style_query = "json_extract(data, '$.class.anime') > 0.1 AND isNFSW = false"
    elif style == Style.s3D:
        style_query = "json_extract(data, '$.class.3d') > 0.1 AND isNFSW = false"
    elif style == Style.realistic:
        style_query = "json_extract(data, '$.class.real_life') > 0.1 AND isNFSW = false"
    elif style == Style.nsfw:
        style_query = "isNFSW = true"

    with database.get_db() as db:
        cursor = db.cursor()
        cursor.execute(
            f"""
                SELECT *,
                        COUNT(*) OVER() AS total,
                        isNFSW
                    FROM (
                        SELECT *,
                            json_extract(data, '$.class.explicit') > 0.3 OR json_extract(data, '$.class.suggestive') > 0.3 AS isNFSW
                        FROM models
                    ) AS subquery
                    WHERE (? IS NULL AND likes > 3 OR ? IS NOT NULL)
                    AND {style_query}
                    AND (? IS NULL OR EXISTS (
                            SELECT 1
                            FROM json_each(json_extract(data, '$.meta.tags'))
                            WHERE json_each.value = ?
                        ))
                    ORDER BY {sort_query}
                    LIMIT {MAX_PAGE_SIZE} OFFSET {(page - 1) * MAX_PAGE_SIZE};
        """,
            (tag, tag, tag, tag),
        )
        results = cursor.fetchall()
        total = results[0]["total"] if results else 0
        total_pages = (total + MAX_PAGE_SIZE - 1) // MAX_PAGE_SIZE
        models_data = []
        for result in results:
            data = json.loads(result["data"])
            images = data["images"]
            filtered_images = [x for x in images if x is not None]
            # clean nulls
            data["images"] = filtered_images
            # update downloads and likes from db table
            data["downloads"] = result["downloads"]
            data["likes"] = result["likes"]
            data["isNFSW"] = bool(result["isNFSW"])
            models_data.append(data)

    return {"models": models_data, "totalPages": total_pages}


@app.get("/")
def read_root():
    # return html page from string
    return HTMLResponse(
        """
    <p>Just a bot to sync data from diffusers gallery please go to
    <a href="https://huggingface.co/spaces/huggingface-projects/diffusers-gallery" target="_blank" rel="noopener noreferrer">https://huggingface.co/spaces/huggingface-projects/diffusers-gallery</a>
    </p>"""
    )


@app.on_event("startup")
@repeat_every(seconds=60 * 60 * 6, wait_first=False)
async def repeat_sync():
    await sync_data()
    return "Synced data to huggingface datasets"