Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
from transformers import
|
| 2 |
from PIL import Image
|
| 3 |
import gradio as gr
|
| 4 |
import torch
|
|
@@ -29,27 +29,24 @@ except Exception as e:
|
|
| 29 |
sf = None
|
| 30 |
print(f"Failed to connect to Salesforce: {str(e)}")
|
| 31 |
|
| 32 |
-
# Load
|
| 33 |
-
processor =
|
| 34 |
-
model =
|
| 35 |
model.eval()
|
| 36 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 37 |
model.to(device)
|
| 38 |
|
| 39 |
-
# Inference function to
|
| 40 |
def generate_captions_from_image(image):
|
| 41 |
if image.mode != "RGB":
|
| 42 |
image = image.convert("RGB")
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
caption = processor.decode(output[0], skip_special_tokens=True)
|
| 51 |
-
|
| 52 |
-
return caption
|
| 53 |
|
| 54 |
# Function to save DPR text to a PDF file
|
| 55 |
def save_dpr_to_pdf(dpr_text, image_paths, captions, filename):
|
|
@@ -92,16 +89,14 @@ def save_dpr_to_pdf(dpr_text, image_paths, captions, filename):
|
|
| 92 |
else:
|
| 93 |
flowables.append(Spacer(1, 12))
|
| 94 |
|
| 95 |
-
# Add images and captions in the correct order
|
| 96 |
for img_path, caption in zip(image_paths, captions):
|
| 97 |
try:
|
| 98 |
-
# Add image first
|
| 99 |
img = PDFImage(img_path, width=200, height=150) # Adjust image size if needed
|
| 100 |
flowables.append(img)
|
| 101 |
-
# Add description below the image
|
| 102 |
description = f"Description: {caption}"
|
| 103 |
flowables.append(Paragraph(description, body_style))
|
| 104 |
-
flowables.append(Spacer(1, 12))
|
| 105 |
except Exception as e:
|
| 106 |
flowables.append(Paragraph(f"Error loading image: {str(e)}", body_style))
|
| 107 |
|
|
@@ -111,18 +106,15 @@ def save_dpr_to_pdf(dpr_text, image_paths, captions, filename):
|
|
| 111 |
except Exception as e:
|
| 112 |
return f"Error saving PDF: {str(e)}", None
|
| 113 |
|
| 114 |
-
# Function to upload
|
| 115 |
def upload_file_to_salesforce(file_path, filename, sf_connection, file_type):
|
| 116 |
try:
|
| 117 |
-
# Read file content and encode in base64
|
| 118 |
with open(file_path, 'rb') as f:
|
| 119 |
file_content = f.read()
|
| 120 |
file_content_b64 = base64.b64encode(file_content).decode('utf-8')
|
| 121 |
|
| 122 |
-
# Set description based on file type
|
| 123 |
description = "Daily Progress Report PDF" if file_type == "pdf" else "Site Image"
|
| 124 |
|
| 125 |
-
# Create ContentVersion
|
| 126 |
content_version = sf_connection.ContentVersion.create({
|
| 127 |
'Title': filename,
|
| 128 |
'PathOnClient': filename,
|
|
@@ -130,78 +122,60 @@ def upload_file_to_salesforce(file_path, filename, sf_connection, file_type):
|
|
| 130 |
'Description': description
|
| 131 |
})
|
| 132 |
|
| 133 |
-
# Get ContentDocumentId
|
| 134 |
content_version_id = content_version['id']
|
| 135 |
content_document = sf_connection.query(
|
| 136 |
f"SELECT ContentDocumentId FROM ContentVersion WHERE Id = '{content_version_id}'"
|
| 137 |
)
|
| 138 |
content_document_id = content_document['records'][0]['ContentDocumentId']
|
| 139 |
|
| 140 |
-
# Generate a valid Salesforce URL for the ContentDocument
|
| 141 |
content_document_url = f"https://{sf_connection.sf_instance}/sfc/servlet.shepherd/version/download/{content_version_id}"
|
| 142 |
|
| 143 |
-
|
| 144 |
-
# Ensure the link is valid
|
| 145 |
return content_document_id, content_document_url, f"File {filename} uploaded successfully"
|
| 146 |
except Exception as e:
|
| 147 |
return None, None, f"Error uploading {filename} to Salesforce: {str(e)}"
|
| 148 |
|
| 149 |
-
#
|
| 150 |
def generate_dpr(files):
|
| 151 |
dpr_text = []
|
| 152 |
captions = []
|
| 153 |
image_paths = []
|
| 154 |
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 155 |
|
| 156 |
-
# Add header to the DPR
|
| 157 |
dpr_text.append(f"Daily Progress Report\nGenerated on: {current_time}\n")
|
| 158 |
|
| 159 |
-
# Process images in parallel for faster performance
|
| 160 |
with concurrent.futures.ThreadPoolExecutor() as executor:
|
| 161 |
results = list(executor.map(lambda file: generate_captions_from_image(Image.open(file.name)), files))
|
| 162 |
|
| 163 |
for i, file in enumerate(files):
|
| 164 |
caption = results[i]
|
| 165 |
captions.append(caption)
|
| 166 |
-
|
| 167 |
-
# Generate DPR section for this image with dynamic caption
|
| 168 |
dpr_section = f"\nImage: {file.name}\nDescription: {caption}\n"
|
| 169 |
dpr_text.append(dpr_section)
|
| 170 |
-
|
| 171 |
-
# Save image path for embedding in the report
|
| 172 |
image_paths.append(file.name)
|
| 173 |
|
| 174 |
-
# Combine DPR text
|
| 175 |
dpr_output = "\n".join(dpr_text)
|
| 176 |
-
|
| 177 |
-
# Generate PDF filename with timestamp
|
| 178 |
pdf_filename = f"DPR_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.pdf"
|
| 179 |
|
| 180 |
-
# Save DPR text to PDF
|
| 181 |
pdf_result, pdf_filepath = save_dpr_to_pdf(dpr_output, image_paths, captions, pdf_filename)
|
| 182 |
|
| 183 |
salesforce_result = ""
|
| 184 |
pdf_content_document_id = None
|
| 185 |
pdf_url = None
|
| 186 |
-
image_content_document_ids = []
|
| 187 |
|
| 188 |
if sf and pdf_filepath:
|
| 189 |
try:
|
| 190 |
-
|
| 191 |
-
report_description = "; ".join(captions)[:255] # Concatenate captions, limit to 255 chars
|
| 192 |
dpr_record = sf.Daily_Progress_Reports__c.create({
|
| 193 |
-
'Detected_Activities__c': report_description
|
| 194 |
})
|
| 195 |
dpr_record_id = dpr_record['id']
|
| 196 |
salesforce_result += f"Created Daily_Progress_Reports__c record with ID: {dpr_record_id}\n"
|
| 197 |
|
| 198 |
-
# Upload PDF to Salesforce
|
| 199 |
pdf_content_document_id, pdf_url, pdf_upload_result = upload_file_to_salesforce(
|
| 200 |
pdf_filepath, pdf_filename, sf, "pdf"
|
| 201 |
)
|
| 202 |
salesforce_result += pdf_upload_result + "\n"
|
| 203 |
|
| 204 |
-
# Link PDF to DPR record
|
| 205 |
if pdf_content_document_id:
|
| 206 |
sf.ContentDocumentLink.create({
|
| 207 |
'ContentDocumentId': pdf_content_document_id,
|
|
@@ -209,33 +183,26 @@ def generate_dpr(files):
|
|
| 209 |
'ShareType': 'V'
|
| 210 |
})
|
| 211 |
|
| 212 |
-
# Update the DPR record with the PDF URL
|
| 213 |
if pdf_url:
|
| 214 |
sf.Daily_Progress_Reports__c.update(dpr_record_id, {
|
| 215 |
-
'PDF_URL__c': pdf_url
|
| 216 |
})
|
| 217 |
salesforce_result += f"Updated PDF URL for record ID {dpr_record_id}\n"
|
| 218 |
|
| 219 |
-
# Upload images to Salesforce and link them to DPR record
|
| 220 |
for file in files:
|
| 221 |
image_filename = os.path.basename(file.name)
|
| 222 |
image_content_document_id, image_url, image_upload_result = upload_file_to_salesforce(
|
| 223 |
file.name, image_filename, sf, "image"
|
| 224 |
)
|
| 225 |
-
|
| 226 |
if image_content_document_id:
|
| 227 |
-
# Link image to the Daily Progress Report record (DPR) using ContentDocumentLink
|
| 228 |
sf.ContentDocumentLink.create({
|
| 229 |
'ContentDocumentId': image_content_document_id,
|
| 230 |
-
'LinkedEntityId': dpr_record_id,
|
| 231 |
-
'ShareType': 'V'
|
| 232 |
})
|
| 233 |
-
|
| 234 |
-
# Now, update the DPR record with the ContentDocumentId in the Site_Images field (if it's a text or URL field)
|
| 235 |
sf.Daily_Progress_Reports__c.update(dpr_record_id, {
|
| 236 |
-
'Site_Images__c': image_content_document_id
|
| 237 |
})
|
| 238 |
-
|
| 239 |
salesforce_result += image_upload_result + "\n"
|
| 240 |
|
| 241 |
except Exception as e:
|
|
@@ -243,12 +210,11 @@ def generate_dpr(files):
|
|
| 243 |
else:
|
| 244 |
salesforce_result = "Salesforce connection not available or PDF generation failed.\n"
|
| 245 |
|
| 246 |
-
# Return DPR text, PDF file, and Salesforce upload status
|
| 247 |
return (
|
| 248 |
dpr_output + f"\n\n{pdf_result}\n\nSalesforce Upload Status:\n{salesforce_result}",
|
| 249 |
pdf_filepath
|
| 250 |
)
|
| 251 |
-
|
| 252 |
iface = gr.Interface(
|
| 253 |
fn=generate_dpr,
|
| 254 |
inputs=gr.Files(type="filepath", label="Upload Site Photos"),
|
|
|
|
| 1 |
+
from transformers import AutoProcessor, AutoModelForImageClassification
|
| 2 |
from PIL import Image
|
| 3 |
import gradio as gr
|
| 4 |
import torch
|
|
|
|
| 29 |
sf = None
|
| 30 |
print(f"Failed to connect to Salesforce: {str(e)}")
|
| 31 |
|
| 32 |
+
# Load ViT model and processor (generic ImageNet pretrained)
|
| 33 |
+
processor = AutoProcessor.from_pretrained("google/vit-base-patch16-224")
|
| 34 |
+
model = AutoModelForImageClassification.from_pretrained("google/vit-base-patch16-224")
|
| 35 |
model.eval()
|
| 36 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 37 |
model.to(device)
|
| 38 |
|
| 39 |
+
# Inference function to classify image and get predicted label
|
| 40 |
def generate_captions_from_image(image):
|
| 41 |
if image.mode != "RGB":
|
| 42 |
image = image.convert("RGB")
|
| 43 |
+
inputs = processor(images=image, return_tensors="pt").to(device)
|
| 44 |
+
with torch.no_grad():
|
| 45 |
+
outputs = model(**inputs)
|
| 46 |
+
logits = outputs.logits
|
| 47 |
+
predicted_class_idx = logits.argmax(-1).item()
|
| 48 |
+
predicted_label = model.config.id2label[predicted_class_idx]
|
| 49 |
+
return predicted_label
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
# Function to save DPR text to a PDF file
|
| 52 |
def save_dpr_to_pdf(dpr_text, image_paths, captions, filename):
|
|
|
|
| 89 |
else:
|
| 90 |
flowables.append(Spacer(1, 12))
|
| 91 |
|
| 92 |
+
# Add images and captions in the correct order
|
| 93 |
for img_path, caption in zip(image_paths, captions):
|
| 94 |
try:
|
|
|
|
| 95 |
img = PDFImage(img_path, width=200, height=150) # Adjust image size if needed
|
| 96 |
flowables.append(img)
|
|
|
|
| 97 |
description = f"Description: {caption}"
|
| 98 |
flowables.append(Paragraph(description, body_style))
|
| 99 |
+
flowables.append(Spacer(1, 12))
|
| 100 |
except Exception as e:
|
| 101 |
flowables.append(Paragraph(f"Error loading image: {str(e)}", body_style))
|
| 102 |
|
|
|
|
| 106 |
except Exception as e:
|
| 107 |
return f"Error saving PDF: {str(e)}", None
|
| 108 |
|
| 109 |
+
# Function to upload file to Salesforce as ContentVersion
|
| 110 |
def upload_file_to_salesforce(file_path, filename, sf_connection, file_type):
|
| 111 |
try:
|
|
|
|
| 112 |
with open(file_path, 'rb') as f:
|
| 113 |
file_content = f.read()
|
| 114 |
file_content_b64 = base64.b64encode(file_content).decode('utf-8')
|
| 115 |
|
|
|
|
| 116 |
description = "Daily Progress Report PDF" if file_type == "pdf" else "Site Image"
|
| 117 |
|
|
|
|
| 118 |
content_version = sf_connection.ContentVersion.create({
|
| 119 |
'Title': filename,
|
| 120 |
'PathOnClient': filename,
|
|
|
|
| 122 |
'Description': description
|
| 123 |
})
|
| 124 |
|
|
|
|
| 125 |
content_version_id = content_version['id']
|
| 126 |
content_document = sf_connection.query(
|
| 127 |
f"SELECT ContentDocumentId FROM ContentVersion WHERE Id = '{content_version_id}'"
|
| 128 |
)
|
| 129 |
content_document_id = content_document['records'][0]['ContentDocumentId']
|
| 130 |
|
|
|
|
| 131 |
content_document_url = f"https://{sf_connection.sf_instance}/sfc/servlet.shepherd/version/download/{content_version_id}"
|
| 132 |
|
|
|
|
|
|
|
| 133 |
return content_document_id, content_document_url, f"File {filename} uploaded successfully"
|
| 134 |
except Exception as e:
|
| 135 |
return None, None, f"Error uploading {filename} to Salesforce: {str(e)}"
|
| 136 |
|
| 137 |
+
# Generate DPR, save PDF, upload to Salesforce
|
| 138 |
def generate_dpr(files):
|
| 139 |
dpr_text = []
|
| 140 |
captions = []
|
| 141 |
image_paths = []
|
| 142 |
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 143 |
|
|
|
|
| 144 |
dpr_text.append(f"Daily Progress Report\nGenerated on: {current_time}\n")
|
| 145 |
|
|
|
|
| 146 |
with concurrent.futures.ThreadPoolExecutor() as executor:
|
| 147 |
results = list(executor.map(lambda file: generate_captions_from_image(Image.open(file.name)), files))
|
| 148 |
|
| 149 |
for i, file in enumerate(files):
|
| 150 |
caption = results[i]
|
| 151 |
captions.append(caption)
|
|
|
|
|
|
|
| 152 |
dpr_section = f"\nImage: {file.name}\nDescription: {caption}\n"
|
| 153 |
dpr_text.append(dpr_section)
|
|
|
|
|
|
|
| 154 |
image_paths.append(file.name)
|
| 155 |
|
|
|
|
| 156 |
dpr_output = "\n".join(dpr_text)
|
|
|
|
|
|
|
| 157 |
pdf_filename = f"DPR_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.pdf"
|
| 158 |
|
|
|
|
| 159 |
pdf_result, pdf_filepath = save_dpr_to_pdf(dpr_output, image_paths, captions, pdf_filename)
|
| 160 |
|
| 161 |
salesforce_result = ""
|
| 162 |
pdf_content_document_id = None
|
| 163 |
pdf_url = None
|
|
|
|
| 164 |
|
| 165 |
if sf and pdf_filepath:
|
| 166 |
try:
|
| 167 |
+
report_description = "; ".join(captions)[:255]
|
|
|
|
| 168 |
dpr_record = sf.Daily_Progress_Reports__c.create({
|
| 169 |
+
'Detected_Activities__c': report_description
|
| 170 |
})
|
| 171 |
dpr_record_id = dpr_record['id']
|
| 172 |
salesforce_result += f"Created Daily_Progress_Reports__c record with ID: {dpr_record_id}\n"
|
| 173 |
|
|
|
|
| 174 |
pdf_content_document_id, pdf_url, pdf_upload_result = upload_file_to_salesforce(
|
| 175 |
pdf_filepath, pdf_filename, sf, "pdf"
|
| 176 |
)
|
| 177 |
salesforce_result += pdf_upload_result + "\n"
|
| 178 |
|
|
|
|
| 179 |
if pdf_content_document_id:
|
| 180 |
sf.ContentDocumentLink.create({
|
| 181 |
'ContentDocumentId': pdf_content_document_id,
|
|
|
|
| 183 |
'ShareType': 'V'
|
| 184 |
})
|
| 185 |
|
|
|
|
| 186 |
if pdf_url:
|
| 187 |
sf.Daily_Progress_Reports__c.update(dpr_record_id, {
|
| 188 |
+
'PDF_URL__c': pdf_url
|
| 189 |
})
|
| 190 |
salesforce_result += f"Updated PDF URL for record ID {dpr_record_id}\n"
|
| 191 |
|
|
|
|
| 192 |
for file in files:
|
| 193 |
image_filename = os.path.basename(file.name)
|
| 194 |
image_content_document_id, image_url, image_upload_result = upload_file_to_salesforce(
|
| 195 |
file.name, image_filename, sf, "image"
|
| 196 |
)
|
|
|
|
| 197 |
if image_content_document_id:
|
|
|
|
| 198 |
sf.ContentDocumentLink.create({
|
| 199 |
'ContentDocumentId': image_content_document_id,
|
| 200 |
+
'LinkedEntityId': dpr_record_id,
|
| 201 |
+
'ShareType': 'V'
|
| 202 |
})
|
|
|
|
|
|
|
| 203 |
sf.Daily_Progress_Reports__c.update(dpr_record_id, {
|
| 204 |
+
'Site_Images__c': image_content_document_id
|
| 205 |
})
|
|
|
|
| 206 |
salesforce_result += image_upload_result + "\n"
|
| 207 |
|
| 208 |
except Exception as e:
|
|
|
|
| 210 |
else:
|
| 211 |
salesforce_result = "Salesforce connection not available or PDF generation failed.\n"
|
| 212 |
|
|
|
|
| 213 |
return (
|
| 214 |
dpr_output + f"\n\n{pdf_result}\n\nSalesforce Upload Status:\n{salesforce_result}",
|
| 215 |
pdf_filepath
|
| 216 |
)
|
| 217 |
+
|
| 218 |
iface = gr.Interface(
|
| 219 |
fn=generate_dpr,
|
| 220 |
inputs=gr.Files(type="filepath", label="Upload Site Photos"),
|