File size: 16,257 Bytes
0cfe6dd
5b9a5d8
09d178c
 
799f675
 
 
 
 
 
 
0cfe6dd
799f675
 
09d178c
 
 
 
 
0cfe6dd
799f675
0cfe6dd
09d178c
0cfe6dd
09d178c
 
 
0cfe6dd
 
 
 
 
 
 
09d178c
0cfe6dd
 
799f675
09d178c
0cfe6dd
09d178c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cfe6dd
09d178c
0cfe6dd
 
09d178c
0cfe6dd
09d178c
0cfe6dd
09d178c
 
 
0cfe6dd
 
 
09d178c
0cfe6dd
09d178c
0cfe6dd
09d178c
 
 
0cfe6dd
 
09d178c
 
 
 
 
0cfe6dd
09d178c
0cfe6dd
09d178c
0cfe6dd
 
09d178c
 
0cfe6dd
 
09d178c
 
 
 
 
0cfe6dd
09d178c
 
0cfe6dd
 
09d178c
 
 
0cfe6dd
 
 
09d178c
 
 
 
 
0cfe6dd
09d178c
 
 
 
0cfe6dd
09d178c
0cfe6dd
 
09d178c
0cfe6dd
 
09d178c
 
 
 
 
 
 
 
 
0cfe6dd
09d178c
 
0cfe6dd
09d178c
 
0cfe6dd
 
 
 
09d178c
 
 
 
 
0cfe6dd
09d178c
 
 
0cfe6dd
 
 
09d178c
 
 
0cfe6dd
09d178c
 
0cfe6dd
 
09d178c
 
0cfe6dd
09d178c
 
0cfe6dd
09d178c
 
 
 
 
0cfe6dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09d178c
0cfe6dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
799f675
0cfe6dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09d178c
 
799f675
 
09d178c
0cfe6dd
09d178c
 
 
0cfe6dd
 
 
 
09d178c
 
0cfe6dd
 
 
799f675
0cfe6dd
 
 
 
09d178c
 
 
 
 
0cfe6dd
 
 
 
 
 
 
 
 
09d178c
0cfe6dd
09d178c
 
 
 
799f675
0cfe6dd
 
 
 
09d178c
 
 
 
0cfe6dd
 
09d178c
 
 
 
0cfe6dd
 
09d178c
0cfe6dd
09d178c
0cfe6dd
 
 
 
09d178c
0cfe6dd
 
 
 
 
09d178c
0cfe6dd
09d178c
0cfe6dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09d178c
 
 
0cfe6dd
09d178c
 
 
 
 
0cfe6dd
 
 
 
 
09d178c
0cfe6dd
09d178c
 
799f675
0cfe6dd
799f675
0cfe6dd
 
799f675
0cfe6dd
 
09d178c
 
 
0cfe6dd
 
 
 
 
 
 
09d178c
 
0cfe6dd
09d178c
 
0cfe6dd
 
799f675
09d178c
0cfe6dd
 
 
09d178c
0cfe6dd
 
 
 
 
 
 
09d178c
 
0cfe6dd
09d178c
 
0cfe6dd
09d178c
0cfe6dd
 
 
09d178c
 
 
0cfe6dd
09d178c
0cfe6dd
09d178c
 
 
0cfe6dd
 
09d178c
 
 
 
 
0cfe6dd
799f675
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
# --- flash_attn Mock ---------------------------------------------------------
import sys
import types
import importlib.util

flash_mock = types.ModuleType("flash_attn")
flash_mock.__version__ = "2.0.0"
flash_mock.__spec__ = importlib.util.spec_from_loader("flash_attn", loader=None)
sys.modules["flash_attn"] = flash_mock
sys.modules["flash_attn.flash_attn_interface"] = types.ModuleType("flash_attn.flash_attn_interface")
sys.modules["flash_attn.bert_padding"] = types.ModuleType("flash_attn.bert_padding")
# -----------------------------------------------------------------------------

import io
import os
import time
import uuid
import threading
import subprocess

import cv2
import torch
from PIL import Image
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, HTMLResponse
from starlette.background import BackgroundTask
from transformers import (
    BlipProcessor,
    BlipForQuestionAnswering,
    AutoProcessor,
    AutoModelForCausalLM,
)


BLIP_MODEL_ID = "Salesforce/blip-vqa-base"
FLORENCE_MODEL_ID = "microsoft/Florence-2-large-ft"
FRAMES_PER_SECOND = 1
TEMP_DIR = "/tmp/video_filter"
os.makedirs(TEMP_DIR, exist_ok=True)

BLIP_QUESTIONS = [
    "is there a person in this image?",
    "is there a woman in this image?",
    "is there a human body part in this image?",
    "is there a hand or arm visible?",
    "is there a face visible?",
    "is there a leg or foot visible?",
    "is there a belly or stomach visible?",
]

