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