TroglodyteDerivations commited on
Commit
bf0b180
Β·
verified Β·
1 Parent(s): 90386fb

Upload 8 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ images/flux_krea_00001_.png filter=lfs diff=lfs merge=lfs -text
37
+ images/flux_krea_00002_.png filter=lfs diff=lfs merge=lfs -text
38
+ images/flux_krea_00014_.png filter=lfs diff=lfs merge=lfs -text
app.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import gradio as gr
3
+ import matplotlib.pyplot as plt
4
+ import requests, validators
5
+ import torch
6
+ import pathlib
7
+ from PIL import Image
8
+ from transformers import AutoFeatureExtractor, YolosForObjectDetection, DetrForObjectDetection
9
+ import os
10
+ import warnings
11
+
12
+ warnings.filterwarnings("ignore", category=FutureWarning)
13
+ os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
14
+
15
+ # colors for visualization
16
+ COLORS = [
17
+ [0.000, 0.447, 0.741],
18
+ [0.850, 0.325, 0.098],
19
+ [0.929, 0.694, 0.125],
20
+ [0.494, 0.184, 0.556],
21
+ [0.466, 0.674, 0.188],
22
+ [0.301, 0.745, 0.933]
23
+ ]
24
+
25
+ def make_prediction(img, feature_extractor, model):
26
+ inputs = feature_extractor(img, return_tensors="pt")
27
+ outputs = model(**inputs)
28
+ img_size = torch.tensor([tuple(reversed(img.size))])
29
+ processed_outputs = feature_extractor.post_process(outputs, img_size)
30
+ return processed_outputs[0]
31
+
32
+ def fig2img(fig):
33
+ buf = io.BytesIO()
34
+ fig.savefig(buf)
35
+ buf.seek(0)
36
+ pil_img = Image.open(buf)
37
+ basewidth = 750
38
+ wpercent = (basewidth/float(pil_img.size[0]))
39
+ hsize = int((float(pil_img.size[1])*float(wpercent)))
40
+ img = pil_img.resize((basewidth,hsize), Image.Resampling.LANCZOS)
41
+ return img
42
+
43
+ def visualize_prediction(img, output_dict, threshold=0.5, id2label=None):
44
+ keep = output_dict["scores"] > threshold
45
+ boxes = output_dict["boxes"][keep].tolist()
46
+ scores = output_dict["scores"][keep].tolist()
47
+ labels = output_dict["labels"][keep].tolist()
48
+
49
+ if id2label is not None:
50
+ labels = [id2label[x] for x in labels]
51
+
52
+ plt.figure(figsize=(50, 50))
53
+ plt.imshow(img)
54
+ ax = plt.gca()
55
+ colors = COLORS * 100
56
+ for score, (xmin, ymin, xmax, ymax), label, color in zip(scores, boxes, labels, colors):
57
+ if label == 'license-plates':
58
+ ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, fill=False, color=color, linewidth=10))
59
+ ax.text(xmin, ymin, f"{label}: {score:0.2f}", fontsize=60, bbox=dict(facecolor="yellow", alpha=0.8))
60
+ plt.axis("off")
61
+ return fig2img(plt.gcf())
62
+
63
+ def get_original_image(url_input):
64
+ if validators.url(url_input):
65
+ try:
66
+ response = requests.get(url_input, stream=True)
67
+ response.raise_for_status()
68
+ image = Image.open(response.raw)
69
+ return image
70
+ except Exception as e:
71
+ print(f"Error loading image from URL: {e}")
72
+ return None
73
+ return None
74
+
75
+ def detect_objects(model_name, url_input, image_input, webcam_input, threshold):
76
+ # Handle case where no image is provided
77
+ image = None
78
+
79
+ if validators.url(url_input) and url_input.strip():
80
+ image = get_original_image(url_input)
81
+ elif image_input is not None:
82
+ image = image_input
83
+ elif webcam_input is not None:
84
+ image = webcam_input
85
+
86
+ if image is None:
87
+ raise gr.Error("Please provide an image via URL, file upload, or webcam")
88
+
89
+ # Extract model and feature extractor
90
+ feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
91
+
92
+ if "yolos" in model_name:
93
+ model = YolosForObjectDetection.from_pretrained(model_name)
94
+ elif "detr" in model_name:
95
+ model = DetrForObjectDetection.from_pretrained(model_name)
96
+
97
+ # Make prediction
98
+ processed_outputs = make_prediction(image, feature_extractor, model)
99
+
100
+ # Visualize prediction
101
+ viz_img = visualize_prediction(image, processed_outputs, threshold, model.config.id2label)
102
+
103
+ return viz_img
104
+
105
+ def set_example_image(example: list) -> dict:
106
+ return gr.Image.update(value=example[0])
107
+
108
+ def set_example_url(example: list) -> dict:
109
+ image = get_original_image(example[0])
110
+ return gr.Textbox.update(value=example[0]), gr.Image.update(value=image)
111
+
112
+ title = """<h1 id="title">License Plate Detection with YOLOS</h1>"""
113
+
114
+ description = """
115
+ # πŸš—βœ¨ Customize Your Biblical Porsche Scene Showcase βœ¨πŸš—
116
+
117
+ **YOLOS: When a Vision Transformer Gets Divine Revelation**
118
+
119
+ Behold! YOLOS is a Vision Transformer (ViT) that achieved 42 AP on COCO - not just a number, but *the answer to everything* (including which disciple gets shotgun in your biblical Porsche).
120
+
121
+ **The Scripture According to YOLOS:**
122
+ - "In the beginning was the Sequence, and the Sequence was One" - YOLOS 1:1
123
+ - Trained on 118k sacred images from the COCO testament
124
+ - Performs miracles at detecting heavenly vehicles and license plates
125
+ - Fine-tuned on the "Book of Car Plates" (443 verses of automotive divinity)
126
+
127
+ **Biblical Porsche Detection Capabilities:**
128
+ - βœ… Finds Peter's Porsche at the Gates of Heaven
129
+ - βœ… Spots Moses' license plate ("LET-M-PPL-GO")
130
+ - βœ… Detects David's sports car facing Goliath's SUV
131
+ - βœ… Locates the Holy Ghost's invisible convertible
132
+
133
+ *"And lo, the model saith: thou shalt look at only one sequence, and it shall be enough to find thy Porsche in the Red Sea of data."*
134
+
135
+ **Warning:** May occasionally confuse manna with hubcaps. Results not guaranteed in actual biblical times (camels not detected).
136
+ Links to HuggingFace Models:
137
+ - [nickmuchi/yolos-small-rego-plates-detection](https://huggingface.co/nickmuchi/yolos-small-rego-plates-detection)
138
+ """
139
+
140
+ models = ["nickmuchi/yolos-small-finetuned-license-plate-detection","nickmuchi/detr-resnet50-license-plate-detection"]
141
+
142
+ # FIXED: Use "resolve/main" URLs instead of "blob/main" for raw images
143
+ urls = [
144
+ "https://huggingface.co/spaces/TroglodyteDerivations/Customize_your_biblical_Porsche_scene_Showcase/resolve/main/images/flux_krea_00005_.png",
145
+ "https://huggingface.co/spaces/TroglodyteDerivations/Customize_your_biblical_Porsche_scene_Showcase/resolve/main/images/flux_krea_00007_.png"
146
+ ]
147
+
148
+ images = [[path.as_posix()] for path in sorted(pathlib.Path('images').rglob('*.*')) if path.suffix.lower() in ['.webp', '.jpg', '.jpeg', '.png']]
149
+
150
+ tik_tok_link = """
151
+ [![](https://img.shields.io/badge/TikTok-@porsche-000000?style=flat&logo=tiktok&logoColor=white)](https://www.tiktok.com/@porsche)
152
+ """
153
+
154
+ css = '''
155
+ h1#title {
156
+ text-align: center;
157
+ }
158
+ '''
159
+ demo = gr.Blocks()
160
+
161
+ with demo:
162
+ gr.Markdown(title)
163
+ gr.Markdown(description)
164
+ gr.Markdown(tik_tok_link)
165
+ options = gr.Dropdown(choices=models,label='Object Detection Model',value=models[0],show_label=True)
166
+ slider_input = gr.Slider(minimum=0.2,maximum=1,value=0.5,step=0.1,label='Prediction Threshold')
167
+
168
+ with gr.Tabs():
169
+ with gr.TabItem('Image URL'):
170
+ with gr.Row():
171
+ with gr.Column():
172
+ url_input = gr.Textbox(lines=2,label='Enter valid image URL here..')
173
+ original_image = gr.Image(height=750, width=750)
174
+ # Update the change event to handle errors
175
+ url_input.change(
176
+ get_original_image,
177
+ inputs=[url_input],
178
+ outputs=[original_image],
179
+ show_progress=True
180
+ )
181
+ with gr.Column():
182
+ img_output_from_url = gr.Image(height=750, width=750)
183
+
184
+ with gr.Row():
185
+ example_url = gr.Examples(
186
+ examples=urls,
187
+ inputs=[url_input],
188
+ outputs=[original_image],
189
+ fn=set_example_url,
190
+ cache_examples=False
191
+ )
192
+
193
+ url_but = gr.Button('Detect')
194
+
195
+ with gr.TabItem('Image Upload'):
196
+ with gr.Row():
197
+ img_input = gr.Image(type='pil', height=750, width=750)
198
+ img_output_from_upload= gr.Image(height=750, width=750)
199
+
200
+ with gr.Row():
201
+ example_images = gr.Examples(examples=images,inputs=[img_input])
202
+
203
+
204
+ img_but = gr.Button('Detect')
205
+
206
+ with gr.TabItem('WebCam'):
207
+ with gr.Row():
208
+ web_input = gr.Image(sources=['webcam'], type='pil', height=750, width=750, streaming=True)
209
+ img_output_from_webcam= gr.Image(height=750, width=750)
210
+
211
+ cam_but = gr.Button('Detect')
212
+
213
+ url_but.click(detect_objects,inputs=[options,url_input,img_input,web_input,slider_input],outputs=[img_output_from_url],queue=True)
214
+ img_but.click(detect_objects,inputs=[options,url_input,img_input,web_input,slider_input],outputs=[img_output_from_upload],queue=True)
215
+ cam_but.click(detect_objects,inputs=[options,url_input,img_input,web_input,slider_input],outputs=[img_output_from_webcam],queue=True)
216
+
217
+ gr.Markdown("[![](https://img.shields.io/badge/TikTok-Follow%20@porsche-000000?style=social&logo=tiktok)](https://www.tiktok.com/@porsche)")
218
+
219
+ demo.launch(debug=True, css=css)
image-1.webp ADDED
image-2.webp ADDED
image.webp ADDED
images/flux_krea_00001_.png ADDED

Git LFS Details

  • SHA256: 7425a025f79d08063d5884b133e11773dab06d5052f75cad083917b5c09c84d4
  • Pointer size: 132 Bytes
  • Size of remote file: 1.44 MB
images/flux_krea_00002_.png ADDED

Git LFS Details

  • SHA256: eafd2535153eb7f9ec85c54c48a2b6217b3eff6ba00dd1abf1912afbc28811dc
  • Pointer size: 132 Bytes
  • Size of remote file: 1.43 MB
images/flux_krea_00014_.png ADDED

Git LFS Details

  • SHA256: c275c539cbe2211467252dd266bb9110c4539bc97df805754a63372909f5b728
  • Pointer size: 132 Bytes
  • Size of remote file: 1.33 MB
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ beautifulsoup4
2
+ bs4
3
+ requests-file
4
+ torch
5
+ transformers
6
+ validators
7
+ timm
8
+ gradio
9
+ matplotlib