Zynaly commited on
Commit
b32255c
·
verified ·
1 Parent(s): 54c2eef

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -3
app.py CHANGED
@@ -75,7 +75,26 @@ def save_image(image, incident_type):
75
 
76
  # Function to create Freshdesk ticket
77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  def create_freshdesk_ticket(incident_type, confidence_score, img):
 
 
 
 
 
79
  # Save the image to the appropriate directory and get its local path
80
  image_url = None
81
  image_path = None
@@ -94,7 +113,7 @@ def create_freshdesk_ticket(incident_type, confidence_score, img):
94
  # Shortened subject
95
  subject = f"{incident_type} Detected - Confidence: {confidence_score*100:.1f}%"
96
 
97
- # Detailed description
98
  description = f"""
99
  {incident_type} is critical.
100
  Details:
@@ -105,12 +124,20 @@ Details:
105
  5. Incident Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
106
  """
107
 
 
108
  ticket_data = {
109
  "email": "safe.city@example.com",
110
  "subject": subject,
111
  "description": description,
112
  "priority": 4, # Urgent
113
- "status": 2 # Open
 
 
 
 
 
 
 
114
  }
115
 
116
  # Create ticket
@@ -136,7 +163,6 @@ Details:
136
  try:
137
  with open(image_path, 'rb') as f:
138
  files = {'attachments[]': (os.path.basename(image_path), f, 'image/jpeg')}
