Vara1605454 commited on
Commit
aa69a67
·
verified ·
1 Parent(s): 042f147

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -687
app.py CHANGED
@@ -1,701 +1,43 @@
1
-
2
- import base64
3
- import numpy as np
4
  import torch
5
- from flask import Flask, render_template, request
6
- from flask_socketio import SocketIO, emit
7
- from PIL import Image, ImageEnhance, ImageFilter
8
- from io import BytesIO
9
- import logging
10
- import threading
11
- import time
12
- from transformers import BlipProcessor, BlipForConditionalGeneration
13
- from collections import deque
14
- import cv2
15
- import asyncio
16
- from concurrent.futures import ThreadPoolExecutor
17
- import hashlib
18
- import json
19
- from datetime import datetime, timedelta
20
- import queue
21
-
22
- # ---- 1. ENHANCED SETUP ----
23
-
24
- # Suppress excessive logging from libraries
25
- logging.getLogger('engineio').setLevel(logging.ERROR)
26
- logging.getLogger('socketio').setLevel(logging.ERROR)
27
-
28
- # --- Enhanced Configuration ---
29
- FRAME_SKIP = 3 # Adaptive frame skipping
30
- IMAGE_SIZE = 224 # Optimized size for BLIP
31
- BUFFER_SIZE = 5 # Smart buffering
32
- MIN_CONFIDENCE_DIFF = 0.03
33
- MAX_WORKERS = 6 # Increased thread pool
34
- CACHE_SIZE = 500 # Larger cache with LRU
35
- BATCH_SIZE = 4 # Batch processing capability
36
 
37
- # Advanced performance settings
38
- ADAPTIVE_QUALITY = True
39
- MIN_PROCESSING_INTERVAL = 0.1 # Minimum time between processing
40
- SCENE_CHANGE_THRESHOLD = 0.15 # For scene change detection
41
- CAPTION_HISTORY_SIZE = 10 # Keep caption history for context
42
-
43
- # --- Flask & SocketIO App Initialization ---
44
  app = Flask(__name__)
