Artaxias commited on
Commit
950e052
·
verified ·
1 Parent(s): 76662e0

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -398
app.py DELETED
@@ -1,398 +0,0 @@
1
- import gradio as gr
2
- import os
3
- import json
4
- import shutil
5
- from pathlib import Path
6
- from PIL import Image
7
- import torch
8
- import clip
9
- import numpy as np
10
- import requests
11
- from io import BytesIO
12
- import tempfile
13
-
14
- # Global variables for CLIP model (load once, reuse)
15
- _clip_model = None
16
- _clip_preprocess = None
17
- _device = None
18
-
19
- def get_clip_model():
20
- global _clip_model, _clip_preprocess, _device
21
- if _clip_model is None:
22
- _device = "cuda" if torch.cuda.is_available() else "cpu"
23
- _clip_model, _clip_preprocess = clip.load("ViT-B/32", device=_device)
24
- return _clip_model, _clip_preprocess, _device
25
-
26
- class SmartCLIPClassifierNextCloudShare:
27
- def __init__(self, share_url, share_password, progress_callback=None):
28
-
29
- self.share_url = share_url.rstrip('/')
30
- self.share_password = share_password
31
- self.progress_callback = progress_callback
32
-
33
- self.session = requests.Session()
34
- self.session.auth = (self.get_share_token(), share_password)
35
-
36
- self.temp_dir = tempfile.mkdtemp()
37
-
38
- self.categories = [
39
- "1_Booth",
40
- "2_Business_Interaction",
41
- "3_Buyer_Delegation",
42
- "4_Aisle",
43
- "5_Conference",
44
- "6_Fairground",
45
- "7_Products",
46
- "8_Registration",
47
- "9_Miscellaneous"
48
- ]
49
-
50
- self.log("Loading CLIP model...")
51
- self.model, self.preprocess, self.device = get_clip_model()
52
- self.log(f"✅ CLIP loaded on {self.device}")
53
-
54
- self.load_deep_analysis()
55
-
56
- self.log("🔍 Scanning NextCloud share...")
57
- self.all_files = self.list_files("")
58
- self.log(f"Found {len(self.all_files)} total files")
59
-
60
- self.get_image_list()
61
-
62
- def log(self, message):
63
- if self.progress_callback:
64
- self.progress_callback(message)
65
- print(message)
66
-
67
- def get_share_token(self):
68
- return self.share_url.split('/s/')[-1]
69
-
70
- def get_webdav_url(self, path=""):
71
- token = self.get_share_token()
72
- base = self.share_url.rsplit('/s/', 1)[0]
73
- if path:
74
- return f"{base}/public.php/webdav/{path}"
75
- return f"{base}/public.php/webdav/"
76
-
77
- def download_file(self, filename):
78
- url = self.get_webdav_url(filename)
79
- max_retries = 3
80
- for attempt in range(max_retries):
81
- try:
82
- response = self.session.get(url, timeout=60) # Increased to 60 seconds
83
- response.raise_for_status()
84
- return response.content
85
- except requests.exceptions.Timeout:
86
- if attempt == max_retries - 1:
87
- raise
88
- self.log(f"Timeout on attempt {attempt + 1}, retrying...")
89
- continue
90
-
91
- def upload_file(self, local_path, remote_filename):
92
- url = self.get_webdav_url(remote_filename)
93
-
94
- # Try to delete existing file first
95
- try:
96
- self.session.delete(url, timeout=60)
97
- except:
98
- pass
99
-
100
- # Now upload with retry
101
- max_retries = 3
102
- for attempt in range(max_retries):
103
- try:
104
- with open(local_path, 'rb') as f:
105
- response = self.session.put(url, data=f, timeout=60)
106
- response.raise_for_status()
107
- return
108
- except requests.exceptions.Timeout:
109
- if attempt == max_retries - 1:
110
- raise
111
- self.log(f"Upload timeout on attempt {attempt + 1}, retrying...")
112
- continue
113
-
114
- def list_files(self, remote_path=""):
115
- url = self.get_webdav_url(remote_path)
116
- max_retries = 3
117
- for attempt in range(max_retries):
118
- try:
119
- response = self.session.request('PROPFIND', url, headers={'Depth': '1'}, timeout=60)
120
- response.raise_for_status()
121
-
122
- files = []
123
- lines = response.text.split('<d:href>')
124
- for line in lines:
125
- if '</d:href>' in line:
126
- href = line.split('</d:href>')[0]
127
- if '/webdav/' in href:
128
- filename = href.split('/webdav/')[-1]
129
- if filename and not filename.endswith('/'):
130
- files.append(filename)
131
-
132
- return files
133
- except requests.exceptions.Timeout:
134
- if attempt == max_retries - 1:
135
- raise
136
- self.log(f"List files timeout on attempt {attempt + 1}, retrying...")
137
- continue
138
-
139
- def create_folder(self, folder_name):
140
- url = self.get_webdav_url(folder_name)
141
- try:
142
- self.session.request('MKCOL', url, timeout=60)
143
- except:
144
- pass
145
-
146
- def get_image_list(self):
147
- self.log("Filtering images...")
148
- valid_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'}
149
-
150
- self.images = [f for f in self.all_files if Path(f).suffix.lower() in valid_extensions]
151
- self.images.sort()
152
- self.log(f"✅ Found {len(self.images)} images to classify")
153
-
154
- def load_deep_analysis(self):
155
- self.log("Looking for deep_training_analysis.json...")
156
-
157
- # Check local file first
158
- local_json_path = "deep_training_analysis.json"
159
-
160
- if os.path.exists(local_json_path):
161
- self.log(f"Found local file: {local_json_path}")
162
- try:
163
- with open(local_json_path, 'r') as f:
164
- self.deep_analysis = json.load(f)
165
-
166
- self.log("📚 Loaded deep training analysis from local file")
167
-
168
- self.category_embeddings = {}
169
-
170
- for category in self.categories:
171
- if category in self.deep_analysis:
172
- data = self.deep_analysis[category]
173
- avg_embedding = torch.tensor(data['avg_embedding'], dtype=torch.float32).to(self.device)
174
- avg_embedding = avg_embedding / avg_embedding.norm()
175
- self.category_embeddings[category] = avg_embedding
176
-
177
- self.log(f" {category}: {data['num_training_images']} training images")
178
- else:
179
- self.category_embeddings[category] = self.create_text_embedding(category)
180
-
181
- return
182
-
183
- except Exception as e:
184
- self.log(f"❌ Error loading local deep analysis: {e}")
185
-
186
- # Fallback to text embeddings
187
- self.log("⚠️ deep_training_analysis.json not found - using fallback embeddings")
188
- self.category_embeddings = {cat: self.create_text_embedding(cat) for cat in self.categories}
189
-
190
- def create_text_embedding(self, category):
191
- descriptions = {
192
- "1_Booth": "a photo of an exhibition booth at a trade show",
193
- "2_Business_Interaction": "a photo of business people talking at a trade show",
194
- "3_Buyer_Delegation": "a photo of a large group visiting a trade show",
195
- "4_Aisle": "a photo of a trade show aisle between booths",
196
- "5_Conference": "a photo of a conference presentation or seminar",
197
- "6_Fairground": "a photo of an exhibition hall or fairground",
198
- "7_Products": "a photo of products on display",
199
- "8_Registration": "a photo of a registration desk or entry gate",
200
- "9_Miscellaneous": "a miscellaneous trade show photo"
201
- }
202
-
203
- text = descriptions.get(category, "a photo")
204
- text_input = clip.tokenize([text]).to(self.device)
205
-
206
- with torch.no_grad():
207
- text_features = self.model.encode_text(text_input)
208
- text_features = text_features / text_features.norm(dim=-1, keepdim=True)
209
-
210
- return text_features[0]
211
-
212
- def classify_image(self, filename):
213
- try:
214
- img_data = self.download_file(filename)
215
-
216
- img = Image.open(BytesIO(img_data)).convert('RGB')
217
- img_input = self.preprocess(img).unsqueeze(0).to(self.device)
218
-
219
- with torch.no_grad():
220
- img_features = self.model.encode_image(img_input)
221
- img_features = img_features / img_features.norm(dim=-1, keepdim=True)
222
- img_features = img_features[0]
223
-
224
- similarities = {}
225
- for category, cat_embedding in self.category_embeddings.items():
226
- similarity = (img_features @ cat_embedding).item()
227
- similarities[category] = similarity
228
-
229
- best_category = max(similarities, key=similarities.get)
230
- confidence = similarities[best_category]
231
-
232
- local_path = os.path.join(self.temp_dir, Path(filename).name)
233
- with open(local_path, 'wb') as f:
234
- f.write(img_data)
235
-
236
- category_folder = f"Classified/{best_category}"
237
- self.create_folder("Classified")
238
- self.create_folder(category_folder)
239
-
240
- remote_dest = f"{category_folder}/{Path(filename).name}"
241
- self.upload_file(local_path, remote_dest)
242
-
243
- os.remove(local_path)
244
-
245
- return best_category, confidence
246
-
247
- except Exception as e:
248
- self.log(f"❌ Error processing {filename}: {str(e)}")
249
- return "9_Miscellaneous", 0.0
250
-
251
- def run(self):
252
- self.log("🚀 Starting classification...")
253
-
254
- self.create_folder("Classified")
255
- for cat in self.categories:
256
- self.create_folder(f"Classified/{cat}")
257
-
258
- stats = {cat: 0 for cat in self.categories}
259
- confidences = {cat: [] for cat in self.categories}
260
-
261
- for i, filename in enumerate(self.images, 1):
262
- self.log(f"[{i}/{len(self.images)}] Processing {Path(filename).name}...")
263
-
264
- category, confidence = self.classify_image(filename)
265
-
266
- stats[category] += 1
267
- confidences[category].append(confidence)
268
-
269
- self.log(f" ✓ Classified as {category} (confidence: {confidence:.3f})")
270
-
271
- self.log("✅ CLASSIFICATION COMPLETE!")
272
- self.log("📁 Results uploaded to: Classified/")
273
-
274
- result_text = "## ✅ Classification Complete!\n\n**Results Summary:**\n\n"
275
- for cat in self.categories:
276
- count = stats[cat]
277
- if count > 0:
278
- avg_conf = sum(confidences[cat]) / len(confidences[cat])
279
- result_text += f"- **{cat}**: {count} images (avg confidence: {avg_conf:.3f})\n"
280
-
281
- shutil.rmtree(self.temp_dir)
282
-
283
- return result_text
284
-
285
- def classify_photos(share_url, share_password, progress=gr.Progress()):
286
- if not share_url or not share_password:
287
- return "❌ Please enter both the share URL and password", ""
288
-
289
- logs = []
290
-
291
- def log_callback(message):
292
- logs.append(message)
293
- # Update progress display with latest logs
294
- log_display = "\n".join(logs[-20:]) # Show last 20 log lines
295
- return log_display
296
-
297
- try:
298
- progress(0, desc="Initializing...")
299
-
300
- progress(0.1, desc="Connecting to NextCloud...")
301
-
302
- classifier = SmartCLIPClassifierNextCloudShare(
303
- share_url,
304
- share_password,
305
- progress_callback=log_callback
306
- )
307
-
308
- progress(0.3, desc=f"Found {len(classifier.images)} images to classify")
309
-
310
- # Run classification
311
- result = classifier.run()
312
-
313
- progress(1.0, desc="Complete!")
314
-
315
- # Return both result and logs
316
- return result, "\n".join(logs)
317
-
318
- except requests.exceptions.Timeout:
319
- error_msg = "❌ Connection Timeout: NextCloud is taking too long to respond.\n\nPlease check your network connection and try again."
320
- return error_msg, "\n".join(logs)
321
- except requests.exceptions.RequestException as e:
322
- error_msg = f"❌ Connection Error: Could not connect to NextCloud.\n\nPlease check:\n- Your share URL is correct\n- Your password is correct\n- The share link has 'Allow upload and editing' enabled\n\nError details: {str(e)}"
323
- return error_msg, "\n".join(logs)
324
- except Exception as e:
325
- error_msg = f"❌ Error: {str(e)}\n\nPlease check your share URL and password and try again."
326
- return error_msg, "\n".join(logs)
327
-
328
- # Gradio Interface
329
- with gr.Blocks(title="Trade Show Photo Classifier", theme=gr.themes.Soft()) as demo:
330
- gr.Markdown("# 🤖 Trade Show Photo Classifier")
331
- gr.Markdown("Automatically classify your trade show photos using AI-powered image recognition")
332
-
333
- gr.Markdown("""
334
- ### 📋 Setup Instructions:
335
-
336
- 1. Upload your photos to a NextCloud folder
337
- 2. Create a public share link for that folder
338
- 3. **Important:** When creating the share, enable **"Allow upload and editing"** (click the three dots → Share settings)
339
- 4. Set a password for the share
340
- 5. Copy the share URL and password below
341
- 6. Click "Start Classification"
342
-
343
- The app will create a `Classified` folder with subfolders for each category.
344
- """)
345
-
346
- with gr.Row():
347
- with gr.Column():
348
- share_url = gr.Textbox(
349
- label="NextCloud Share URL",
350
- placeholder="https://cloud2.messefrankfurtexchange.com/s/...",
351
- info="Enter the public share link to your NextCloud folder"
352
- )
353
- share_password = gr.Textbox(
354
- label="Share Password",
355
- type="password",
356
- info="Enter the password for the NextCloud share"
357
- )
358
- classify_btn = gr.Button("🚀 Start Classification", variant="primary", size="lg")
359
-
360
- with gr.Row():
361
- with gr.Column():
362
- gr.Markdown("### 📊 Results")
363
- output = gr.Markdown()
364
-
365
- with gr.Column():
366
- gr.Markdown("### 📝 Classification Log")
367
- logs_output = gr.Textbox(
368
- label="Progress",
369
- lines=15,
370
- max_lines=20,
371
- interactive=False,
372
- show_label=False
373
- )
374
-
375
- classify_btn.click(
376
- fn=classify_photos,
377
- inputs=[share_url, share_password],
378
- outputs=[output, logs_output]
379
- )
380
-
381
- gr.Markdown("---")
382
- gr.Markdown("""
383
- **Categories:**
384
- - 1_Booth: Exhibition booths
385
- - 2_Business_Interaction: Business conversations
386
- - 3_Buyer_Delegation: Group visits
387
- - 4_Aisle: Walkways between booths
388
- - 5_Conference: Presentations and seminars
389
- - 6_Fairground: Exhibition halls
390
- - 7_Products: Product displays
391
- - 8_Registration: Entry and registration areas
392
- - 9_Miscellaneous: Other trade show content
393
-
394
- *Powered by OpenAI CLIP | Deployed on Hugging Face Spaces*
395
- """)
396
-
397
- if __name__ == "__main__":
398
- demo.launch()