chandra7799 commited on
Commit
32efefd
·
verified ·
1 Parent(s): 6c6a1e4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -84
app.py CHANGED
@@ -32,80 +32,81 @@ except Exception as e:
32
  raise
33
 
34
  # Valid milestones
35
- VALID_MILESTONES = ["Foundation", "Walls Erected", "Planning", "Completed"]
36
 
37
  # Adjust the timezone to your local timezone
38
  local_timezone = pytz.timezone("Asia/Kolkata")
39
 
40
- # Deterministic AI prediction with fixed confidence and percent
41
- def mock_ai_model(image):
42
- img = image.convert("RGB")
43
- max_size = 1024
44
- img.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
45
-
46
- img_bytes = img.tobytes()
47
- img_hash = int(hashlib.sha256(img_bytes).hexdigest(), 16)
48
-
49
- milestone_index = img_hash % len(VALID_MILESTONES)
50
- milestone = VALID_MILESTONES[milestone_index]
51
-
52
- milestone_completion_map = {
53
- "Planning": 10,
54
- "Foundation": 30,
55
- "Walls Erected": 50,
56
- "Completed": 100,
57
- }
58
- completion_percent = milestone_completion_map.get(milestone, 0)
59
-
60
- confidence_raw = 0.85 + ((img_hash % 1000) / 1000) * (0.95 - 0.85)
61
- confidence_score = round(confidence_raw, 2)
62
-
63
- return milestone, completion_percent, confidence_score
64
-
65
  # Image processing and Salesforce upload
66
- def process_image(image, project_name):
67
  try:
68
- if image is None:
69
- return "Error: Please upload an image to proceed.", "Pending", "", "", 0
70
-
71
- img = Image.open(image)
72
- image_size_mb = os.path.getsize(image) / (1024 * 1024)
73
- if image_size_mb > 20:
74
- return "Error: Image size exceeds 20MB.", "Failure", "", "", 0
75
- if not str(image).lower().endswith(('.jpg', '.jpeg', '.png')):
76
- return "Error: Only JPG/PNG images are supported.", "Failure", "", "", 0
77
-
78
- # Save image to public folder temporarily before uploading to Salesforce
79
- upload_dir = "public_uploads"
80
- os.makedirs(upload_dir, exist_ok=True)
81
- unique_id = datetime.now().strftime("%Y%m%d%H%M%S")
82
- image_filename = f"{unique_id}_{os.path.basename(image)}"
83
- saved_image_path = os.path.join(upload_dir, image_filename)
84
- shutil.copy(image, saved_image_path)
85
-
86
- # Convert image to base64 before uploading to Salesforce
87
- with open(saved_image_path, 'rb') as image_file:
88
- image_data = base64.b64encode(image_file.read()).decode('utf-8')
 
 
 
 
 
 
 
 
 
 
89
 
90
- # Create the ContentVersion record in Salesforce
91
- content_version = {
92
- 'Title': image_filename,
93
- 'PathOnClient': saved_image_path,
94
- 'VersionData': image_data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  }
 
96
 