FLORENCE_QUESTION = (
    "Is there a woman or any part of a woman's body in this image? "
    "Answer yes or no only."
)

MODEL_DATA = {}
MODEL_STATUS = {"status": "loading", "message": "ุฌุงุฑูŠ ุชุญู…ูŠู„ ุงู„ู†ู…ุงุฐุฌ..."}
JOB_OUTPUTS = {}


def load_models() -> None:
    try:
        print("Loading BLIP...", flush=True)
        MODEL_STATUS.update({"status": "loading", "message": "ุฌุงุฑูŠ ุชุญู…ูŠู„ BLIP..."})
        start = time.time()
        MODEL_DATA["blip_processor"] = BlipProcessor.from_pretrained(BLIP_MODEL_ID)
        MODEL_DATA["blip_model"] = BlipForQuestionAnswering.from_pretrained(
            BLIP_MODEL_ID,
            torch_dtype=torch.float32,
        ).eval()
        print(f"BLIP ready in {time.time() - start:.1f}s", flush=True)

        print("Loading Florence-2...", flush=True)
        MODEL_STATUS.update({"status": "loading", "message": "ุฌุงุฑูŠ ุชุญู…ูŠู„ Florence-2..."})
        start = time.time()
        MODEL_DATA["florence_processor"] = AutoProcessor.from_pretrained(
            FLORENCE_MODEL_ID,
            trust_remote_code=True,
        )
        MODEL_DATA["florence_model"] = AutoModelForCausalLM.from_pretrained(
            FLORENCE_MODEL_ID,
            torch_dtype=torch.float32,
            trust_remote_code=True,
            attn_implementation="eager",
        ).eval()
        print(f"Florence-2 ready in {time.time() - start:.1f}s", flush=True)

        MODEL_STATUS.update({"status": "ready", "message": "ุงู„ู†ู…ุงุฐุฌ ุฌุงู‡ุฒุฉ"})
        print("All models loaded", flush=True)
    except Exception as e:
        MODEL_STATUS.update({"status": "error", "message": str(e)})
        print(f"Error loading models: {e}", flush=True)


@asynccontextmanager
async def lifespan(app: FastAPI):
    thread = threading.Thread(target=load_models, daemon=True)
    thread.start()
    print("Server started, models are loading in background", flush=True)
    yield
    MODEL_DATA.clear()
    JOB_OUTPUTS.clear()


app = FastAPI(
    title="Video Female Filter",
    description="ุชุญู„ูŠู„ ุงู„ููŠุฏูŠูˆ ูˆุฅุฒุงู„ุฉ ู…ู‚ุงุทุน ุงู„ู†ุณุงุก | BLIP + Florence-2",
    version="1.0.0",
    lifespan=lifespan,
)

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


def run_blip(image: Image.Image) -> dict:
    processor = MODEL_DATA["blip_processor"]
    model = MODEL_DATA["blip_model"]
    yes_answers = {}
    no_answers = {}

    for question in BLIP_QUESTIONS:
        inputs = processor(image, question, return_tensors="pt")
        with torch.no_grad():
            out = model.generate(**inputs, max_new_tokens=5)
        answer = processor.decode(out[0], skip_special_tokens=True).strip().lower()
        if answer == "yes" or answer.startswith("yes"):
            yes_answers[question] = answer
        else:
            no_answers[question] = answer

    return {"yes": yes_answers, "no": no_answers}


def run_florence(image: Image.Image) -> str:
    processor = MODEL_DATA["florence_processor"]
    model = MODEL_DATA["florence_model"]
    task = "<VQA>"
    prompt = f"{task}{FLORENCE_QUESTION}"
    inputs = processor(text=prompt, images=image, return_tensors="pt")
    with torch.no_grad():
        generated_ids = model.generate(
            input_ids=inputs["input_ids"],
            pixel_values=inputs["pixel_values"],
            max_new_tokens=10,
            do_sample=False,
        )
    generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
    parsed = processor.post_process_generation(
        generated_text,
        task=task,
        image_size=(image.width, image.height),
    )
    return parsed.get(task, "").strip().lower()


def is_female_in_frame(image: Image.Image) -> tuple[bool, str]:
    blip_result = run_blip(image)
    yes_q = blip_result["yes"]

    if "is there a woman in this image?" in yes_q:
        return True, "blip_woman"

    if not yes_q:
        return False, "blip_clean"

    florence_answer = run_florence(image)
    if "yes" in florence_answer:
        return True, "florence_confirmed"
    return False, "florence_clean"


def run_ffmpeg_command(args: list[str]) -> None:
    proc = subprocess.run(args, capture_output=True, text=True)
    if proc.returncode != 0:
        stderr_msg = (proc.stderr or "").strip()
        if len(stderr_msg) > 600:
            stderr_msg = stderr_msg[-600:]
        raise RuntimeError(f"ffmpeg failed (exit={proc.returncode}): {stderr_msg}")


