Rekham1110 commited on
Commit
122012a
·
verified ·
1 Parent(s): bc0a800

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -20
app.py CHANGED
@@ -4,7 +4,8 @@ import os
4
  from dotenv import load_dotenv
5
  from simple_salesforce import Salesforce
6
  from datetime import datetime
7
- import random # For mock predictions
 
8
 
9
  # Load environment variables
10
  load_dotenv()
@@ -22,55 +23,62 @@ 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
- # Valid milestone values from Salesforce picklist
32
  VALID_MILESTONES = ["Foundation", "Walls Erected", "Planning", "Completed"]
33
 
34
- # Mock AI model for milestone detection (since we can't train a real model here)
35
  def mock_ai_model(image):
36
- # Preprocessing: Resize, normalize (simulated)
37
  img = image.convert("RGB")
38
  max_size = 1024
39
  img.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
40
-
41
- # Simulate milestone detection by picking a random valid value
42
  milestone = random.choice(VALID_MILESTONES)
43
- completion_percent = random.choice([10, 30, 50, 80, 100]) # Just for variety
44
  confidence_score = round(random.uniform(0.85, 0.95), 2)
45
-
46
  return milestone, completion_percent, confidence_score
47
 
48
- # Function for Gradio UI to process the image
49
- def process_image(image):
50
  try:
51
  if image is None:
52
  return "Error: Please upload an image to proceed.", "Pending", "", "", 0
53
 
54
  img = Image.open(image)
55
-
56
  image_size_mb = os.path.getsize(image) / (1024 * 1024)
57
  if image_size_mb > 20:
58
  return "Error: Image size exceeds 20MB.", "Failure", "", "", 0
59
  if not str(image).lower().endswith(('.jpg', '.jpeg', '.png')):
60
  return "Error: Only JPG/PNG images are supported.", "Failure", "", "", 0
61
 
62
- # Run mock AI model
63
- milestone, percent_complete, confidence_score = mock_ai_model(img)
64
-
65
  unique_id = datetime.now().strftime("%Y%m%d%H%M%S")
 
 
 
66
 
 
 
 
 
 
 
 
 
67
  record = {
68
- "Name__c": unique_id,
69
  "Current_Milestone__c": milestone,
70
  "Completion_Percentage__c": percent_complete,
71
  "Last_Updated_On__c": datetime.now().isoformat(),
72
  "Upload_Status__c": "Success",
73
- "Comments__c": f"AI Prediction: {milestone} with {confidence_score*100}% confidence"
 
74
  }
75
 
76
  try:
@@ -89,10 +97,13 @@ def process_image(image):
89
  except Exception as e:
90
  return f"Error: {str(e)}", "Failure", "", "", 0
91
 
92
- # Gradio interface for testing
93
  with gr.Blocks(css=".gradio-container {background-color: #f0f4f8; font-family: Arial;} .title {color: #2c3e50; font-size: 24px; text-align: center;}") as demo:
94
  gr.Markdown("<h1 class='title'>Construction Milestone Detector</h1>")
95
- image_input = gr.Image(type="filepath", label="Upload Construction Site Photo (JPG/PNG, ≤ 20MB)")
 
 
 
96
  submit_button = gr.Button("Process Image")
97
  output_text = gr.Textbox(label="Result")
98
  upload_status = gr.Textbox(label="Upload Status")
@@ -102,7 +113,7 @@ with gr.Blocks(css=".gradio-container {background-color: #f0f4f8; font-family: A
102
 
103
  submit_button.click(
104
  fn=process_image,
105
- inputs=[image_input],
106
  outputs=[output_text, upload_status, milestone, confidence, progress]
107
  )
108
 
 
4
  from dotenv import load_dotenv
5
  from simple_salesforce import Salesforce
6
  from datetime import datetime
7
+ import random
8
+ import shutil
9
 
10
  # Load environment variables
11
  load_dotenv()
 
23
  username=SF_USERNAME,
24
  password=SF_PASSWORD,
25
  security_token=SF_SECURITY_TOKEN,
26
+ domain='login'
27
  )