97
- # Upload the file to Salesforce
98
- try:
99
- content_version_result = sf.ContentVersion.create(content_version)
100
- content_version_id = content_version_result['id']
101
- file_url = f"https://sathkruthatechsolutionspri8-dev-ed.develop.lightning.force.com/{content_version_id}"
102
- except Exception as e:
103
- return f"Error: Failed to upload image to Salesforce - {str(e)}", "Failure", "", "", 0
104
-
105
- # AI-based milestone and completion prediction
106
- milestone, percent_complete, confidence_score = mock_ai_model(img)
107
-
108
- # Detailed Completion Breakdown (based on detected milestone)
109
  completion_details = {
110
  "Planning": {
111
  "completed": [
@@ -159,9 +160,8 @@ def process_image(image, project_name):
159
  }
160
  }
161
 
162
- # Format the completed and not completed tasks as HTML for collapsible sections
163
- completed_tasks = completion_details[milestone]["completed"]
164
- not_completed_tasks = completion_details[milestone]["not_completed"]
165
 
166
  completed_html = "".join([f'<li style="color: green;">✔ {task}</li>' for task in completed_tasks])
167
  not_completed_html = "".join([f'<li style="color: red;">✘ {task}</li>' for task in not_completed_tasks])
@@ -173,26 +173,21 @@ def process_image(image, project_name):
173
  <div style="display: flex; justify-content: space-around; margin-bottom: 20px;">
174
  <div style="text-align: center;">
175
  <h3 style="color: #34495e;">Detected Milestone</h3>
176
- <p style="font-size: 18px; font-weight: bold;">{milestone}</p>
177
  </div>
178
  <div style="text-align: center;">
179
  <h3 style="color: #34495e;">Completion</h3>
180
  <progress value="{percent_complete}" max="100" style="width: 200px; height: 20px;"></progress>
181
  <p>{percent_complete}%</p>
182
  </div>
183
- <div style="text-align: center;">
184
- <h3 style="color: #34495e;">Confidence Score</h3>
185
- <p style="font-size: 18px; font-weight: bold;">{confidence_score * 100}%</p>
186
- <small>The AI is {confidence_score * 100}% confident that this image represents the {milestone} stage.</small>
187
- </div>
188
  </div>
189
 
190
  <h3 style="color: #2c3e50;">Milestone Timeline</h3>
191
  <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
192
- <span style="color: {'#2ecc71' if milestone == 'Planning' else '#bdc3c7'};">Planning</span>
193
- <span style="color: {'#2ecc71' if milestone == 'Foundation' else '#bdc3c7'};">Foundation</span>
194
- <span style="color: {'#2ecc71' if milestone == 'Walls Erected' else '#bdc3c7'};">Walls Erected</span>
195
- <span style="color: {'#2ecc71' if milestone == 'Completed' else '#bdc3c7'};">Completed</span>
196
  </div>
197
 
198
  <details style="margin-bottom: 20px;">
@@ -215,14 +210,14 @@ def process_image(image, project_name):
215
  now = datetime.now(local_timezone)
216
  local_time = now.strftime("%Y-%m-%dT%H:%M:%S") + now.strftime("%z")[:-2] + ":" + now.strftime("%z")[-2:]
217
 
218
- # Create the Salesforce record
219
  record = {
220
  "Name__c": project_name,
221
- "Current_Milestone__c": milestone,
222
  "Completion_Percentage__c": percent_complete,
223
  "Last_Updated_On__c": local_time,
224
  "Upload_Status__c": "Success",
225
- "Comments__c": f"{milestone} with {confidence_score*100}% confidence",
226
  "Last_Updated_Image__c": file_url
227
  }
228
 
@@ -231,7 +226,7 @@ def process_image(image, project_name):
231
  except Exception as e:
232
  return f"Error: Failed to update Salesforce - {str(e)}", "Failure", "", "", 0
233
 
234
- return result_html, "Success", milestone, f"Confidence Score: {confidence_score}", f"{percent_complete}%"
235
 
236
  except Exception as e:
237
  return f"Error: {str(e)}", "Failure", "", "", "0%"
@@ -290,14 +285,14 @@ with gr.Blocks(css="""
290
  """) as demo:
291
  gr.Markdown("<h1 class='title'>Construction Progress Analyzer</h1>")
292
  with gr.Row():
293
- image_input = gr.Image(type="filepath", label="Upload Construction Site Photo (JPG/PNG, ≤ 20MB)")
294
  project_name_input = gr.Textbox(label="Project Name (Required)", placeholder="e.g. Project_12345")
295
 
296
  submit_button = gr.Button("Process Image")
297
  output_html = gr.HTML(label="Result") # Changed to HTML for richer output
298
  upload_status = gr.Textbox(label="Upload Status")
299
  milestone = gr.Textbox(label="Detected Milestone")
300
- confidence = gr.Textbox(label="Confidence Score")
301
  progress = gr.Textbox(label="Completion Percentage", interactive=False)
302
 
303
  submit_button.click(
 
32
  raise
33
 
34
  # Valid milestones
35
+ VALID_MILESTONES = ["Planning", "Foundation", "Walls Erected", "Completed"]
36
 
37
  # Adjust the timezone to your local timezone
38
  local_timezone = pytz.timezone("Asia/Kolkata")
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  # Image processing and Salesforce upload
41
+ def process_image(images, project_name):
42
  try:
43
+ if not images or not isinstance(images, list):
44
+ return "Error: Please upload at least one image to proceed.", "Pending", "", "", 0
45
+
46
+ # Process each image
47
+ milestones = []
48
+ for image in images:
49
+ img = Image.open(image)
50
+ image_size_mb = os.path.getsize(image) / (1024 * 1024)
51
+ if image_size_mb > 20:
52
+ return "Error: One or more images exceed 20MB.", "Failure", "", "", 0
53
+ if not str(image).lower().endswith(('.jpg', '.jpeg', '.png')):
54
+ return "Error: Only JPG/PNG images are supported.", "Failure", "", "", 0
55
+
56
+ # Save image to public folder temporarily before uploading to Salesforce
57
+ upload_dir = "public_uploads"
58
+ os.makedirs(upload_dir, exist_ok=True)
59
+ unique_id = datetime.now().strftime("%Y%m%d%H%M%S")
60
+ image_filename = f"{unique_id}_{os.path.basename(image)}"
61
+ saved_image_path = os.path.join(upload_dir, image_filename)
62
+ shutil.copy(image, saved_image_path)
63
+
64
+ # Convert image to base64 before uploading to Salesforce
65
+ with open(saved_image_path, 'rb') as image_file:
66
+ image_data = base64.b64encode(image_file.read()).decode('utf-8')
67
+
68
+ # Create the ContentVersion record in Salesforce
69
+ content_version = {
70
+ 'Title': image_filename,
71
+ 'PathOnClient': saved_image_path,
72
+ 'VersionData': image_data
73
+ }
74
 
75
+ # Upload the file to Salesforce
76
+ try:
77
+ content_version_result = sf.ContentVersion.create(content_version)
78
+ content_version_id = content_version_result['id']
79
+ file_url = f"https://sathkruthatechsolutionspri8-dev-ed.develop.lightning.force.com/{content_version_id}"
80
+ except Exception as e:
81
+ return f"Error: Failed to upload image to Salesforce - {str(e)}", "Failure", "", "", 0
82
+
83
+ # Mock AI model to detect milestone based on image content
84
+ img_bytes = img.tobytes()
85
+ img_hash = int(hashlib.sha256(img_bytes).hexdigest(), 16)
86
+ milestone_index = img_hash % len(VALID_MILESTONES)
87
+ milestone = VALID_MILESTONES[milestone_index]
88
+
89
+ # Adjust milestone detection based on internal/external features
90
+ if milestone == "Walls Erected" and any("interior" in img_text.lower() for img_text in [img.filename] if img_text):
91
+ # Check for visible internal works like electrical/plumbing
92
+ if any(keyword in str(img).lower() for keyword in ["electrical", "plumbing", "wiring", "pipes"]):
93
+ milestone = "Completed" # Upgrade to Completed if internal works are detected
94
+ else:
95
+ milestone = "Walls Erected" # Retain if no internal works visible
96
+
97
+ milestones.append(milestone)
98
+
99
+ # Determine overall milestone (most advanced detected)
100
+ final_milestone = max(set(milestones), key=milestones.count) if milestones else "Planning"
101
+ milestone_completion_map = {
102
+ "Planning": 10,
103
+ "Foundation": 30,
104
+ "Walls Erected": 50,
105
+ "Completed": 100,
106
  }
107
+ percent_complete = milestone_completion_map.get(final_milestone, 0)
108
 
109
+ # Detailed Completion Breakdown based on final milestone
 
 
 
 
 
 
 
 
 
 
 
110
  completion_details = {
111
  "Planning": {
112
  "completed": [
 
160
  }
161
  }
162
 
163
+ completed_tasks = completion_details[final_milestone]["completed"]
164
+ not_completed_tasks = completion_details[final_milestone]["not_completed"]
 
165
 
166
  completed_html = "".join([f'<li style="color: green;">✔ {task}</li>' for task in completed_tasks])
167
  not_completed_html = "".join([f'<li style="color: red;">✘ {task}</li>' for task in not_completed_tasks])
 
173
  <div style="display: flex; justify-content: space-around; margin-bottom: 20px;">
174
  <div style="text-align: center;">
175
  <h3 style="color: #34495e;">Detected Milestone</h3>
176
+ <p style="font-size: 18px; font-weight: bold;">{final_milestone}</p>
177
  </div>
178
  <div style="text-align: center;">
179
  <h3 style="color: #34495e;">Completion</h3>
180
  <progress value="{percent_complete}" max="100" style="width: 200px; height: 20px;"></progress>
181
  <p>{percent_complete}%</p>
182
  </div>
 
 
 
 
 
183
  </div>
184
 
185
  <h3 style="color: #2c3e50;">Milestone Timeline</h3>
186
  <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
187
+ <span style="color: {'#2ecc71' if final_milestone == 'Planning' else '#bdc3c7'};">Planning</span>
188
+ <span style="color: {'#2ecc71' if final_milestone == 'Foundation' else '#bdc3c7'};">Foundation</span>
189
+ <span style="color: {'#2ecc71' if final_milestone == 'Walls Erected' else '#bdc3c7'};">Walls Erected</span>
190
+ <span style="color: {'#2ecc71' if final_milestone == 'Completed' else '#bdc3c7'};">Completed</span>
191
  </div>
192
 
193
  <details style="margin-bottom: 20px;">
 
210
  now = datetime.now(local_timezone)
211
  local_time = now.strftime("%Y-%m-%dT%H:%M:%S") + now.strftime("%z")[:-2] + ":" + now.strftime("%z")[-2:]
212
 
213
+ # Create the Salesforce record (removing confidence score)
214
  record = {
215
  "Name__c": project_name,
216
+ "Current_Milestone__c": final_milestone,
217
  "Completion_Percentage__c": percent_complete,
218
  "Last_Updated_On__c": local_time,
219
  "Upload_Status__c": "Success",
220
+ "Comments__c": f"{final_milestone}",
221
  "Last_Updated_Image__c": file_url
222
  }
223
 
 
226
  except Exception as e:
227
  return f"Error: Failed to update Salesforce - {str(e)}", "Failure", "", "", 0
228
 
229
+ return result_html, "Success", final_milestone, "", f"{percent_complete}%"
230
 
231
  except Exception as e:
232
  return f"Error: {str(e)}", "Failure", "", "", "0%"
 
285
  """) as demo:
286
  gr.Markdown("<h1 class='title'>Construction Progress Analyzer</h1>")
287
  with gr.Row():
288
+ image_input = gr.Image(type="filepath", label="Upload Construction Site Photos (JPG/PNG, ≤ 20MB)", file_count="multiple")
289
  project_name_input = gr.Textbox(label="Project Name (Required)", placeholder="e.g. Project_12345")
290
 
291
  submit_button = gr.Button("Process Image")
292
  output_html = gr.HTML(label="Result") # Changed to HTML for richer output
293
  upload_status = gr.Textbox(label="Upload Status")
294
  milestone = gr.Textbox(label="Detected Milestone")
295
+ confidence = gr.Textbox(label="Confidence Score") # Kept for compatibility, but unused
296
  progress = gr.Textbox(label="Completion Percentage", interactive=False)
297
 
298
  submit_button.click(