Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,13 +1,3 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
import requests
|
| 3 |
-
from PIL import Image
|
| 4 |
-
import io
|
| 5 |
-
import os
|
| 6 |
-
import re
|
| 7 |
-
from dotenv import load_dotenv
|
| 8 |
-
from simple_salesforce import Salesforce
|
| 9 |
-
from datetime import datetime
|
| 10 |
-
|
| 11 |
# Load environment variables
|
| 12 |
load_dotenv()
|
| 13 |
HF_API_KEY = os.getenv("HF_API_KEY")
|
|
@@ -17,6 +7,10 @@ SF_SECURITY_TOKEN = os.getenv("SF_SECURITY_TOKEN")
|
|
| 17 |
SF_CONSUMER_KEY = os.getenv("SF_CONSUMER_KEY")
|
| 18 |
SF_CONSUMER_SECRET = os.getenv("SF_CONSUMER_SECRET")
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
# Initialize Salesforce connection
|
| 21 |
try:
|
| 22 |
sf = Salesforce(
|
|
@@ -29,120 +23,4 @@ try:
|
|
| 29 |
)
|
| 30 |
except Exception as e:
|
| 31 |
print(f"Salesforce connection failed: {str(e)}")
|
| 32 |
-
raise
|
| 33 |
-
|
| 34 |
-
# Hugging Face Inference API endpoint (replace with your model)
|
| 35 |
-
HF_MODEL_URL = "https://api-inference.huggingface.co/models/nasreshsuguru/construction-milestone-detector"
|
| 36 |
-
|
| 37 |
-
def process_image(image, project_name):
|
| 38 |
-
try:
|
| 39 |
-
# Validate inputs
|
| 40 |
-
if image is None:
|
| 41 |
-
return "Error: Please upload an image to proceed.", "Pending", "", 0.0, 0.0, ""
|
| 42 |
-
if not project_name:
|
| 43 |
-
return "Error: Please enter a project name to proceed.", "Pending", "", 0.0, 0.0, ""
|
| 44 |
-
if not re.match(r'^[a-zA-Z0-9\s-]+$', project_name):
|
| 45 |
-
return "Error: Project name must be alphanumeric (letters, numbers, spaces, or hyphens).", "Pending", "", 0.0, 0.0, ""
|
| 46 |
-
|
| 47 |
-
# Validate image size and type
|
| 48 |
-
image_size_mb = os.path.getsize(image) / (1024 * 1024)
|
| 49 |
-
if image_size_mb > 20:
|
| 50 |
-
return "Error: Image size exceeds 20MB.", "Failure", "", 0.0, 0.0, ""
|
| 51 |
-
if not image.lower().endswith(('.jpg', '.jpeg', '.png')):
|
| 52 |
-
return "Error: Only JPG/PNG images are supported.", "Failure", "", 0.0, 0.0, ""
|
| 53 |
-
|
| 54 |
-
# Preprocess image
|
| 55 |
-
img = Image.open(image)
|
| 56 |
-
max_size = 1024 # Optimize for performance
|
| 57 |
-
img.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
|
| 58 |
-
img = img.resize((224, 224))
|
| 59 |
-
img_byte_arr = io.BytesIO()
|
| 60 |
-
img.save(img_byte_arr, format="PNG")
|
| 61 |
-
img_byte_arr = img_byte_arr.getvalue()
|
| 62 |
-
|
| 63 |
-
# Call Hugging Face API
|
| 64 |
-
headers = {"Authorization": f"Bearer {HF_API_KEY}"}
|
| 65 |
-
response = requests.post(HF_MODEL_URL, headers=headers, data=img_byte_arr, timeout=10)
|
| 66 |
-
|
| 67 |
-
if response.status_code != 200:
|
| 68 |
-
return f"Error: Hugging Face API failed with status {response.status_code}", "Failure", "", 0.0, 0.0, ""
|
| 69 |
-
|
| 70 |
-
# Parse AI output
|
| 71 |
-
result = response.json()
|
| 72 |
-
top_predictions = sorted(result, key=lambda x: x["score"], reverse=True)[:3]
|
| 73 |
-
milestone = top_predictions[0]["label"]
|
| 74 |
-
confidence = top_predictions[0]["score"]
|
| 75 |
-
percent_complete = min(max(int(confidence * 100), 0), 100)
|
| 76 |
-
prediction_details = "\n".join([f"{pred['label']}: {pred['score']:.2f}" for pred in top_predictions])
|
| 77 |
-
|
| 78 |
-
# Update Salesforce record
|
| 79 |
-
record = {
|
| 80 |
-
"Name": project_name,
|
| 81 |
-
"Current_Milestone__c": milestone,
|
| 82 |
-
"Completion_Percentage__c": percent_complete,
|
| 83 |
-
"Last_Updated_On__c": datetime.now().isoformat(),
|
| 84 |
-
"Upload_Status__c": "Success",
|
| 85 |
-
"Comments__c": f"AI Confidence: {confidence:.2f}",
|
| 86 |
-
"Version__c": 1
|
| 87 |
-
}
|
| 88 |
-
|
| 89 |
-
try:
|
| 90 |
-
project_name = project_name.replace("'", "''") # Basic escaping
|
| 91 |
-
query = f"SELECT Id, Version__c FROM Construction_Project__c WHERE Name = '{project_name}'"
|
| 92 |
-
result = sf.query(query)
|
| 93 |
-
if result["totalSize"] > 0:
|
| 94 |
-
project_id = result["records"][0]["Id"]
|
| 95 |
-
current_version = result["records"][0].get("Version__c", 0)
|
| 96 |
-
record["Version__c"] = current_version + 1
|
| 97 |
-
sf.Construction_Project__c.update(project_id, record)
|
| 98 |
-
else:
|
| 99 |
-
sf.Construction_Project__c.create(record)
|
| 100 |
-
except Exception as e:
|
| 101 |
-
return f"Error: Failed to update Salesforce - {str(e)}", "Failure", "", 0.0, 0.0, prediction_details
|
| 102 |
-
|
| 103 |
-
return (
|
| 104 |
-
f"Success: Milestone: {milestone}, Completion: {percent_complete}%",
|
| 105 |
-
"Success",
|
| 106 |
-
milestone,
|
| 107 |
-
percent_complete,
|
| 108 |
-
confidence,
|
| 109 |
-
prediction_details
|
| 110 |
-
)
|
| 111 |
-
|
| 112 |
-
except Exception as e:
|
| 113 |
-
return f"Error: {str(e)}", "Failure", "", 0.0, 0.0, ""
|
| 114 |
-
|
| 115 |
-
# Gradio interface
|
| 116 |
-
with gr.Blocks(css=".gradio-container {background-color: #f0f4f8; font-family: Arial;} .title {color: #2c3e50; font-size: 24px; text-align: center;}") as demo:
|
| 117 |
-
gr.Markdown("<h1 class='title'>Construction Milestone Detector</h1>")
|
| 118 |
-
project_name = gr.Textbox(label="Project Name", placeholder="Enter project name")
|
| 119 |
-
image_input = gr.Image(type="filepath", label="Upload Construction Site Photo (JPG/PNG, ≤ 20MB)")
|
| 120 |
-
submit_button = gr.Button("Process Image")
|
| 121 |
-
output_text = gr.Textbox(label="Result")
|
| 122 |
-
upload_status = gr.Textbox(label="Upload Status")
|
| 123 |
-
milestone = gr.Textbox(label="Detected Milestone")
|
| 124 |
-
completion_percent = gr.Slider(0, 100, label="Completion Percentage (%)", interactive=False)
|
| 125 |
-
confidence_score = gr.Slider(0, 1, label="Confidence Score", interactive=False)
|
| 126 |
-
prediction_details = gr.Textbox(label="Top Predictions")
|
| 127 |
-
progress = gr.Slider(0, 100, label="Processing Progress", interactive=False, value=0)
|
| 128 |
-
|
| 129 |
-
def update_progress():
|
| 130 |
-
return 50
|
| 131 |
-
|
| 132 |
-
def complete_progress():
|
| 133 |
-
return 100
|
| 134 |
-
|
| 135 |
-
submit_button.click(
|
| 136 |
-
fn=update_progress,
|
| 137 |
-
outputs=progress
|
| 138 |
-
).then(
|
| 139 |
-
fn=process_image,
|
| 140 |
-
inputs=[image_input, project_name],
|
| 141 |
-
outputs=[output_text, upload_status, milestone, completion_percent, confidence_score, prediction_details]
|
| 142 |
-
).then(
|
| 143 |
-
fn=complete_progress,
|
| 144 |
-
outputs=progress
|
| 145 |
-
)
|
| 146 |
-
|
| 147 |
-
if __name__ == "__main__":
|
| 148 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# Load environment variables
|
| 2 |
load_dotenv()
|
| 3 |
HF_API_KEY = os.getenv("HF_API_KEY")
|
|
|
|
| 7 |
SF_CONSUMER_KEY = os.getenv("SF_CONSUMER_KEY")
|
| 8 |
SF_CONSUMER_SECRET = os.getenv("SF_CONSUMER_SECRET")
|
| 9 |
|
| 10 |
+
# Validate Salesforce credentials
|
| 11 |
+
if not all([SF_USERNAME, SF_PASSWORD, SF_SECURITY_TOKEN, SF_CONSUMER_KEY, SF_CONSUMER_SECRET]):
|
| 12 |
+
raise ValueError("Missing Salesforce credentials. Please set SF_USERNAME, SF_PASSWORD, SF_SECURITY_TOKEN, SF_CONSUMER_KEY, and SF_CONSUMER_SECRET in environment variables.")
|
| 13 |
+
|
| 14 |
# Initialize Salesforce connection
|
| 15 |
try:
|
| 16 |
sf = Salesforce(
|
|
|
|
| 23 |
)
|
| 24 |
except Exception as e:
|
| 25 |
print(f"Salesforce connection failed: {str(e)}")
|
| 26 |
+
raise
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|