def merge_overlapping_segments(segments: list[list[float]], duration_sec: float) -> list[list[float]]:
    if not segments:
        return []

    clipped = []
    for s, e in segments:
        s = max(0.0, min(s, duration_sec))
        e = max(0.0, min(e, duration_sec))
        if e > s:
            clipped.append([s, e])

    if not clipped:
        return []

    clipped.sort(key=lambda x: x[0])
    merged = [clipped[0]]
    for s, e in clipped[1:]:
        last = merged[-1]
        if s <= last[1]:
            last[1] = max(last[1], e)
        else:
            merged.append([s, e])

    return merged


def cleanup_files(paths: list[str]) -> None:
    for p in paths:
        try:
            if p and os.path.exists(p):
                os.remove(p)
        except Exception:
            pass


def cleanup_job_output(job_id: str) -> None:
    output = JOB_OUTPUTS.pop(job_id, None)
    if output:
        cleanup_files([output])


def build_clean_video(
    input_path: str,
    output_path: str,
    keep_segments: list[list[float]],
    job_id: str,
) -> bool:
    segment_files = []
    temp_files = []

    try:
        for i, (start_sec, end_sec) in enumerate(keep_segments):
            seg_file = f"{TEMP_DIR}/{job_id}_seg_{i}.mp4"
            temp_files.append(seg_file)
            run_ffmpeg_command(
                [
                    "ffmpeg",
                    "-y",
                    "-ss",
                    f"{start_sec:.3f}",
                    "-to",
                    f"{end_sec:.3f}",
                    "-i",
                    input_path,
                    "-map",
                    "0:v:0?",
                    "-map",
                    "0:a:0?",
                    "-c:v",
                    "libx264",
                    "-preset",
                    "veryfast",
                    "-crf",
                    "23",
                    "-pix_fmt",
                    "yuv420p",
                    "-c:a",
                    "aac",
                    "-b:a",
                    "128k",
                    "-movflags",
                    "+faststart",
                    seg_file,
                ]
            )
            if os.path.exists(seg_file) and os.path.getsize(seg_file) > 0:
                segment_files.append(seg_file)

        if not segment_files:
            return False

        list_file = f"{TEMP_DIR}/{job_id}_list.txt"
        temp_files.append(list_file)
        with open(list_file, "w", encoding="utf-8") as f:
            for seg in segment_files:
                f.write(f"file '{seg}'\n")

        run_ffmpeg_command(
            [
                "ffmpeg",
                "-y",
                "-f",
                "concat",
                "-safe",
                "0",
                "-i",
                list_file,
                "-c:v",
                "libx264",
                "-preset",
                "veryfast",
                "-crf",
                "23",
                "-pix_fmt",
                "yuv420p",
                "-c:a",
                "aac",
                "-b:a",
                "128k",
                "-movflags",
                "+faststart",
                output_path,
            ]
        )

        return os.path.exists(output_path) and os.path.getsize(output_path) > 0
    finally:
        cleanup_files(temp_files)


@app.get("/", response_class=HTMLResponse)
def root():
    with open("index.html", "r", encoding="utf-8") as f:
        return f.read()


@app.get("/health")
def health():
    return {
        "status": MODEL_STATUS["status"],
        "message": MODEL_STATUS["message"],
        "blip_loaded": "blip_model" in MODEL_DATA,
        "florence_loaded": "florence_model" in MODEL_DATA,
    }


