Humphreykowl commited on
Commit
2e2d3e6
·
verified ·
1 Parent(s): 22328b7

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -0
app.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, io, shutil, zipfile, hashlib, json
2
+ from pathlib import Path
3
+ from typing import List, Dict, Tuple
4
+
5
+
6
+ import gradio as gr
7
+ import numpy as np
8
+ from PIL import Image
9
+ import cv2
10
+
11
+
12
+ import torch
13
+ from transformers import BlipProcessor, BlipForConditionalGeneration
14
+
15
+
16
+ # -------- Settings --------
17
+ DEFAULT_MODEL = "Salesforce/blip-image-captioning-base" # CPU friendly
18
+ BIG_MODEL = "Salesforce/blip-image-captioning-large" # better on T4/A10G
19
+
20
+
21
+ # Blur threshold: lower => more tolerant (keep blurrier images)
22
+ BLUR_VAR_THRESHOLD = 100.0
23
+
24
+
25
+ # Work dirs inside the Space container
26
+ ROOT = Path("workspace")
27
+ IMAGES_DIR = ROOT / "images"
28
+ EXPORT_DIR = ROOT / "export"
29
+ ROOT.mkdir(parents=True, exist_ok=True)
30
+ IMAGES_DIR.mkdir(parents=True, exist_ok=True)
31
+ EXPORT_DIR.mkdir(parents=True, exist_ok=True)
32
+
33
+
34
+ # -------- Utilities --------
35
+
36
+
37
+ def clear_workspace():
38
+ if IMAGES_DIR.exists():
39
+ shutil.rmtree(IMAGES_DIR)
40
+ if EXPORT_DIR.exists():
41
+ shutil.rmtree(EXPORT_DIR)
42
+ IMAGES_DIR.mkdir(parents=True, exist_ok=True)
43
+ EXPORT_DIR.mkdir(parents=True, exist_ok=True)
44
+
45
+
46
+
47
+
48
+ def is_image(fname: str) -> bool:
49
+ ext = str(fname).lower().split(".")[-1]
50
+ return ext in ["jpg", "jpeg", "png", "bmp", "webp"]
51
+
52
+
53
+
54
+
55
+ def laplacian_var_blur(pil_img: Image.Image) -> float:
56
+ arr = np.array(pil_img.convert("L"))
57
+ fm = cv2.Laplacian(arr, cv2.CV_64F).var()
58
+ return float(fm)
59
+
60
+
61
+
62
+
63
+ def dhash(pil_img: Image.Image, hash_size: int = 8) -> str:
64
+ # Perceptual dHash for near-duplicate filtering
65
+ img = pil_img.convert("L").resize((hash_size + 1, hash_size), Image.LANCZOS)
66
+ diff = np.array(img)[:, 1:] > np.array(img)[:, :-1]
67
+ return ''.join('1' if v else '0' for v in diff.flatten())
68
+
69
+
70
+
71
+
72
+ def save_uploaded_files(files: List[gr.File]) -> List[str]:
73
+ saved = []
74
+ for f in files:
75
+ if f is None:
76
+ continue
77
+ name = os.path.basename(f.name)
78
+ dst = IMAGES_DIR / name
79
+ shutil.copy(f.name, dst)
80
+ saved.append(str(dst))
81
+ return saved
82
+
83
+
84
+
85
+
86
+ def unzip_to_images(zbytes: bytes) -> List[str]:
87
+ saved = []
88
+ with zipfile.ZipFile(io.BytesIO(zbytes)) as zf:
89
+ demo.launch()