Artaxias commited on
Commit
9ecd270
Β·
verified Β·
1 Parent(s): 950e052

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +426 -0
app.py ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
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 delete_file(self, filename):
115
+ """Delete a file from NextCloud"""
116
+ url = self.get_webdav_url(filename)
117
+ max_retries = 3
118
+ for attempt in range(max_retries):
119
+ try:
120
+ response = self.session.delete(url, timeout=60)
121
+ response.raise_for_status()
122
+ return True
123
+ except requests.exceptions.Timeout:
124
+ if attempt == max_retries - 1:
125
+ raise
126
+ self.log(f"Delete timeout on attempt {attempt + 1}, retrying...")
127
+ continue
128
+ except Exception as e:
129
+ self.log(f"Warning: Could not delete {filename}: {e}")
130
+ return False
131
+
132
+ def list_files(self, remote_path=""):
133
+ url = self.get_webdav_url(remote_path)
134
+ max_retries = 3
135
+ for attempt in range(max_retries):
136
+ try:
137
+ response = self.session.request('PROPFIND', url, headers={'Depth': '1'}, timeout=60)
138
+ response.raise_for_status()
139
+
140
+ files = []
141
+ lines = response.text.split('<d:href>')
142
+ for line in lines:
143
+ if '</d:href>' in line:
144
+ href = line.split('</d:href>')[0]
145
+ if '/webdav/' in href:
146
+ filename = href.split('/webdav/')[-1]
147
+ if filename and not filename.endswith('/'):
148
+ files.append(filename)
149
+
150
+ return files
151
+ except requests.exceptions.Timeout:
152
+ if attempt == max_retries - 1:
153
+ raise
154
+ self.log(f"List files timeout on attempt {attempt + 1}, retrying...")
155
+ continue
156
+
157
+ def create_folder(self, folder_name):
158
+ url = self.get_webdav_url(folder_name)
159
+ try:
160
+ self.session.request('MKCOL', url, timeout=60)
161
+ except:
162
+ pass
163
+
164
+ def get_image_list(self):
165
+ self.log("Filtering images...")
166
+ valid_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'}
167
+
168
+ self.images = [f for f in self.all_files if Path(f).suffix.lower() in valid_extensions]
169
+ self.images.sort()
170
+ self.log(f"βœ… Found {len(self.images)} images to classify")
171
+
172
+ def load_deep_analysis(self):
173
+ self.log("Looking for deep_training_analysis.json...")
174
+
175
+ # Check local file first
176
+ local_json_path = "deep_training_analysis.json"
177
+
178
+ if os.path.exists(local_json_path):
179
+ self.log(f"Found local file: {local_json_path}")
180
+ try:
181
+ with open(local_json_path, 'r') as f:
182
+ self.deep_analysis = json.load(f)
183
+
184
+ self.log("πŸ“š Loaded deep training analysis from local file")
185
+
186
+ self.category_embeddings = {}
187
+
188
+ for category in self.categories:
189
+ if category in self.deep_analysis:
190
+ data = self.deep_analysis[category]
191
+ avg_embedding = torch.tensor(data['avg_embedding'], dtype=torch.float32).to(self.device)
192
+ avg_embedding = avg_embedding / avg_embedding.norm()
193
+ self.category_embeddings[category] = avg_embedding
194
+
195
+ self.log(f" {category}: {data['num_training_images']} training images")
196
+ else:
197
+ self.category_embeddings[category] = self.create_text_embedding(category)
198
+
199
+ return
200
+
201
+ except Exception as e:
202
+ self.log(f"❌ Error loading local deep analysis: {e}")
203
+
204
+ # Fallback to text embeddings
205
+ self.log("⚠️ deep_training_analysis.json not found - using fallback embeddings")
206
+ self.category_embeddings = {cat: self.create_text_embedding(cat) for cat in self.categories}
207
+
208
+ def create_text_embedding(self, category):
209
+ descriptions = {
210
+ "1_Booth": "a photo of an exhibition booth at a trade show",
211
+ "2_Business_Interaction": "a photo of business people talking at a trade show",
212
+ "3_Buyer_Delegation": "a photo of a large group visiting a trade show",
213
+ "4_Aisle": "a photo of a trade show aisle between booths",
214
+ "5_Conference": "a photo of a conference presentation or seminar",
215
+ "6_Fairground": "a photo of an exhibition hall or fairground",
216
+ "7_Products": "a photo of products on display",
217
+ "8_Registration": "a photo of a registration desk or entry gate",
218
+ "9_Miscellaneous": "a miscellaneous trade show photo"
219
+ }
220
+
221
+ text = descriptions.get(category, "a photo")
222
+ text_input = clip.tokenize([text]).to(self.device)
223
+
224
+ with torch.no_grad():
225
+ text_features = self.model.encode_text(text_input)
226
+ text_features = text_features / text_features.norm(dim=-1, keepdim=True)
227
+
228
+ return text_features[0]
229
+
230
+ def classify_image(self, filename):
231
+ try:
232
+ # Download the image
233
+ img_data = self.download_file(filename)
234
+
235
+ # Classify it
236
+ img = Image.open(BytesIO(img_data)).convert('RGB')
237
+ img_input = self.preprocess(img).unsqueeze(0).to(self.device)
238
+
239
+ with torch.no_grad():
240
+ img_features = self.model.encode_image(img_input)
241
+ img_features = img_features / img_features.norm(dim=-1, keepdim=True)
242
+ img_features = img_features[0]
243
+
244
+ similarities = {}
245
+ for category, cat_embedding in self.category_embeddings.items():
246
+ similarity = (img_features @ cat_embedding).item()
247
+ similarities[category] = similarity
248
+
249
+ best_category = max(similarities, key=similarities.get)
250
+ confidence = similarities[best_category]
251
+
252
+ # Save to temp file
253
+ local_path = os.path.join(self.temp_dir, Path(filename).name)
254
+ with open(local_path, 'wb') as f:
255
+ f.write(img_data)
256
+
257
+ # Create category folder structure
258
+ category_folder = f"Classified/{best_category}"
259
+ self.create_folder("Classified")
260
+ self.create_folder(category_folder)
261
+
262
+ # Upload to new location
263
+ remote_dest = f"{category_folder}/{Path(filename).name}"
264
+ self.upload_file(local_path, remote_dest)
265
+
266
+ # **MOVE instead of COPY: Delete the original file**
267
+ self.delete_file(filename)
268
+
269
+ # Clean up temp file
270
+ os.remove(local_path)
271
+
272
+ return best_category, confidence
273
+
274
+ except Exception as e:
275
+ self.log(f"❌ Error processing {filename}: {str(e)}")
276
+ return "9_Miscellaneous", 0.0
277
+
278
+ def run(self):
279
+ self.log("πŸš€ Starting classification...")
280
+
281
+ # Create category folders
282
+ self.create_folder("Classified")
283
+ for cat in self.categories:
284
+ self.create_folder(f"Classified/{cat}")
285
+
286
+ stats = {cat: 0 for cat in self.categories}
287
+ confidences = {cat: [] for cat in self.categories}
288
+
289
+ for i, filename in enumerate(self.images, 1):
290
+ self.log(f"[{i}/{len(self.images)}] Processing {Path(filename).name}...")
291
+
292
+ category, confidence = self.classify_image(filename)
293
+
294
+ stats[category] += 1
295
+ confidences[category].append(confidence)
296
+
297
+ self.log(f" βœ“ Moved to {category} (confidence: {confidence:.3f})")
298
+
299
+ self.log("βœ… CLASSIFICATION COMPLETE!")
300
+ self.log("πŸ“ Results moved to: Classified/")
301
+ self.log("πŸ“ Original files have been removed from root folder")
302
+
303
+ result_text = "## βœ… Classification Complete!\n\n**Files have been MOVED (not copied) to categorized folders**\n\n**Results Summary:**\n\n"
304
+ for cat in self.categories:
305
+ count = stats[cat]
306
+ if count > 0:
307
+ avg_conf = sum(confidences[cat]) / len(confidences[cat])
308
+ result_text += f"- **{cat}**: {count} images (avg confidence: {avg_conf:.3f})\n"
309
+
310
+ # Clean up temp directory
311
+ shutil.rmtree(self.temp_dir)
312
+
313
+ return result_text
314
+
315
+ def classify_photos(share_url, share_password, progress=gr.Progress()):
316
+ if not share_url or not share_password:
317
+ return "❌ Please enter both the share URL and password", ""
318
+
319
+ logs = []
320
+
321
+ def log_callback(message):
322
+ logs.append(message)
323
+ log_display = "\n".join(logs[-20:])
324
+ return log_display
325
+
326
+ try:
327
+ progress(0, desc="Initializing...")
328
+
329
+ progress(0.1, desc="Connecting to NextCloud...")
330
+
331
+ classifier = SmartCLIPClassifierNextCloudShare(
332
+ share_url,
333
+ share_password,
334
+ progress_callback=log_callback
335
+ )
336
+
337
+ progress(0.3, desc=f"Found {len(classifier.images)} images to classify")
338
+
339
+ # Run classification
340
+ result = classifier.run()
341
+
342
+ progress(1.0, desc="Complete!")
343
+
344
+ return result, "\n".join(logs)
345
+
346
+ except requests.exceptions.Timeout:
347
+ error_msg = "❌ Connection Timeout: NextCloud is taking too long to respond.\n\nPlease check your network connection and try again."
348
+ return error_msg, "\n".join(logs)
349
+ except requests.exceptions.RequestException as e:
350
+ 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)}"
351
+ return error_msg, "\n".join(logs)
352
+ except Exception as e:
353
+ error_msg = f"❌ Error: {str(e)}\n\nPlease check your share URL and password and try again."
354
+ return error_msg, "\n".join(logs)
355
+
356
+ # Gradio Interface
357
+ with gr.Blocks(title="Trade Show Photo Classifier", theme=gr.themes.Soft()) as demo:
358
+ gr.Markdown("# πŸ€– Trade Show Photo Classifier")
359
+ gr.Markdown("Automatically classify your trade show photos using AI-powered image recognition")
360
+
361
+ gr.Markdown("""
362
+ ### πŸ“‹ Setup Instructions:
363
+
364
+ 1. Upload your photos to a NextCloud folder
365
+ 2. Create a public share link for that folder
366
+ 3. **Important:** When creating the share, enable **"Allow upload and editing"** (click the three dots β†’ Share settings)
367
+ 4. Set a password for the share
368
+ 5. Copy the share URL and password below
369
+ 6. Click "Start Classification"
370
+
371
+ **⚠️ Note: Files will be MOVED (not copied) to the Classified folder. Original files will be deleted from the root.**
372
+ """)
373
+
374
+ with gr.Row():
375
+ with gr.Column():
376
+ share_url = gr.Textbox(
377
+ label="NextCloud Share URL",
378
+ placeholder="https://cloud2.messefrankfurtexchange.com/s/...",
379
+ info="Enter the public share link to your NextCloud folder"
380
+ )
381
+ share_password = gr.Textbox(
382
+ label="Share Password",
383
+ type="password",
384
+ info="Enter the password for the NextCloud share"
385
+ )
386
+ classify_btn = gr.Button("πŸš€ Start Classification", variant="primary", size="lg")
387
+
388
+ with gr.Row():
389
+ with gr.Column():
390
+ gr.Markdown("### πŸ“Š Results")
391
+ output = gr.Markdown()
392
+
393
+ with gr.Column():
394
+ gr.Markdown("### πŸ“ Classification Log")
395
+ logs_output = gr.Textbox(
396
+ label="Progress",
397
+ lines=15,
398
+ max_lines=20,
399
+ interactive=False,
400
+ show_label=False
401
+ )
402
+
403
+ classify_btn.click(
404
+ fn=classify_photos,
405
+ inputs=[share_url, share_password],
406
+ outputs=[output, logs_output]
407
+ )
408
+
409
+ gr.Markdown("---")
410
+ gr.Markdown("""
411
+ **Categories:**
412
+ - 1_Booth: Exhibition booths
413
+ - 2_Business_Interaction: Business conversations
414
+ - 3_Buyer_Delegation: Group visits
415
+ - 4_Aisle: Walkways between booths
416
+ - 5_Conference: Presentations and seminars
417
+ - 6_Fairground: Exhibition halls
418
+ - 7_Products: Product displays
419
+ - 8_Registration: Entry and registration areas
420
+ - 9_Miscellaneous: Other trade show content
421
+
422
+ *Powered by OpenAI CLIP | Deployed on Hugging Face Spaces*
423
+ """)
424
+
425
+ if __name__ == "__main__":
426
+ demo.launch()