Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,17 +1,57 @@
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
import gradio as gr
|
| 3 |
+
import torch
|
| 4 |
+
from transformers import AutoModelForImageClassification
|
| 5 |
+
import shutil
|
| 6 |
+
from optimum.pipelines import pipeline
|
| 7 |
+
|
| 8 |
+
device = 1 if torch.cuda.is_available() else "cpu"
|
| 9 |
+
|
| 10 |
+
chk_point = "kdhht2334/autotrain-diffusion-emotion-facial-expression-recognition-40429105176"
|
| 11 |
+
|
| 12 |
+
model = AutoModelForImageClassification.from_pretrained(chk_point)
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
pipe = pipeline(
|
| 16 |
+
"image-classification",
|
| 17 |
+
chk_point,
|
| 18 |
+
accelerator="bettertransformer",
|
| 19 |
+
device=device,
|
| 20 |
+
)
|
| 21 |
+
except NotImplementedError:
|
| 22 |
+
from transformers import pipeline
|
| 23 |
+
|
| 24 |
+
pipe = pipeline("image-classification", chk_point, device=device)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def make_label_folders():
|
| 28 |
+
folders = model.config.label2id.keys()
|
| 29 |
+
for folder in folders:
|
| 30 |
+
folder = Path(folder)
|
| 31 |
+
if not folder.exists():
|
| 32 |
+
folder.mkdir()
|
| 33 |
+
return folders
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def predictions_into_folders(files):
|
| 37 |
+
files = [file.name for file in files]
|
| 38 |
+
files = [
|
| 39 |
+
file for file in files if not file.startswith(".") and "DS_Store" not in file
|
| 40 |
+
]
|
| 41 |
+
folders = make_label_folders()
|
| 42 |
+
predictions = pipe(files)
|
| 43 |
+
for file, prediction in zip(files, predictions):
|
| 44 |
+
label = prediction[0]["label"]
|
| 45 |
+
file_name = Path(file).name
|
| 46 |
+
shutil.copy(file, f"{label}/{file_name}")
|
| 47 |
+
for folder in folders:
|
| 48 |
+
shutil.make_archive(folder, "zip", ".", folder)
|
| 49 |
+
return [f"{folder}.zip" for folder in folders]
|
| 50 |
+
|
| 51 |
+
demo = gr.Interface(
|
| 52 |
+
predictions_into_folders,
|
| 53 |
+
gr.Files(file_count="directory", file_types=["image"]),
|
| 54 |
+
gr.Files(),
|
| 55 |
+
cache_examples=True,
|
| 56 |
+
)
|
| 57 |
+
demo.launch(enable_queue=True)
|