Rekham1110 commited on
Commit
dddb2a9
·
verified ·
1 Parent(s): 8dbf69f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -22
app.py CHANGED
@@ -22,54 +22,53 @@ try:
22
  username=SF_USERNAME,
23
  password=SF_PASSWORD,
24
  security_token=SF_SECURITY_TOKEN,
25
- domain='login' # Use 'test' for sandbox
26
  )
27
  except Exception as e:
28
  print(f"Salesforce connection failed: {str(e)}")
29
  raise
30
 
31
- # Mock AI model for milestone detection (since we can't train a real model here)
 
 
 
 
 
 
 
 
32
  def mock_ai_model(image):
33
- # Preprocessing: Resize, normalize (simulated)
34
  img = image.convert("RGB")
35
  max_size = 1024
36
  img.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
37
 
38
- # Feature Extraction and Milestone Detection (simulated)
39
- # In a real scenario, this would use a CNN model trained on construction images
40
- # Using a generic milestone value that is likely to be in a Salesforce picklist
41
- milestone = "In Progress" # Changed to a more generic value to avoid picklist error
42
- completion_percent = 30 # Estimated based on the image
43
- confidence_score = round(random.uniform(0.85, 0.95), 2) # Random confidence between 85-95%
44
 
45
  return milestone, completion_percent, confidence_score
46
 
47
- # Function for Gradio UI to process the image
48
  def process_image(image):
49
  try:
50
- # Validate inputs
51
  if image is None:
52
  return "Error: Please upload an image to proceed.", "Pending", "", "", 0
53
 
54
- # Open and validate image
55
  img = Image.open(image)
56
 
57
- # Validate image size and type
58
  image_size_mb = os.path.getsize(image) / (1024 * 1024)
59
- if image_size_mb > 20: # Fixed the typo: image_size_mb_tb to image_size_mb
60
  return "Error: Image size exceeds 20MB.", "Failure", "", "", 0
61
  if not str(image).lower().endswith(('.jpg', '.jpeg', '.png')):
62
  return "Error: Only JPG/PNG images are supported.", "Failure", "", "", 0
63
 
64
- # Run mock AI model
65
  milestone, percent_complete, confidence_score = mock_ai_model(img)
66
-
67
- # Generate a unique identifier for the Salesforce record
68
  unique_id = datetime.now().strftime("%Y%m%d%H%M%S")
69
 
70
- # Store result in Salesforce
71
  record = {
72
- "Name__c": unique_id, # Use a timestamp-based unique ID
73
  "Current_Milestone__c": milestone,
74
  "Completion_Percentage__c": percent_complete,
75
  "Last_Updated_On__c": datetime.now().isoformat(),
@@ -78,7 +77,7 @@ def process_image(image):
78
  }
79
 
80
  try:
81
- sf.Construction__c.create(record) # Always create a new record
82
  except Exception as e:
83
  return f"Error: Failed to update Salesforce - {str(e)}", "Failure", "", "", 0
84
 
@@ -93,7 +92,7 @@ def process_image(image):
93
  except Exception as e:
94
  return f"Error: {str(e)}", "Failure", "", "", 0
95
 
96
- # Gradio interface for testing
97
  with gr.Blocks(css=".gradio-container {background-color: #f0f4f8; font-family: Arial;} .title {color: #2c3e50; font-size: 24px; text-align: center;}") as demo:
98
  gr.Markdown("<h1 class='title'>Construction Milestone Detector</h1>")
99
  image_input = gr.Image(type="filepath", label="Upload Construction Site Photo (JPG/PNG, ≤ 20MB)")
@@ -111,4 +110,4 @@ with gr.Blocks(css=".gradio-container {background-color: #f0f4f8; font-family: A
111
  )
112
 
113
  # Launch the Gradio app
114
- demo.launch(share=False) # Note: share=True may not work in all environments; you may need to run this locally
 
22
  username=SF_USERNAME,
23
  password=SF_PASSWORD,
24
  security_token=SF_SECURITY_TOKEN,
25
+ domain='login' # Use 'test' for sandbox orgs
26
  )
27
  except Exception as e:
28
  print(f"Salesforce connection failed: {str(e)}")
29
  raise
30
 
31
+ # Safe milestone values (must match Salesforce picklist exactly)
32
+ MILESTONE_MAPPING = {
33
+ "In Progress": "In_Progress",
34
+ "Started": "In_Progress",
35
+ "Completed": "Completed",
36
+ "Planning": "Planning"
37
+ }
38
+
39
+ # Mock AI model for milestone detection
40
  def mock_ai_model(image):
 
41
  img = image.convert("RGB")
42
  max_size = 1024
43
  img.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
44
 
45
+ # Simulated AI result
46
+ predicted_label = "In Progress" # This label is mapped to valid picklist
47
+ milestone = MILESTONE_MAPPING.get(predicted_label, "Planning") # Safe fallback
48
+ completion_percent = 30
49
+ confidence_score = round(random.uniform(0.85, 0.95), 2)
 
50
 
51
  return milestone, completion_percent, confidence_score
52
 
53
+ # Function for Gradio UI
54
  def process_image(image):
55
  try:
 
56
  if image is None:
57
  return "Error: Please upload an image to proceed.", "Pending", "", "", 0
58
 
 
59
  img = Image.open(image)
60
 
 
61
  image_size_mb = os.path.getsize(image) / (1024 * 1024)
62
+ if image_size_mb > 20:
63
  return "Error: Image size exceeds 20MB.", "Failure", "", "", 0
64
  if not str(image).lower().endswith(('.jpg', '.jpeg', '.png')):
65
  return "Error: Only JPG/PNG images are supported.", "Failure", "", "", 0
66
 
 
67
  milestone, percent_complete, confidence_score = mock_ai_model(img)
 
 
68
  unique_id = datetime.now().strftime("%Y%m%d%H%M%S")
69
 
 
70
  record = {
71
+ "Name__c": unique_id,
72
  "Current_Milestone__c": milestone,
73
  "Completion_Percentage__c": percent_complete,
74
  "Last_Updated_On__c": datetime.now().isoformat(),
 
77
  }
78
 
79
  try:
80
+ sf.Construction__c.create(record)
81
  except Exception as e:
82
  return f"Error: Failed to update Salesforce - {str(e)}", "Failure", "", "", 0
83
 
 
92
  except Exception as e:
93
  return f"Error: {str(e)}", "Failure", "", "", 0
94
 
95
+ # Gradio interface
96
  with gr.Blocks(css=".gradio-container {background-color: #f0f4f8; font-family: Arial;} .title {color: #2c3e50; font-size: 24px; text-align: center;}") as demo:
97
  gr.Markdown("<h1 class='title'>Construction Milestone Detector</h1>")
98
  image_input = gr.Image(type="filepath", label="Upload Construction Site Photo (JPG/PNG, ≤ 20MB)")
 
110
  )
111
 
112
  # Launch the Gradio app
113
+ demo.launch(share=False)