28
  except Exception as e:
29
  print(f"Salesforce connection failed: {str(e)}")
30
  raise
31
 
32
+ # Valid milestones
33
  VALID_MILESTONES = ["Foundation", "Walls Erected", "Planning", "Completed"]
34
 
35
+ # Mock AI prediction
36
  def mock_ai_model(image):
 
37
  img = image.convert("RGB")
38
  max_size = 1024
39
  img.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
 
 
40
  milestone = random.choice(VALID_MILESTONES)
41
+ completion_percent = random.choice([10, 30, 50, 80, 100])
42
  confidence_score = round(random.uniform(0.85, 0.95), 2)
 
43
  return milestone, completion_percent, confidence_score
44
 
45
+ # Gradio function
46
+ def process_image(image, project_name):
47
  try:
48
  if image is None:
49
  return "Error: Please upload an image to proceed.", "Pending", "", "", 0
50
 
51
  img = Image.open(image)
 
52
  image_size_mb = os.path.getsize(image) / (1024 * 1024)
53
  if image_size_mb > 20:
54
  return "Error: Image size exceeds 20MB.", "Failure", "", "", 0
55
  if not str(image).lower().endswith(('.jpg', '.jpeg', '.png')):
56
  return "Error: Only JPG/PNG images are supported.", "Failure", "", "", 0
57
 
58
+ # Save image to public folder for URL generation
59
+ upload_dir = "public_uploads"
60
+ os.makedirs(upload_dir, exist_ok=True)
61
  unique_id = datetime.now().strftime("%Y%m%d%H%M%S")
62
+ image_filename = f"{unique_id}_{os.path.basename(image)}"
63
+ saved_image_path = os.path.join(upload_dir, image_filename)
64
+ shutil.copy(image, saved_image_path)
65
 
66
+ # Create public URL assuming you're serving /public_uploads/ via static web server (e.g., on localhost or external host)
67
+ public_url_base = os.getenv("PUBLIC_URL_BASE", "http://localhost:7860/public_uploads")
68
+ image_url = f"{public_url_base}/{image_filename}"
69
+
70
+ # Predict
71
+ milestone, percent_complete, confidence_score = mock_ai_model(img)
72
+
73
+ # Construct Salesforce record
74
  record = {
75
+ "Name__c": project_name,
76
  "Current_Milestone__c": milestone,
77
  "Completion_Percentage__c": percent_complete,
78
  "Last_Updated_On__c": datetime.now().isoformat(),
79
  "Upload_Status__c": "Success",
80
+ "Comments__c": f"AI Prediction: {milestone} with {confidence_score*100}% confidence",
81
+ "Last_Updated_Image__c": image_url
82
  }
83
 
84
  try:
 
97
  except Exception as e:
98
  return f"Error: {str(e)}", "Failure", "", "", 0
99
 
100
+ # Gradio UI
101
  with gr.Blocks(css=".gradio-container {background-color: #f0f4f8; font-family: Arial;} .title {color: #2c3e50; font-size: 24px; text-align: center;}") as demo:
102
  gr.Markdown("<h1 class='title'>Construction Milestone Detector</h1>")
103
+ with gr.Row():
104
+ image_input = gr.Image(type="filepath", label="Upload Construction Site Photo (JPG/PNG, ≤ 20MB)")
105
+ project_name_input = gr.Textbox(label="Project Name (Required)", placeholder="e.g. Project_12345")
106
+
107
  submit_button = gr.Button("Process Image")
108
  output_text = gr.Textbox(label="Result")
109
  upload_status = gr.Textbox(label="Upload Status")
 
113
 
114
  submit_button.click(
115
  fn=process_image,
116
+ inputs=[image_input, project_name_input],
117
  outputs=[output_text, upload_status, milestone, confidence, progress]
118
  )
119