Rekham1110 commited on
Commit
0410192
·
verified ·
1 Parent(s): 54e0609

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +11 -26
app.py CHANGED
@@ -6,7 +6,6 @@ from simple_salesforce import Salesforce
6
  from datetime import datetime
7
  import hashlib
8
  import shutil
9
- import base64
10
 
11
  # Load environment variables
12
  load_dotenv()
@@ -59,7 +58,7 @@ def mock_ai_model(image):
59
  return milestone, completion_percent, confidence_score
60
 
61
  # Image processing and Salesforce upload
62
- def process_image(image, project_name, sobject_id):
63
  try:
64
  if image is None:
65
  return "Error: Please upload an image to proceed.", "Pending", "", "", 0
@@ -71,7 +70,7 @@ def process_image(image, project_name, sobject_id):
71
  if not str(image).lower().endswith(('.jpg', '.jpeg', '.png')):
72
  return "Error: Only JPG/PNG images are supported.", "Failure", "", "", 0
73
 
74
- # Save image to a temporary file
75
  upload_dir = "public_uploads"
76
  os.makedirs(upload_dir, exist_ok=True)
77
  unique_id = datetime.now().strftime("%Y%m%d%H%M%S")
@@ -79,26 +78,14 @@ def process_image(image, project_name, sobject_id):
79
  saved_image_path = os.path.join(upload_dir, image_filename)
80
  shutil.copy(image, saved_image_path)
81
 
82
- # Open the image file and encode it as base64
83
- with open(saved_image_path, "rb") as file:
84
- encoded_image = base64.b64encode(file.read()).decode('utf-8')
 
 
85
 
86
- # Upload to Salesforce as a ContentVersion
87
- try:
88
- content_version_data = {
89
- 'Title': image_filename,
90
- 'PathOnClient': image_filename,
91
- 'VersionData': encoded_image, # Using the base64-encoded image data
92
- 'FirstPublishLocationId': sobject_id, # Use the actual Salesforce object ID here
93
- }
94
- content_version = sf.ContentVersion.create(content_version_data)
95
-
96
- # Generate download URL for the uploaded image
97
- file_url = f"https://{sf.sf_instance}/sfc/servlet.shepherd/version/download/{content_version['id']}"
98
- except Exception as e:
99
- return f"Error: Failed to upload image to Salesforce - {str(e)}", "Failure", "", "", 0
100
 
101
- # AI prediction
102
  milestone, percent_complete, confidence_score = mock_ai_model(img)
103
 
104
  record = {
@@ -108,10 +95,9 @@ def process_image(image, project_name, sobject_id):
108
  "Last_Updated_On__c": datetime.now().isoformat(),
109
  "Upload_Status__c": "Success",
110
  "Comments__c": f"AI Prediction: {milestone} with {confidence_score*100}% confidence",
111
- "Last_Updated_Image__c": file_url
112
  }
113
 
114
- # Insert record into Salesforce
115
  try:
116
  sf.Construction__c.create(record)
117
  except Exception as e:
@@ -134,7 +120,6 @@ with gr.Blocks(css=".gradio-container {background-color: #f0f4f8; font-family: A
134
  with gr.Row():
135
  image_input = gr.Image(type="filepath", label="Upload Construction Site Photo (JPG/PNG, ≤ 20MB)")
136
  project_name_input = gr.Textbox(label="Project Name (Required)", placeholder="e.g. Project_12345")
137
- sobject_id_input = gr.Textbox(label="Salesforce Record ID (Required)", placeholder="Enter Salesforce Record ID here")
138
 
139
  submit_button = gr.Button("Process Image")
140
  output_text = gr.Textbox(label="Result")
@@ -145,8 +130,8 @@ with gr.Blocks(css=".gradio-container {background-color: #f0f4f8; font-family: A
145
 
146
  submit_button.click(
147
  fn=process_image,
148
- inputs=[image_input, project_name_input, sobject_id_input],
149
  outputs=[output_text, upload_status, milestone, confidence, progress]
150
  )
151
 
152
- demo.launch(share=True)
 
6
  from datetime import datetime
7
  import hashlib
8
  import shutil
 
9
 
10
  # Load environment variables
11
  load_dotenv()
 
58
  return milestone, completion_percent, confidence_score
59
 
60
  # Image processing and Salesforce upload
61
+ def process_image(image, project_name):
62
  try:
63
  if image is None:
64
  return "Error: Please upload an image to proceed.", "Pending", "", "", 0
 
70
  if not str(image).lower().endswith(('.jpg', '.jpeg', '.png')):
71
  return "Error: Only JPG/PNG images are supported.", "Failure", "", "", 0
72
 
73
+ # Save image to public folder
74
  upload_dir = "public_uploads"
75
  os.makedirs(upload_dir, exist_ok=True)
76
  unique_id = datetime.now().strftime("%Y%m%d%H%M%S")
 
78
  saved_image_path = os.path.join(upload_dir, image_filename)
79
  shutil.copy(image, saved_image_path)
80
 
81
+ # Corrected public URL logic
82
+ if os.getenv("GRADIO_SERVER_NAME"):
83
+ public_url_base = f"https://{os.getenv('GRADIO_SERVER_NAME')}/file"
84
+ else:
85
+ public_url_base = "http://localhost:7860/file"
86
 
87
+ image_url = f"{public_url_base}/{upload_dir}/{image_filename}"
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
 
89
  milestone, percent_complete, confidence_score = mock_ai_model(img)
90
 
91
  record = {
 
95
  "Last_Updated_On__c": datetime.now().isoformat(),
96
  "Upload_Status__c": "Success",
97
  "Comments__c": f"AI Prediction: {milestone} with {confidence_score*100}% confidence",
98
+ "Last_Updated_Image__c": image_url
99
  }
100
 
 
101
  try:
102
  sf.Construction__c.create(record)
103
  except Exception as e:
 
120
  with gr.Row():
121
  image_input = gr.Image(type="filepath", label="Upload Construction Site Photo (JPG/PNG, ≤ 20MB)")
122
  project_name_input = gr.Textbox(label="Project Name (Required)", placeholder="e.g. Project_12345")
 
123
 
124
  submit_button = gr.Button("Process Image")
125
  output_text = gr.Textbox(label="Result")
 
130
 
131
  submit_button.click(
132
  fn=process_image,
133
+ inputs=[image_input, project_name_input],
134
  outputs=[output_text, upload_status, milestone, confidence, progress]
135
  )
136
 
137
+ demo.launch(share=True)