kdhht2334 commited on
Commit
c87f530
·
1 Parent(s): 779f467

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -16
app.py CHANGED
@@ -1,17 +1,57 @@
 
1
  import gradio as gr
2
- from transformers import pipeline
3
-
4
- from transformers import AutoFeatureExtractor, AutoModelForImageClassification
5
-
6
- extractor = AutoFeatureExtractor.from_pretrained("kdhht2334/autotrain-diffusion-emotion-facial-expression-recognition-40429105176")
7
- fer_model = AutoModelForImageClassification.from_pretrained("kdhht2334/autotrain-diffusion-emotion-facial-expression-recognition-40429105176")
8
-
9
- pipe = pipeline(task="image-classification",
10
- # model that can do 7-emotion classification
11
- model=fer_model)
12
- gr.Interface.from_pipeline(pipe,
13
- title="7-emotion classification in DiffusionFER dataset",
14
- description="Facial expression recognition trained with Transformer",
15
- examples = ['happy.png', 'angry.png',],
16
- article = "Author: <a href=\"https://huggingface.co/FER-Universe\">Daeha Kim</a>",
17
- ).launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)