45
- app.config['SECRET_KEY'] = 'your-very-secret-key!'
46
- socketio = SocketIO(app, async_mode='threading', logger=False, engineio_logger=False,
47
- cors_allowed_origins="*", ping_timeout=60, ping_interval=25)
48
-
49
- # --- Enhanced AI Model Setup ---
50
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
51
- print(f"Using device: {device}")
52
-
53
- # Advanced thread pool with priority queue
54
- executor = ThreadPoolExecutor(max_workers=MAX_WORKERS, thread_name_prefix="caption_worker")
55
- priority_queue = queue.PriorityQueue()
56
-
57
- # Load BLIP model with advanced optimizations
58
- try:
59
- print("Loading BLIP model with optimizations...")
60
- processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
61
- model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
62
- model = model.to(device)
63
- model.eval()
64
-
65
- # Advanced CUDA optimizations
66
- if device.type == 'cuda':
67
- torch.backends.cudnn.benchmark = True
68
- torch.backends.cudnn.deterministic = False
69
- model = torch.jit.script(model) # TorchScript optimization
70
- from torch.cuda.amp import autocast, GradScaler
71
- USE_AMP = True
72
- scaler = GradScaler()
73
- print("CUDA optimizations and TorchScript enabled")
74
- else:
75
- USE_AMP = False
76
-
77
- # Warm up the model
78
- dummy_image = Image.new('RGB', (IMAGE_SIZE, IMAGE_SIZE), color='black')
79
- dummy_inputs = processor(dummy_image, return_tensors="pt").to(device)
80
- with torch.no_grad():
81
- _ = model.generate(**dummy_inputs, max_length=10)
82
- print("Model warmed up successfully!")
83
-
84
- except Exception as e:
85
- print(f"Error loading BLIP model: {e}")
86
- exit()
87
-
88
- # --- Advanced Caching System ---
89
- class LRUCache:
90
- def __init__(self, max_size):
91
- self.max_size = max_size
92
- self.cache = {}
93
- self.access_order = deque()
94
- self.lock = threading.Lock()
95
-
96
- def get(self, key):
97
- with self.lock:
98
- if key in self.cache:
99
- # Move to end (most recently used)
100
- self.access_order.remove(key)
101
- self.access_order.append(key)
102
- return self.cache[key]
103
- return None
104
-
105
- def put(self, key, value):
106
- with self.lock:
107
- if key in self.cache:
108
- self.access_order.remove(key)
109
- elif len(self.cache) >= self.max_size:
110
- # Remove least recently used
111
- oldest = self.access_order.popleft()
112
- del self.cache[oldest]
113
-
114
- self.cache[key] = value
115
- self.access_order.append(key)
116
-
117
- def clear(self):
118
- with self.lock:
119
- self.cache.clear()
120
- self.access_order.clear()
121
-
122
- # --- Advanced Frame Processing ---
123
- frame_counters = {}
124
- processing_locks = {}
125
- caption_buffers = {}
126
- last_captions = {}
127
- processing_times = {}
128
- caption_history = {}
129
- last_processed_time = {}
130
- scene_features = {} # For scene change detection
131
-
132
- # Enhanced caching
133
- caption_cache = LRUCache(CACHE_SIZE)
134
- batch_queue = {}
135
-
136
- # --- Smart Performance Monitor ---
137
- class AdvancedPerformanceMonitor:
138
- def __init__(self):
139
- self.metrics = {
140
- 'total_frames': 0,
141
- 'processed_frames': 0,
142
- 'cache_hits': 0,
143
- 'cache_misses': 0,
144
- 'batch_processed': 0,
145
- 'scene_changes': 0,
146
- 'processing_times': deque(maxlen=100),
147
- 'start_time': time.time()
148
- }
149
- self.lock = threading.Lock()
150
-
151
- def log_frame(self, processing_time=None, cache_hit=False, batch_size=1, scene_change=False):
152
- with self.lock:
153
- self.metrics['total_frames'] += 1
154
- if processing_time:
155
- self.metrics['processed_frames'] += 1
156
- self.metrics['processing_times'].append(processing_time)
157
- if batch_size > 1:
158
- self.metrics['batch_processed'] += batch_size
159
-
160
- if cache_hit:
161
- self.metrics['cache_hits'] += 1
162
- else:
163
- self.metrics['cache_misses'] += 1
164
-
165
- if scene_change:
166
- self.metrics['scene_changes'] += 1
167
-
168
- def get_stats(self):
169
- with self.lock:
170
- if not self.metrics['processing_times']:
171
- return {"avg_time": 0, "cache_hit_rate": 0, "fps": 0, "efficiency": 0}
172
-
173
- total_time = time.time() - self.metrics['start_time']
174
- avg_processing_time = np.mean(self.metrics['processing_times'])
175
- cache_hit_rate = self.metrics['cache_hits'] / max(1, self.metrics['total_frames'])
176
- processing_fps = self.metrics['processed_frames'] / max(1, avg_processing_time * self.metrics['processed_frames'])
177
- efficiency = self.metrics['processed_frames'] / max(1, self.metrics['total_frames'])
178
-
179
- return {
180
- "avg_time": avg_processing_time,
181
- "cache_hit_rate": cache_hit_rate,
182
- "processing_fps": processing_fps,
183
- "efficiency": efficiency,
184
- "total_frames": self.metrics['total_frames'],
185
- "scene_changes": self.metrics['scene_changes'],
186
- "batch_efficiency": self.metrics['batch_processed'] / max(1, self.metrics['processed_frames'])
187
- }
188
-
189
- perf_monitor = AdvancedPerformanceMonitor()
190
-
191
- # --- Smart Image Preprocessing ---
192
- def smart_preprocess_image(image, enhance_quality=True):
193
- """Enhanced image preprocessing with quality improvements."""
194
- # Convert to RGB if needed
195
- if image.mode != 'RGB':
196
- image = image.convert('RGB')
197
-
198
- if enhance_quality:
199
- # Enhance image quality
200
- # Sharpening
201
- enhancer = ImageEnhance.Sharpness(image)
202
- image = enhancer.enhance(1.2)
203
-
204
- # Contrast enhancement
205
- enhancer = ImageEnhance.Contrast(image)
206
- image = enhancer.enhance(1.1)
207
-
208
- # Color enhancement
209
- enhancer = ImageEnhance.Color(image)
210
- image = enhancer.enhance(1.05)
211
-
212
- # Smart resizing with aspect ratio preservation
213
- original_size = image.size
214
- if original_size[0] != original_size[1]: # Non-square image
215
- # Crop to square from center
216
- min_dim = min(original_size)
217
- left = (original_size[0] - min_dim) // 2
218
- top = (original_size[1] - min_dim) // 2
219
- image = image.crop((left, top, left + min_dim, top + min_dim))
220
-
221
- # Resize with high-quality resampling
222
- image = image.resize((IMAGE_SIZE, IMAGE_SIZE), Image.LANCZOS)
223
-
224
- return image
225
-
226
- def advanced_hash_image(image):
227
- """Generate robust hash for image similarity detection."""
228
- # Create perceptual hash using multiple features
229
- img_small = image.resize((16, 16), Image.LANCZOS)
230
- img_gray = img_small.convert('L')
231
-
232
- # Get pixel values
233
- pixels = list(img_gray.getdata())
234
-
235
- # Create hash from average and differences
236
- avg = sum(pixels) / len(pixels)
237
- hash_bits = ''.join('1' if pixel > avg else '0' for pixel in pixels)
238
-
239
- # Additional feature: edge detection hash
240
- img_array = np.array(img_gray)
241
- edges = cv2.Canny(img_array, 50, 150)
242
- edge_hash = hashlib.md5(edges.tobytes()).hexdigest()[:8]
243
-
244
- return hash_bits + edge_hash
245
-
246
- def detect_scene_change(sid, current_features):
247
- """Detect significant scene changes."""
248
- if sid not in scene_features:
249
- scene_features[sid] = current_features
250
- return True
251
-
252
- # Compare with previous features
253
- prev_features = scene_features[sid]
254
-
255
- # Calculate similarity (Hamming distance for hash)
256
- if len(current_features) == len(prev_features):
257
- diff_count = sum(c1 != c2 for c1, c2 in zip(current_features[:256], prev_features[:256]))
258
- similarity = 1 - (diff_count / 256)
259
-
260
- scene_features[sid] = current_features
261
- return similarity < (1 - SCENE_CHANGE_THRESHOLD)
262
-
263
- scene_features[sid] = current_features
264
- return True
265
 