139
- # Do not set Content-Type header; let requests handle it
140
  attachment_response = requests.post(
141
  attachment_url,
142
  auth=(API_KEY, "X"),
@@ -151,10 +177,114 @@ Details:
151
  else:
152
  print(f"❌ Image file not found: {image_path}")
153
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  return f"Ticket created for {incident_type} with ID {ticket_id}"
155
  else:
156
  print(f"❌ Failed to create ticket: {response.status_code} - {response.text}")
157
  return f"Failed to create ticket for {incident_type}: {response.status_code} - {response.text}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  # Image inference function
159
  def detect_image(image):
160
  try:
 
75
 
76
  # Function to create Freshdesk ticket
77
 
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
  def create_freshdesk_ticket(incident_type, confidence_score, img):
93
+ import os
94
+ import json
95
+ import requests
96
+ from datetime import datetime
97
+
98
  # Save the image to the appropriate directory and get its local path
99
  image_url = None
100
  image_path = None
 
113
  # Shortened subject
114
  subject = f"{incident_type} Detected - Confidence: {confidence_score*100:.1f}%"
115
 
116
+ # Detailed description with enforced data
117
  description = f"""
118
  {incident_type} is critical.
119
  Details:
 
124
  5. Incident Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
125
  """
126
 
127
+ # Enforce image_urls and created_at in ticket data
128
  ticket_data = {
129
  "email": "safe.city@example.com",
130
  "subject": subject,
131
  "description": description,
132
  "priority": 4, # Urgent
133
+ "status": 2, # Open
134
+ "phone_number": "923013225853",
135
+ "incident_type": incident_type,
136
+ "address": "123 Main Street, Lahore",
137
+ "confidence_score": confidence_score,
138
+ "image_urls": [image_url] if image_url else ["https://example.com/roboi.jpg"], # Enforced with fallback
139
+ "created_at": datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ'), # Enforced current timestamp
140
+ "extraction_failed": False
141
  }
142
 
143
  # Create ticket
 
163
  try:
164
  with open(image_path, 'rb') as f:
165
  files = {'attachments[]': (os.path.basename(image_path), f, 'image/jpeg')}
 
166
  attachment_response = requests.post(
167
  attachment_url,
168
  auth=(API_KEY, "X"),
 
177
  else:
178
  print(f"❌ Image file not found: {image_path}")
179
 
180
+ # Update ticket with enforced fields if API rejects them
181
+ if "image_urls" not in ticket or "created_at" not in ticket:
182
+ update_data = {}
183
+ if "image_urls" not in ticket:
184
+ update_data["image_urls"] = [image_url] if image_url else ["https://example.com/roboi.jpg"]
185
+ if "created_at" not in ticket:
186
+ update_data["created_at"] = datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')
187
+ if update_data:
188
+ update_url = f"https://{FRESHDESK_DOMAIN}/api/v2/tickets/{ticket_id}"
189
+ update_response = requests.put(
190
+ update_url,
191
+ auth=(API_KEY, "X"),
192
+ headers=headers,
193
+ data=json.dumps(update_data)
194
+ )
195
+ if update_response.status_code == 200:
196
+ print(f"✅ Updated ticket {ticket_id} with missing fields")
197
+ else:
198
+ print(f"⚠️ Failed to update ticket {ticket_id} with fields: {update_response.status_code} - {update_response.text}")
199
+
200
  return f"Ticket created for {incident_type} with ID {ticket_id}"
201
  else:
202
  print(f"❌ Failed to create ticket: {response.status_code} - {response.text}")
203
  return f"Failed to create ticket for {incident_type}: {response.status_code} - {response.text}"
204
+
205
+
206
+
207
+
208
+ # def create_freshdesk_ticket(incident_type, confidence_score, img):
209
+ # # Save the image to the appropriate directory and get its local path
210
+ # image_url = None
211
+ # image_path = None
212
+ # if incident_type.lower() == "fire incident":
213
+ # image_url = save_image(img, "fire")
214
+ # image_path = os.path.join(MEDIA_DIR, "fire", os.path.basename(image_url.split("/")[-1]))
215
+ # elif incident_type.lower() == "accident incident":
216
+ # image_url = save_image(img, "accidents")
217
+ # image_path = os.path.join(MEDIA_DIR, "accidents", os.path.basename(image_url.split("/")[-1]))
218
+ # elif incident_type.lower() == "fire and accident incident":
219
+ # fire_url = save_image(img, "fire")
220
+ # accident_url = save_image(img, "accidents")
221
+ # image_url = fire_url or accident_url
222
+ # image_path = os.path.join(MEDIA_DIR, "fire" if fire_url else "accidents", os.path.basename(image_url.split("/")[-1]))
223
+
224
+ # # Shortened subject
225
+ # subject = f"{incident_type} Detected - Confidence: {confidence_score*100:.1f}%"
226
+
227
+ # # Detailed description
228
+ # description = f"""
229
+ # {incident_type} is critical.
230
+ # Details:
231
+ # 1. Address: 123 Main Street, Lahore
232
+ # 2. Phone: 923013225853
233
+ # 3. Confidence Score: {confidence_score*100:.1f}%
234
+ # 4. Image URL: {image_url or 'https://example.com/roboi.jpg'}
235
+ # 5. Incident Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
236
+ # """
237
+
238
+ # ticket_data = {
239
+ # "email": "safe.city@example.com",
240
+ # "subject": subject,
241
+ # "description": description,
242
+ # "priority": 4, # Urgent
243
+ # "status": 2 # Open
244
+ # }
245
+
246
+ # # Create ticket
247
+ # url = f"https://{FRESHDESK_DOMAIN}/api/v2/tickets"
248
+ # headers = {"Content-Type": "application/json"}
249
+
250
+ # response = requests.post(
251
+ # url,
252
+ # auth=(API_KEY, "X"),
253
+ # headers=headers,
254
+ # data=json.dumps(ticket_data)
255
+ # )
256
+
257
+ # if response.status_code == 201:
258
+ # ticket = response.json()
259
+ # ticket_id = ticket.get('id')
260
+ # print(f"✅ Ticket created successfully: Ticket ID {ticket_id}")
261
+ # print(json.dumps(ticket, indent=2))
262
+
263
+ # # Attach image to ticket if image_path exists
264
+ # if image_path and os.path.exists(image_path):
265
+ # attachment_url = f"https://{FRESHDESK_DOMAIN}/api/v2/tickets/{ticket_id}/attachments"
266
+ # try:
267
+ # with open(image_path, 'rb') as f:
268
+ # files = {'attachments[]': (os.path.basename(image_path), f, 'image/jpeg')}
269
+ # # Do not set Content-Type header; let requests handle it
270
+ # attachment_response = requests.post(
271
+ # attachment_url,
272
+ # auth=(API_KEY, "X"),
273
+ # files=files
274
+ # )
275
+ # if attachment_response.status_code == 201:
276
+ # print(f"✅ Image attached to ticket {ticket_id}")
277
+ # else:
278
+ # print(f"❌ Failed to attach image: {attachment_response.status_code} - {attachment_response.text}")
279
+ # except Exception as e:
280
+ # print(f"❌ Error accessing image file {image_path}: {str(e)}")
281
+ # else:
282
+ # print(f"❌ Image file not found: {image_path}")
283
+
284
+ # return f"Ticket created for {incident_type} with ID {ticket_id}"
285
+ # else:
286
+ # print(f"❌ Failed to create ticket: {response.status_code} - {response.text}")
287
+ # return f"Failed to create ticket for {incident_type}: {response.status_code} - {response.text}"
288
  # Image inference function
289
  def detect_image(image):
290
  try: