PrashanthB461 commited on
Commit
f99be17
·
verified ·
1 Parent(s): 238b4a9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1 -149
app.py CHANGED
@@ -132,154 +132,6 @@ def calculate_iou(box1, box2):
132
 
133
  return intersection / union if union > 0 else 0
134
 
135
- # ==========================
136
- # Salesforce Integration (unchanged)
137
- # ==========================
138
- @retry(stop_max_attempt_number=3, wait_fixed=2000)
139
- def connect_to_salesforce():
140
- try:
141
- sf = Salesforce(**CONFIG["SF_CREDENTIALS"])
142
- logger.info("Connected to Salesforce")
143
- sf.describe()
144
- return sf
145
- except Exception as e:
146
- logger.error(f"Salesforce connection failed: {e}")
147
- raise
148
-
149
- def generate_violation_pdf(violations, score):
150
- try:
151
- pdf_filename = f"violations_{int(time.time())}.pdf"
152
- pdf_path = os.path.join(CONFIG["OUTPUT_DIR"], pdf_filename)
153
- pdf_file = BytesIO()
154
- c = canvas.Canvas(pdf_file, pagesize=letter)
155
- c.setFont("Helvetica", 12)
156
- c.drawString(1 * inch, 10 * inch, "Worksite Safety Violation Report")
157
- c.setFont("Helvetica", 10)
158
-
159
- y_position = 9.5 * inch
160
- report_data = {
161
- "Compliance Score": f"{score}%",
162
- "Violations Found": len(violations),
163
- "Timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
164
- }
165
- for key, value in report_data.items():
166
- c.drawString(1 * inch, y_position, f"{key}: {value}")
167
- y_position -= 0.3 * inch
168
-
169
- y_position -= 0.3 * inch
170
- c.drawString(1 * inch, y_position, "Violation Details:")
171
- y_position -= 0.3 * inch
172
- if not violations:
173
- c.drawString(1 * inch, y_position, "No violations detected.")
174
- else:
175
- for v in violations:
176
- display_name = CONFIG["DISPLAY_NAMES"].get(v["violation"], v["violation"])
177
- text = f"{display_name} at {v['timestamp']:.2f}s (Confidence: {v['confidence']})"
178
- c.drawString(1 * inch, y_position, text)
179
- y_position -= 0.3 * inch
180
- if y_position < 1 * inch:
181
- c.showPage()
182
- c.setFont("Helvetica", 10)
183
- y_position = 10 * inch
184
-
185
- c.showPage()
186
- c.save()
187
- pdf_file.seek(0)
188
-
189
- with open(pdf_path, "wb") as f:
190
- f.write(pdf_file.getvalue())
191
- public_url = f"{CONFIG['PUBLIC_URL_BASE']}{pdf_filename}"
192
- logger.info(f"PDF generated: {public_url}")
193
- return pdf_path, public_url, pdf_file
194
- except Exception as e:
195
- logger.error(f"Error generating PDF: {e}")
196
- return "", "", None
197
-
198
- def upload_pdf_to_salesforce(sf, pdf_file, report_id):
199
- try:
200
- if not pdf_file:
201
- logger.error("No PDF file provided for upload")
202
- return ""
203
- encoded_pdf = base64.b64encode(pdf_file.getvalue()).decode('utf-8')
204
- content_version_data = {
205
- "Title": f"Safety_Violation_Report_{int(time.time())}",
206
- "PathOnClient": f"safety_violation_{int(time.time())}.pdf",
207
- "VersionData": encoded_pdf,
208
- "FirstPublishLocationId": report_id
209
- }
210
- content_version = sf.ContentVersion.create(content_version_data)
211
- result = sf.query(f"SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id = '{content_version['id']}'")
212
- if not result['records']:
213
- logger.error("Failed to retrieve ContentVersion")
214
- return ""
215
- file_url = f"https://{sf.sf_instance}/sfc/servlet.shepherd/version/download/{content_version['id']}"
216
- logger.info(f"PDF uploaded to Salesforce: {file_url}")
217
- return file_url
218
- except Exception as e:
219
- logger.error(f"Error uploading PDF to Salesforce: {e}")
220
- return ""
221
-
222
- def push_report_to_salesforce(violations, score, pdf_path, pdf_file):
223
- try:
224
- sf = connect_to_salesforce()
225
- violations_text = "\n".join(
226
- f"{CONFIG['DISPLAY_NAMES'].get(v['violation'], v['violation'])} at {v['timestamp']:.2f}s (Confidence: {v['confidence']})"
227
- for v in violations
228
- ) or "No violations detected."
229
- pdf_url = f"{CONFIG['PUBLIC_URL_BASE']}{os.path.basename(pdf_path)}" if pdf_path else ""
230
-
231
- record_data = {
232
- "Compliance_Score__c": score,
233
- "Violations_Found__c": len(violations),
234
- "Violations_Details__c": violations_text,
235
- "Status__c": "Pending",
236
- "PDF_Report_URL__c": pdf_url
237
- }
238
- logger.info(f"Creating Salesforce record with data: {record_data}")
239
- try:
240
- record = sf.Safety_Video_Report__c.create(record_data)
241
- logger.info(f"Created Safety_Video_Report__c record: {record['id']}")
242
- except Exception as e:
243
- logger.error(f"Failed to create Safety_Video_Report__c: {e}")
244
- record = sf.Account.create({"Name": f"Safety_Report_{int(time.time())}"})
245
- logger.warning(f"Fell back to Account record: {record['id']}")
246
- record_id = record["id"]
247
-
248
- if pdf_file:
249
- uploaded_url = upload_pdf_to_salesforce(sf, pdf_file, record_id)
250
- if uploaded_url:
251
- try:
252
- sf.Safety_Video_Report__c.update(record_id, {"PDF_Report_URL__c": uploaded_url})
253
- logger.info(f"Updated record {record_id} with PDF URL: {uploaded_url}")
254
- except Exception as e:
255
- logger.error(f"Failed to update Safety_Video_Report__c: {e}")
256
- sf.Account.update(record_id, {"Description": uploaded_url})
257
- logger.info(f"Updated Account record {record_id} with PDF URL")
258
- pdf_url = uploaded_url
259
-
260
- return record_id, pdf_url
261
- except Exception as e:
262
- logger.error(f"Salesforce record creation failed: {e}", exc_info=True)
263
- return None, ""
264
-
265
- def calculate_safety_score(violations):
266
- penalties = {
267
- "no_helmet": 25,
268
- "no_harness": 30,
269
- "unsafe_posture": 20,
270
- "unsafe_zone": 35,
271
- "improper_tool_use": 25
272
- }
273
- # Count unique violations per worker
274
- unique_violations = set()
275
- for v in violations:
276
- key = (v["worker_id"], v["violation"])
277
- unique_violations.add(key)
278
-
279
- total_penalty = sum(penalties.get(violation, 0) for _, violation in unique_violations)
280
- score = 100 - total_penalty
281
- return max(score, 0)
282
-
283
  # ==========================
284
  # Enhanced Video Processing
285
  # ==========================
@@ -531,4 +383,4 @@ interface = gr.Interface(
531
 
532
  if __name__ == "__main__":
533
  logger.info("Launching Enhanced Safety Analyzer App...")
534
- interface.launch()
 
132
 
133
  return intersection / union if union > 0 else 0
134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  # ==========================
136
  # Enhanced Video Processing
137
  # ==========================
 
383
 
384
  if __name__ == "__main__":
385
  logger.info("Launching Enhanced Safety Analyzer App...")
386
+ interface.launch()