bhatanerohan commited on
Commit
07ca993
·
verified ·
1 Parent(s): 8481e27

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -9
app.py CHANGED
@@ -11,6 +11,7 @@ import logging
11
  from datetime import datetime
12
  import hashlib
13
  import shutil
 
14
  import gradio as gr
15
  from google import genai
16
  from google.genai import types
@@ -35,19 +36,42 @@ logger = logging.getLogger(__name__)
35
  LOGS_DIR = "generation_logs"
36
  os.makedirs(LOGS_DIR, exist_ok=True)
37
 
38
- def save_generation_log(prompt, images_dict, metadata=None):
39
- """Save generation logs with images"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
41
  session_id = hashlib.md5(f"{prompt}{timestamp}".encode()).hexdigest()[:8]
42
 
43
  session_dir = os.path.join(LOGS_DIR, f"{timestamp}_{session_id}")
44
  os.makedirs(session_dir, exist_ok=True)
45
 
46
- # Save metadata
47
  log_data = {
48
  "timestamp": timestamp,
49
  "session_id": session_id,
50
  "prompt": prompt,
 
 
 
51
  "metadata": metadata or {}
52
  }
53
 
@@ -333,9 +357,16 @@ def edit_3d_model(edit_prompt: str, transparent_image_path: str) -> str:
333
  # GRADIO UI FUNCTIONS
334
  # ============================================================
335
 
336
- def generate_3d_ui(prompt, progress=gr.Progress()):
337
  """UI wrapper with progress updates"""
 
 
 
 
 
 
338
  logger.info(f"=== NEW GENERATION REQUEST ===")
 
339
  logger.info(f"Prompt: {prompt}")
340
 
341
  if not client:
@@ -430,7 +461,7 @@ def generate_3d_ui(prompt, progress=gr.Progress()):
430
  with open(glb_path, 'wb') as f:
431
  f.write(glb_bytes)
432
 
433
- # Save logs
434
  images_dict = {
435
  "original": original_path,
436
  "transparent": nobg_path,
@@ -442,7 +473,12 @@ def generate_3d_ui(prompt, progress=gr.Progress()):
442
  "ply_size_bytes": len(ply_bytes),
443
  "glb_size_bytes": len(glb_bytes) if glb_bytes else 0
444
  }
445
- save_generation_log(prompt, images_dict, metadata)
 
 
 
 
 
446
 
447
  progress(1.0, desc="Done!")
448
  logger.info(f"✓ Generation complete!")
@@ -459,9 +495,16 @@ def generate_3d_ui(prompt, progress=gr.Progress()):
459
  )
460
 
461
 
462
- def edit_3d_ui(edit_prompt, current_image, edit_count, progress=gr.Progress()):
463
  """UI wrapper for editing"""
 
 
 
 
 
 
464
  logger.info(f"=== EDIT REQUEST #{edit_count + 1} ===")
 
465
  logger.info(f"Edit: {edit_prompt}")
466
 
467
  if current_image is None:
@@ -535,7 +578,7 @@ def edit_3d_ui(edit_prompt, current_image, edit_count, progress=gr.Progress()):
535
 
536
  new_edit_count = edit_count + 1
537
 
538
- # Save logs
539
  images_dict = {
540
  "edited": nobg_path,
541
  "mask": mask_path
@@ -545,7 +588,12 @@ def edit_3d_ui(edit_prompt, current_image, edit_count, progress=gr.Progress()):
545
  "edit_number": new_edit_count,
546
  "has_glb": glb_path is not None
547
  }
548
- save_generation_log(edit_prompt, images_dict, metadata)
 
 
 
 
 
549
 
550
  progress(1.0, desc=f"Edit #{new_edit_count} complete!")
551
  logger.info(f"✓ Edit #{new_edit_count} complete!")
@@ -603,6 +651,8 @@ with gr.Blocks() as main_ui:
603
  **This app is also an MCP Server!** Claude Desktop, Cursor, and other MCP clients can use the `generate_3d` and `edit_3d` tools.
604
 
605
  ⏱️ *Generation takes 1-2 minutes. First run may take longer as the model warms up.*
 
 
606
  """)
607
 
608
  gr.Markdown("## 1️⃣ Generate Initial 3D Model")
 
11
  from datetime import datetime
12
  import hashlib
13
  import shutil
14
+ import requests
15
  import gradio as gr
16
  from google import genai
17
  from google.genai import types
 
36
  LOGS_DIR = "generation_logs"
37
  os.makedirs(LOGS_DIR, exist_ok=True)
38
 