@app.post("/analyze-file")
async def analyze_file(file: UploadFile = File(...)):
    if MODEL_STATUS["status"] != "ready":
        raise HTTPException(
            status_code=503,
            detail=f"ุงู„ู†ู…ุงุฐุฌ ู„ู… ุชูƒุชู…ู„ ุจุนุฏ: {MODEL_STATUS['message']}",
        )

    if not file.content_type or not file.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="ุงู„ู…ู„ู ู„ูŠุณ ุตูˆุฑุฉ")

    try:
        image_bytes = await file.read()
        image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
        has_female, reason = is_female_in_frame(image)
        return {
            "has_female": has_female,
            "decision": "BLOCK" if has_female else "ALLOW",
            "reason": reason,
            "status": "success",
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/analyze-video")
async def analyze_video(file: UploadFile = File(...)):
    if MODEL_STATUS["status"] != "ready":
        raise HTTPException(
            status_code=503,
            detail=f"ุงู„ู†ู…ุงุฐุฌ ู„ู… ุชูƒุชู…ู„ ุจุนุฏ: {MODEL_STATUS['message']}",
        )

    if not file.content_type or not file.content_type.startswith("video/"):
        raise HTTPException(status_code=400, detail="ุงู„ู…ู„ู ู„ูŠุณ ููŠุฏูŠูˆ")

    job_id = str(uuid.uuid4())[:8]
    input_path = f"{TEMP_DIR}/{job_id}_input.mp4"
    output_path = f"{TEMP_DIR}/{job_id}_output.mp4"

    with open(input_path, "wb") as f:
        while True:
            chunk = await file.read(1024 * 1024)
            if not chunk:
                break
            f.write(chunk)

    try:
        cap = cv2.VideoCapture(input_path)
        if not cap.isOpened():
            raise HTTPException(status_code=400, detail="ุชุนุฐุฑ ูุชุญ ุงู„ููŠุฏูŠูˆ")

        fps = cap.get(cv2.CAP_PROP_FPS) or 25
        if fps <= 0:
            fps = 25
        total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        duration_sec = total_frames / fps if total_frames > 0 else 0.0

        print(f"Video info: {total_frames} frames, {fps:.2f} fps", flush=True)

        frame_interval = max(1, int(fps / FRAMES_PER_SECOND))
        female_segments = []
        analysis_log = []
        in_female_seg = False
        seg_start = 0.0
        frame_idx = 0
        start_time = time.time()

        try:
            while True:
                ret, frame = cap.read()
                if not ret:
                    break

                if frame_idx % frame_interval == 0:
                    current_sec = frame_idx / fps
                    pil_image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
                    has_female, reason = is_female_in_frame(pil_image)
                    analysis_log.append(
                        {
                            "second": round(current_sec, 2),
                            "has_female": has_female,
                            "reason": reason,
                        }
                    )

                    if has_female and not in_female_seg:
                        in_female_seg = True
                        seg_start = max(0.0, current_sec - 0.5)
                    elif not has_female and in_female_seg:
                        in_female_seg = False
                        female_segments.append([seg_start, current_sec + 0.5])

                frame_idx += 1
        finally:
            cap.release()

        if in_female_seg:
            female_segments.append([seg_start, duration_sec])
        female_segments = merge_overlapping_segments(female_segments, duration_sec)

        elapsed_analysis = round(time.time() - start_time, 2)

        if not female_segments:
            return {
                "has_female": False,
                "female_segments": [],
                "analysis_log": analysis_log,
                "message": "โœ… ุงู„ููŠุฏูŠูˆ ู†ุธูŠู ู„ุง ูŠุญุชูˆูŠ ุนู„ู‰ ู†ุณุงุก",
                "analysis_time": elapsed_analysis,
                "output_available": False,
                "status": "success",
            }

        keep_segments = []
        prev_end = 0.0
        for s, e in female_segments:
            if prev_end < s:
                keep_segments.append([prev_end, s])
            prev_end = e
        if prev_end < duration_sec:
            keep_segments.append([prev_end, duration_sec])

        if not keep_segments:
            return {
                "has_female": True,
                "female_segments": female_segments,
                "analysis_log": analysis_log,
                "message": "โš ๏ธ ุงู„ููŠุฏูŠูˆ ูƒู„ู‡ ูŠุญุชูˆูŠ ุนู„ู‰ ู†ุณุงุก",
                "analysis_time": elapsed_analysis,
                "output_available": False,
                "status": "success",
            }

        output_ok = build_clean_video(input_path, output_path, keep_segments, job_id)
        total_removed = sum(e - s for s, e in female_segments)

        if output_ok:
            JOB_OUTPUTS[job_id] = output_path

        return {
            "has_female": True,
            "female_segments": female_segments,
            "kept_segments": keep_segments,
            "total_removed_sec": round(total_removed, 2),
            "analysis_log": analysis_log,
            "analysis_time": elapsed_analysis,
            "output_available": output_ok,
            "output_job_id": job_id,
            "download_url": f"/download/{job_id}",
            "message": f"โœ… ุชู… ุญุฐู {round(total_removed, 1)} ุซุงู†ูŠุฉ ู…ู† ุงู„ููŠุฏูŠูˆ",
            "status": "success",
        }
    except HTTPException:
        cleanup_files([output_path])
        raise
    except Exception as e:
        cleanup_files([output_path])
        raise HTTPException(status_code=500, detail=str(e))
    finally:
        cleanup_files([input_path])


@app.get("/download/{job_id}")
def download_video(job_id: str):
    output_path = JOB_OUTPUTS.get(job_id, f"{TEMP_DIR}/{job_id}_output.mp4")
    if not os.path.exists(output_path):
        raise HTTPException(status_code=404, detail="ุงู„ููŠุฏูŠูˆ ุบูŠุฑ ู…ูˆุฌูˆุฏ")
    return FileResponse(
        output_path,
        media_type="video/mp4",
        filename="clean_video.mp4",
        background=BackgroundTask(cleanup_job_output, job_id),
    )


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=7860)