266
- # ---- 2. ENHANCED WEBSOCKET HANDLERS ----
267
-
268
- @socketio.on('connect')
269
- def handle_connect():
270
- """Enhanced client connection handler."""
271
- print(f"Client connected: {request.sid}")
272
- sid = request.sid
273
-
274
- # Initialize client data
275
- frame_counters[sid] = 0
276
- processing_locks[sid] = threading.Lock()
277
- caption_buffers[sid] = deque(maxlen=BUFFER_SIZE)
278
- last_captions[sid] = ""
279
- processing_times[sid] = deque(maxlen=20)
280
- caption_history[sid] = deque(maxlen=CAPTION_HISTORY_SIZE)
281
- last_processed_time[sid] = 0
282
- scene_features[sid] = ""
283
- batch_queue[sid] = []
284
-
285
- # Send initial status
286
- emit('status', {'connected': True, 'device': str(device)})
287
-
288
- @socketio.on('disconnect')
289
- def handle_disconnect():
290
- """Enhanced client disconnection handler."""
291
- print(f"Client disconnected: {request.sid}")
292
- cleanup_client(request.sid)
293
-
294
- def cleanup_client(sid):
295
- """Enhanced client cleanup."""
296
- for data_dict in [frame_counters, processing_locks, caption_buffers,
297
- last_captions, processing_times, caption_history,
298
- last_processed_time, scene_features, batch_queue]:
299
- if sid in data_dict:
300
- del data_dict[sid]
301
-
302
- @socketio.on('image')
303
- def handle_image(data_image):
304
- """Enhanced image handling with smart processing."""
305
- sid = request.sid
306
-
307
- # Initialize if not exists
308
- if sid not in frame_counters:
309
- handle_connect()
310
-
311
- frame_counters[sid] += 1
312
- current_time = time.time()
313
-
314
- # Adaptive frame skipping based on processing load
315
- skip_factor = FRAME_SKIP
316
- if sid in processing_times and processing_times[sid]:
317
- avg_time = np.mean(processing_times[sid])
318
- if avg_time > 0.5: # If processing is slow, skip more frames
319
- skip_factor = FRAME_SKIP * 2
320
- elif avg_time < 0.1: # If processing is fast, skip fewer frames
321
- skip_factor = max(1, FRAME_SKIP // 2)
322
-
323
- if frame_counters[sid] % skip_factor != 0:
324
- perf_monitor.log_frame() # Count skipped frames
325
- return
326
-
327
- # Rate limiting
328
- if current_time - last_processed_time.get(sid, 0) < MIN_PROCESSING_INTERVAL:
329
- return
330
-
331
- # Check if we're already processing
332
- if not processing_locks[sid].acquire(blocking=False):
333
- return
334
-
335
- last_processed_time[sid] = current_time
336
-
337
- # Submit to thread pool with priority
338
- priority = 1 # Normal priority
339
- future = executor.submit(process_frame_advanced, sid, data_image, priority)
340
-
341
- def process_frame_advanced(sid, data_image, priority=1):
342
- """Advanced frame processing with multiple optimizations."""
343
- start_time = time.time()
344
-
345
- try:
346
- # Decode image
347
- image_data = base64.b64decode(data_image.split(',')[1])
348
- img = Image.open(BytesIO(image_data))
349
-
350
- # Smart preprocessing
351
- img = smart_preprocess_image(img, enhance_quality=ADAPTIVE_QUALITY)
352
-
353
- # Generate advanced hash
354
- img_hash = advanced_hash_image(img)
355
-
356
- # Scene change detection
357
- scene_changed = detect_scene_change(sid, img_hash)
358
-
359
- # Check cache first
360
- cached_caption = caption_cache.get(img_hash)
361
- if cached_caption and not scene_changed:
362
- caption = cached_caption
363
- cache_hit = True
364
- else:
365
- # Generate new caption
366
- caption = generate_caption_advanced(img)
367
- caption_cache.put(img_hash, caption)
368
- cache_hit = False
369
-
370
- # Smart caption updating with context
371
- if should_update_caption_advanced(sid, caption, scene_changed):
372
- # Add to caption history
373
- caption_history[sid].append({
374
- 'caption': caption,
375
- 'timestamp': time.time(),
376
- 'scene_changed': scene_changed
377
- })
378
-
379
- last_captions[sid] = caption
380
-
381
- # Enhanced caption with context
382
- contextual_caption = add_context_to_caption(sid, caption)
383
-
384
- print(f"New caption for {sid}: {contextual_caption}")
385
-
386
- # Send enhanced response
387
- socketio.emit('caption', {
388
- 'caption': contextual_caption,
389
- 'raw_caption': caption,
390
- 'timestamp': time.time(),
391
- 'confidence': 0.95 if not cache_hit else 1.0,
392
- 'scene_changed': scene_changed,
393
- 'processing_time': time.time() - start_time
394
- }, room=sid)
395
-
396
- # Update performance metrics
397
- processing_time = time.time() - start_time
398
- processing_times[sid].append(processing_time)
399
- perf_monitor.log_frame(processing_time, cache_hit, scene_change=scene_changed)
400
-
401
- # Periodic performance logging
402
- if frame_counters[sid] % 100 == 0:
403
- stats = perf_monitor.get_stats()
404
- print(f"Client {sid}: Avg: {stats['avg_time']:.3f}s, Cache: {stats['cache_hit_rate']:.2f}, "
405
- f"Efficiency: {stats['efficiency']:.2f}, Scene changes: {stats['scene_changes']}")
406
-
407
- except Exception as e:
408
- print(f"Error processing frame for {sid}: {e}")
409
- socketio.emit('caption', {
410
- 'caption': f"Processing error: {str(e)[:50]}...",
411
- 'timestamp': time.time(),
412
- 'confidence': 0.0,
413
- 'error': True
414
- }, room=sid)
415
-
416
- finally:
417
- if sid in processing_locks:
418
- processing_locks[sid].release()
419
-
420
- def should_update_caption_advanced(sid, new_caption, scene_changed):
421
- """Advanced caption update logic with context awareness."""
422
- if sid not in last_captions or scene_changed:
423
- return True
424
-
425
- last_caption = last_captions[sid]
426
-
427
- # Always update on errors or initial state
428
- if not last_caption or "error" in last_caption.lower() or last_caption == "Processing...":
429
- return True
430
-
431
- # Check caption history for patterns
432
- if sid in caption_history and len(caption_history[sid]) > 1:
433
- recent_captions = [item['caption'] for item in list(caption_history[sid])[-3:]]
434
- if len(set(recent_captions)) == 1 and new_caption not in recent_captions:
435
- return True # Break repetition
436
-
437
- # Enhanced semantic similarity with weighted keywords
438
- words_old = set(last_caption.lower().split())
439
- words_new = set(new_caption.lower().split())
440
-
441
- # Weighted keywords for different importance levels
442
- high_priority_words = {'walking', 'running', 'sitting', 'standing', 'jumping', 'dancing',
443
- 'eating', 'drinking', 'driving', 'flying', 'swimming', 'climbing'}
444
- medium_priority_words = {'holding', 'wearing', 'looking', 'pointing', 'smiling', 'talking',
445
- 'reading', 'writing', 'playing', 'working', 'sleeping'}
446
- objects_words = {'car', 'bike', 'phone', 'book', 'cup', 'computer', 'dog', 'cat', 'bird'}
447
-
448
- # Check for high priority changes
449
- old_high = words_old.intersection(high_priority_words)
450
- new_high = words_new.intersection(high_priority_words)
451
- if old_high != new_high:
452
- return True
453
-
454
- # Check for significant object changes
455
- old_objects = words_old.intersection(objects_words)
456
- new_objects = words_new.intersection(objects_words)
457
- if len(old_objects.symmetric_difference(new_objects)) > 1:
458
- return True
459
-
460
- # Advanced similarity calculation
461
- intersection = words_old.intersection(words_new)
462
- union = words_old.union(words_new)
463
-
464
- if len(union) == 0:
465
- return True
466
-
467
- # Weighted similarity based on word importance
468
- weight_old = sum(3 if word in high_priority_words else 2 if word in medium_priority_words else 1
469
- for word in words_old)
470
- weight_new = sum(3 if word in high_priority_words else 2 if word in medium_priority_words else 1
471
- for word in words_new)
472
- weight_intersection = sum(3 if word in high_priority_words else 2 if word in medium_priority_words else 1
473
- for word in intersection)
474
-
475
- weighted_similarity = (2 * weight_intersection) / (weight_old + weight_new) if (weight_old + weight_new) > 0 else 0
476
-
477
- return weighted_similarity < 0.75
478
-
479
- def add_context_to_caption(sid, caption):
480
- """Add temporal context to captions."""
481
- if sid not in caption_history or len(caption_history[sid]) < 2:
482
- return caption
483
-
484
- recent_captions = [item['caption'] for item in list(caption_history[sid])[-3:]]
485
-
486
- # Detect action continuity
487
- action_words = {'walking', 'running', 'sitting', 'standing', 'eating', 'drinking'}
488
- current_actions = set(caption.lower().split()).intersection(action_words)
489
-
490
- if current_actions:
491
- for prev_caption in recent_captions[:-1]:
492
- prev_actions = set(prev_caption.lower().split()).intersection(action_words)
493
- if current_actions == prev_actions:
494
- return f"{caption} (continuing)"
495
-
496
- return caption
497
 
498
- def generate_caption_advanced(image):
499
- """Advanced caption generation with optimizations."""
500
- try:
501
- inputs = processor(image, return_tensors="pt").to(device)
502
-
503
- # Enhanced generation parameters
504
- generation_kwargs = {
505
- 'max_length': 30,
506
- 'min_length': 8,
507
- 'num_beams': 5,
508
- 'do_sample': True,
509
- 'temperature': 0.8,
510
- 'top_p': 0.95,
511
- 'top_k': 50,
512
- 'early_stopping': True,
513
- 'no_repeat_ngram_size': 3,
514
- 'length_penalty': 1.1,
515
- 'repetition_penalty': 1.2
516
- }
517
-
518
- if USE_AMP and device.type == 'cuda':
519
- with autocast():
520
- with torch.no_grad():
521
- generated_ids = model.generate(**inputs, **generation_kwargs)
522
- else:
523
- with torch.no_grad():
524
- generated_ids = model.generate(**inputs, **generation_kwargs)
525
-
526
- caption = processor.decode(generated_ids[0], skip_special_tokens=True)
527
- return enhance_caption_advanced(caption)
528
-
529
- except Exception as e:
530
- print(f"Error in generate_caption_advanced: {e}")
531
- return "Processing scene..."
532
 
533
- def enhance_caption_advanced(caption):
534
- """Advanced caption enhancement with NLP improvements."""
535
- caption = caption.strip()
536
- if not caption:
537
- return "Analyzing scene..."
538
-
539
- # Remove common prefixes more intelligently
540
- prefixes_to_remove = [
541
- "a picture of ", "an image of ", "this is ", "there is ", "there are ",
542
- "the image shows ", "this image shows ", "a photo of ", "a photograph of "
543
- ]
544
-
545
- caption_lower = caption.lower()
546
- for prefix in prefixes_to_remove:
547
- if caption_lower.startswith(prefix):
548
- caption = caption[len(prefix):]
549
- break
550
-
551
- # Advanced replacements for more natural language
552
- replacements = {
553
- r'\b(man|woman|person) (is )?(sitting on|standing in|walking on)\b':
554
- lambda m: f"{m.group(1)} {m.group(3).replace('on', 'at').replace('in', 'within')}",
555
- r'\bholding a\b': 'holding',
556
- r'\bwearing a\b': 'wearing',
557
- r'\blooking at the\b': 'observing the',
558
- r'\bstanding next to\b': 'beside',
559
- r'\bwalking down\b': 'walking along',
560
- r'\bsitting at\b': 'seated at'
561
- }
562
-
563
- import re
564
- for pattern, replacement in replacements.items():
565
- if callable(replacement):
566
- caption = re.sub(pattern, replacement, caption, flags=re.IGNORECASE)
567
- else:
568
- caption = re.sub(pattern, replacement, caption, flags=re.IGNORECASE)
569
-
570
- # Capitalize appropriately
571
- if caption and not caption[0].isupper():
572
- caption = caption[0].upper() + caption[1:]
573
-
574
- # Add descriptive variety
575
- action_variations = {
576
- 'walking': ['strolling', 'moving', 'walking'],
577
- 'sitting': ['seated', 'resting', 'sitting'],
578
- 'standing': ['positioned', 'standing', 'upright'],
579
- 'holding': ['grasping', 'carrying', 'holding'],
580
- 'looking': ['observing', 'viewing', 'watching', 'looking at']
581
- }
582
-
583
- # Randomly vary some common actions (seed based on caption for consistency)
584
- import random
585
- random.seed(hash(caption) % 1000)
586
-
587
- for base_action, variations in action_variations.items():
588
- if base_action in caption.lower():
589
- if random.random() < 0.3: # 30% chance to vary
590
- caption = caption.replace(base_action, random.choice(variations))
591
-
592
- return caption
593
 
594
- # ---- 3. ENHANCED FLASK ROUTES ----
595
 
596
  @app.route('/')
597
- def index():
598
- """Render the main HTML page."""
599
- return render_template('index.html')
 
 
 
 
 
600
 
601
  @app.route('/status')
602
  def status():
603
- """Enhanced server status with detailed metrics."""
604
- stats = perf_monitor.get_stats()
605
- return {
606
- 'active_connections': len(frame_counters),
607
- 'device': str(device),
608
- 'configuration': {
609
- 'frame_skip': FRAME_SKIP,
610
- 'image_size': IMAGE_SIZE,
611
- 'buffer_size': BUFFER_SIZE,
612
- 'cache_size': CACHE_SIZE,
613
- 'batch_size': BATCH_SIZE,
614
- 'adaptive_quality': ADAPTIVE_QUALITY
615
- },
616
- 'performance': stats,
617
- 'cache_info': {
618
- 'size': len(caption_cache.cache),
619
- 'max_size': CACHE_SIZE
620
- },
621
- 'optimizations': {
622
- 'mixed_precision': USE_AMP,
623
- 'torch_script': device.type == 'cuda',
624
- 'thread_pool_size': MAX_WORKERS
625
- }
626
- }
627
-
628
- @app.route('/metrics')
629
- def metrics():
630
- """Detailed performance metrics endpoint."""
631
- stats = perf_monitor.get_stats()
632
-
633
- # Client-specific metrics
634
- client_metrics = {}
635
- for sid in frame_counters:
636
- if sid in processing_times and processing_times[sid]:
637
- client_metrics[sid] = {
638
- 'frames_processed': frame_counters[sid],
639
- 'avg_processing_time': np.mean(processing_times[sid]),
640
- 'caption_history_size': len(caption_history.get(sid, [])),
641
- 'last_caption': last_captions.get(sid, "None")
642
- }
643
-
644
- return {
645
- 'global_metrics': stats,
646
- 'client_metrics': client_metrics,
647
- 'system_info': {
648
- 'device': str(device),
649
- 'cuda_available': torch.cuda.is_available(),
650
- 'cuda_memory': torch.cuda.get_device_properties(0).total_memory if torch.cuda.is_available() else None
651
- }
652
- }
653
-
654
- @app.route('/clear_cache')
655
- def clear_cache():
656
- """Clear all caches."""
657
- caption_cache.clear()
658
- return {'status': 'cache_cleared', 'timestamp': time.time()}
659
-
660
- @app.route('/config', methods=['GET', 'POST'])
661
- def config():
662
- """Dynamic configuration endpoint."""
663
- global FRAME_SKIP, ADAPTIVE_QUALITY, SCENE_CHANGE_THRESHOLD
664
-
665
- if request.method == 'POST':
666
- config_data = request.get_json()
667
- if 'frame_skip' in config_data:
668
- FRAME_SKIP = max(1, int(config_data['frame_skip']))
669
- if 'adaptive_quality' in config_data:
670
- ADAPTIVE_QUALITY = bool(config_data['adaptive_quality'])
671
- if 'scene_change_threshold' in config_data:
672
- SCENE_CHANGE_THRESHOLD = float(config_data['scene_change_threshold'])
673
-
674
- return {'status': 'updated', 'config': {
675
- 'frame_skip': FRAME_SKIP,
676
- 'adaptive_quality': ADAPTIVE_QUALITY,
677
- 'scene_change_threshold': SCENE_CHANGE_THRESHOLD
678
- }}
679
-
680
- return {
681
- 'frame_skip': FRAME_SKIP,
682
- 'adaptive_quality': ADAPTIVE_QUALITY,
683
- 'scene_change_threshold': SCENE_CHANGE_THRESHOLD
684
- }
685
 
686
- # ---- 4. ENHANCED STARTUP ----
687
  if __name__ == '__main__':
688
- print("=" * 60)
689
- print("🚀 Starting Enhanced Real-Time Video Captioning Server")
690
- print("=" * 60)
691
- print(f"📱 Device: {device}")
692
- print(f"🎯 Image Processing: {IMAGE_SIZE}x{IMAGE_SIZE}")
693
- print(f"⚡ Frame Skip: {FRAME_SKIP} (adaptive)")
694
- print(f"🧠 Mixed Precision: {USE_AMP}")
695
- print(f"🔄 Thread Pool: {MAX_WORKERS} workers")
696
- print(f"💾 Cache Size: {CACHE_SIZE} entries (LRU)")
697
- print(f"🎨 Quality Enhancement: {ADAPTIVE_QUALITY}")
698
- print(f"🔍 Scene Change Detection: Enabled")
699
- print("=" * 60)
700
-
701
- socketio.run(app, host='0.0.0.0', port=7860, debug=False, allow_unsafe_werkzeug=True)
 
1
+ from flask import Flask
 
 
2
  import torch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
 
 
 
 
 
 
 
4
  app = Flask(__name__)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
+ @app.route('/')
7
+ def hello():
8
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
9
+ return f"""
10
+ <h1>Video Captioning App - Test</h1>
11
+ <p>Device: {device}</p>
12
+ <p>PyTorch version: {torch.__version__}</p>
13
+ <p>App is running successfully!</p>
14
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ @app.route('/status')
17
+ def status():
18
+ return {'status': 'running', 'device': str(torch.device("cuda" if torch.cuda.is_available() else "cpu"))}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
+ if __name__ == '__main__':
21
+ print("Starting simple test app...")
22
+ app.run(host="0.0.0.0", port=7860, debug=False)from flask import Flask
23
+ import torch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ app = Flask(__name__)
26
 
27
  @app.route('/')
28
+ def hello():
29
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
30
+ return f"""
31
+ <h1>Video Captioning App - Test</h1>
32
+ <p>Device: {device}</p>
33
+ <p>PyTorch version: {torch.__version__}</p>
34
+ <p>App is running successfully!</p>
35
+ """
36
 
37
  @app.route('/status')
38
  def status():
39
+ return {'status': 'running', 'device': str(torch.device("cuda" if torch.cuda.is_available() else "cpu"))}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
 
41
  if __name__ == '__main__':
42
+ print("Starting simple test app...")
43
+ app.run(host="0.0.0.0", port=7860, debug=False)