39
+ def get_location_from_ip(ip):
40
+ """Get approximate location from IP address"""
41
+ if ip == "unknown" or ip.startswith("127.") or ip.startswith("192.168."):
42
+ return {"country": "unknown", "city": "unknown"}
43
+
44
+ try:
45
+ response = requests.get(f"https://ipapi.co/{ip}/json/", timeout=2)
46
+ data = response.json()
47
+ return {
48
+ "ip": ip,
49
+ "country": data.get("country_name", "unknown"),
50
+ "city": data.get("city", "unknown"),
51
+ "region": data.get("region", "unknown"),
52
+ "latitude": data.get("latitude"),
53
+ "longitude": data.get("longitude")
54
+ }
55
+ except Exception as e:
56
+ logger.error(f"Geolocation failed: {e}")
57
+ return {"country": "unknown", "city": "unknown"}
58
+
59
+ def save_generation_log(prompt, images_dict, metadata=None, request_info=None):
60
+ """Save generation logs with images and user info"""
61
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
62
  session_id = hashlib.md5(f"{prompt}{timestamp}".encode()).hexdigest()[:8]
63
 
64
  session_dir = os.path.join(LOGS_DIR, f"{timestamp}_{session_id}")
65
  os.makedirs(session_dir, exist_ok=True)
66
 
67
+ # Save metadata WITH request info
68
  log_data = {
69
  "timestamp": timestamp,
70
  "session_id": session_id,
71
  "prompt": prompt,
72
+ "client_ip": request_info.get("ip") if request_info else None,
73
+ "location": request_info.get("location") if request_info else None,
74
+ "user_agent": request_info.get("user_agent") if request_info else None,
75
  "metadata": metadata or {}
76
  }
77
 
 
357
  # GRADIO UI FUNCTIONS
358
  # ============================================================
359
 
360
+ def generate_3d_ui(prompt, request: gr.Request, progress=gr.Progress()):
361
  """UI wrapper with progress updates"""
362
+
363
+ # Get client info
364
+ client_ip = request.client.host if request else "unknown"
365
+ location = get_location_from_ip(client_ip)
366
+ user_agent = request.headers.get("user-agent", "unknown") if request else "unknown"
367
+
368
  logger.info(f"=== NEW GENERATION REQUEST ===")
369
+ logger.info(f"IP: {client_ip} | Location: {location.get('city', 'unknown')}, {location.get('country', 'unknown')}")
370
  logger.info(f"Prompt: {prompt}")
371
 
372
  if not client:
 
461
  with open(glb_path, 'wb') as f:
462
  f.write(glb_bytes)
463
 
464
+ # Save logs WITH request info
465
  images_dict = {
466
  "original": original_path,
467
  "transparent": nobg_path,
 
473
  "ply_size_bytes": len(ply_bytes),
474
  "glb_size_bytes": len(glb_bytes) if glb_bytes else 0
475
  }
476
+ request_info = {
477
+ "ip": client_ip,
478
+ "location": location,
479
+ "user_agent": user_agent
480
+ }
481
+ save_generation_log(prompt, images_dict, metadata, request_info)
482
 
483
  progress(1.0, desc="Done!")
484
  logger.info(f"✓ Generation complete!")
 
495
  )
496
 
497
 
498
+ def edit_3d_ui(edit_prompt, current_image, edit_count, request: gr.Request, progress=gr.Progress()):
499
  """UI wrapper for editing"""
500
+
501
+ # Get client info
502
+ client_ip = request.client.host if request else "unknown"
503
+ location = get_location_from_ip(client_ip)
504
+ user_agent = request.headers.get("user-agent", "unknown") if request else "unknown"
505
+
506
  logger.info(f"=== EDIT REQUEST #{edit_count + 1} ===")
507
+ logger.info(f"IP: {client_ip} | Location: {location.get('city', 'unknown')}, {location.get('country', 'unknown')}")
508
  logger.info(f"Edit: {edit_prompt}")
509
 
510
  if current_image is None:
 
578
 
579
  new_edit_count = edit_count + 1
580
 
581
+ # Save logs WITH request info
582
  images_dict = {
583
  "edited": nobg_path,
584
  "mask": mask_path
 
588
  "edit_number": new_edit_count,
589
  "has_glb": glb_path is not None
590
  }
591
+ request_info = {
592
+ "ip": client_ip,
593
+ "location": location,
594
+ "user_agent": user_agent
595
+ }
596
+ save_generation_log(edit_prompt, images_dict, metadata, request_info)
597
 
598
  progress(1.0, desc=f"Edit #{new_edit_count} complete!")
599
  logger.info(f"✓ Edit #{new_edit_count} complete!")
 
651
  **This app is also an MCP Server!** Claude Desktop, Cursor, and other MCP clients can use the `generate_3d` and `edit_3d` tools.
652
 
653
  ⏱️ *Generation takes 1-2 minutes. First run may take longer as the model warms up.*
654
+
655
+ 📍 *Note: IP addresses and approximate locations are logged for analytics.*
656
  """)
657
 
658
  gr.Markdown("## 1️⃣ Generate Initial 3D Model")