jennifee commited on
Commit
aabac73
·
verified ·
1 Parent(s): 08cb245

initial commit

Browse files
Files changed (2) hide show
  1. app.py +122 -0
  2. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import zipfile
4
+ import pathlib
5
+ import tempfile
6
+
7
+ import gradio
8
+ import pandas
9
+ import PIL.Image
10
+
11
+ import huggingface_hub
12
+ import autogluon.multimodal
13
+
14
+ # Hardcoded Hub model (native zip)
15
+ MODEL_REPO_ID = "aedupuga/image-autogluon-predictor"
16
+ ZIP_FILENAME = "autogluon_image_predictor_dir.zip"
17
+ HF_TOKEN = os.getenv("HF_TOKEN", None)
18
+
19
+ # Local cache/extract dirs
20
+ CACHE_DIR = pathlib.Path("hf_assets")
21
+ EXTRACT_DIR = CACHE_DIR / "predictor_native"
22
+
23
+ # Download & load the native predictor
24
+ def _prepare_predictor_dir() -> str:
25
+ CACHE_DIR.mkdir(parents=True, exist_ok=True)
26
+ local_zip = huggingface_hub.hf_hub_download(
27
+ repo_id=MODEL_REPO_ID,
28
+ filename=ZIP_FILENAME,
29
+ repo_type="model",
30
+ token=HF_TOKEN,
31
+ local_dir=str(CACHE_DIR),
32
+ local_dir_use_symlinks=False,
33
+ )
34
+ if EXTRACT_DIR.exists():
35
+ shutil.rmtree(EXTRACT_DIR)
36
+ EXTRACT_DIR.mkdir(parents=True, exist_ok=True)
37
+ with zipfile.ZipFile(local_zip, "r") as zf:
38
+ zf.extractall(str(EXTRACT_DIR))
39
+ contents = list(EXTRACT_DIR.iterdir())
40
+ predictor_root = contents[0] if (len(contents) == 1 and contents[0].is_dir()) else EXTRACT_DIR
41
+ return str(predictor_root)
42
+
43
+ PREDICTOR_DIR = _prepare_predictor_dir()
44
+ PREDICTOR = autogluon.multimodal.MultiModalPredictor.load(PREDICTOR_DIR)
45
+
46
+ # Explicit class labels (edit copy as desired)
47
+ CLASS_LABELS = {0: "Fiction", 1: "Nonfiction"}
48
+
49
+ # Helper to map model class -> human label
50
+ def _human_label(c):
51
+ try:
52
+ ci = int(c)
53
+ return CLASS_LABELS.get(ci, str(c))
54
+ except Exception:
55
+ return CLASS_LABELS.get(c, str(c))
56
+
57
+ # Do the prediction!
58
+ def do_predict(pil_img: PIL.Image.Image):
59
+ # Make sure there's actually an image to work with
60
+ if pil_img is None:
61
+ return "No image provided.", {}, pandas.DataFrame(columns=["Predicted label", "Confidence (%)"])
62
+
63
+ # IF we have something to work with, save it and prepare the input
64
+ tmpdir = pathlib.Path(tempfile.mkdtemp())
65
+ img_path = tmpdir / "input.png"
66
+ pil_img.save(img_path)
67
+
68
+ df = pandas.DataFrame({"image": [str(img_path)]}) # For AutoGluon expected input format
69
+
70
+ # For class probabilities
71
+ proba_df = PREDICTOR.predict_proba(df)
72
+
73
+ # For user-friendly column names
74
+ proba_df = proba_df.rename(columns={0: "Fiction", 1: "Nonfiction"})
75
+ row = proba_df.iloc[0]
76
+
77
+ # For pretty ranked dict expected by gr.Label
78
+ pretty_dict = {
79
+ "Fiction": float(row.get("Fiction", 0.0)),
80
+ "Nonfiction": float(row.get("Nonfiction", 0.0)),
81
+ }
82
+
83
+ return pretty_dict
84
+
85
+ # Representative example images! These can be local or links.
86
+ EXAMPLES = [
87
+ ["https://pictures.abebooks.com/inventory/31174850639.jpg"],
88
+ ["https://res.cloudinary.com/bloomsbury-atlas/image/upload/w_568,c_scale,dpr_1.5/jackets/9781408872925.jpg"],
89
+ ["https://images3.penguinrandomhouse.com/cover/9780593191897"]
90
+ ]
91
+
92
+ # Gradio UI
93
+ with gradio.Blocks() as demo:
94
+
95
+ # Provide an introduction
96
+ gradio.Markdown("# Judge a Book by its Cover: Fiction or Nonfiction?")
97
+ gradio.Markdown("""
98
+ This is a simple app that demonstrates how to use an autogluon multimodal
99
+ predictor in a gradio space to predict the contents of a picture. To use,
100
+ just upload a photo. The result should be generated automatically.
101
+ """)
102
+
103
+ # Interface for the incoming image
104
+ image_in = gradio.Image(type="pil", label="Input image", sources=["upload", "webcam"])
105
+
106
+ # Interface elements to show htte result and probabilities
107
+ proba_pretty = gradio.Label(num_top_classes=2, label="Class probabilities")
108
+
109
+ # Whenever a new image is uploaded, update the result
110
+ image_in.change(fn=do_predict, inputs=[image_in], outputs=[proba_pretty])
111
+
112
+ # For clickable example images
113
+ gradio.Examples(
114
+ examples=EXAMPLES,
115
+ inputs=[image_in],
116
+ label="Representative examples",
117
+ examples_per_page=8,
118
+ cache_examples=False,
119
+ )
120
+
121
+ if __name__ == "__main__":
122
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ autogluon.multimodal
2
+ gradio
3
+ pandas
4
+ Pillow
5
+ huggingface_hub