Rekham1110 commited on
Commit
521c424
·
verified ·
1 Parent(s): 53f2658

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -82
app.py CHANGED
@@ -1,90 +1,123 @@
1
  import gradio as gr
2
- import datetime
3
  import os
4
- import shutil
5
- import uuid
6
- from fastapi import FastAPI
7
- from gradio.routes import mount_gradio_app
8
  from simple_salesforce import Salesforce
 
 
 
 
 
 
 
 
 
 
9
 
10
- # Salesforce login
11
- sf = Salesforce(
12
- username='your_username',
13
- password='your_password',
14
- security_token='your_token'
15
- )
16
-
17
- # Hugging Face public folder for Spaces
18
- PUBLIC_DIR = "/home/user/app/public_uploads"
19
- os.makedirs(PUBLIC_DIR, exist_ok=True)
20
-
21
- # FastAPI instance
22
- app = FastAPI()
23
-
24
- # Dummy model for milestone detection
25
- def predict_milestone(image_path):
26
- return {
27
- "milestone": "Foundation",
28
- "confidence": 0.9,
29
- "completion_percentage": 80
30
- }
31
-
32
- def process_image(image):
33
- # Save uploaded image with unique name
34
- timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
35
- filename = f"{timestamp}_{os.path.basename(image.name)}"
36
- local_path = os.path.join(PUBLIC_DIR, filename)
37
- shutil.copy(image.name, local_path)
38
-
39
- # Publicly accessible URL on Hugging Face Spaces
40
- public_url = f"https://{os.environ['HF_SPACE_ID']}.hf.space/file/public_uploads/{filename}"
41
-
42
- # Model prediction
43
- result = predict_milestone(local_path)
44
- milestone = result["milestone"]
45
- confidence = result["confidence"]
46
- completion = result["completion_percentage"]
47
-
48
- # Save to Salesforce
49
- now_str = datetime.datetime.now().strftime('%d/%m/%Y, %I:%M %p')
50
- sf.Construction__c.create({
51
- 'Project_Name__c': 'Construction',
52
- 'Current_Milestone__c': milestone,
53
- 'Completion_Percentage__c': f"{completion}%",
54
- 'Last_Updated_Image__c': public_url,
55
- 'Last_Updated_On__c': now_str,
56
- 'Upload_Status__c': 'Success',
57
- 'Comments__c': f"AI Prediction: {milestone} with {confidence*100:.1f}% confidence"
58
- })
59
-
60
- return (
61
- f"Success: Milestone: {milestone}, Completion: {completion}%",
62
- "Success",
63
- milestone,
64
- f"Confidence Score: {confidence}",
65
- completion
66
  )
 
 
 
67
 
68
- # Gradio UI
69
- def build_ui():
70
- with gr.Blocks() as demo:
71
- gr.Markdown("## Process Image")
72
- with gr.Row():
73
- image_input = gr.Image(type="filepath", label="Upload Image")
74
- with gr.Row():
75
- result = gr.Textbox(label="Result")
76
- with gr.Row():
77
- upload_status = gr.Textbox(label="Upload Status")
78
- milestone = gr.Textbox(label="Detected Milestone")
79
- with gr.Row():
80
- confidence = gr.Textbox(label="Confidence Score")
81
- percentage = gr.Slider(minimum=0, maximum=100, label="Completion Percentage")
82
- image_input.change(
83
- fn=process_image,
84
- inputs=[image_input],
85
- outputs=[result, upload_status, milestone, confidence, percentage]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  )
87
- return demo
88
 
89
- demo_app = build_ui()
90
- mount_gradio_app(app, demo_app, path="/")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from PIL import Image
3
  import os
4
+ from dotenv import load_dotenv
 
 
 
5
  from simple_salesforce import Salesforce
6
+ from datetime import datetime
7
+ import random
8
+ import shutil
9
+
10
+ # Load environment variables
11
+ load_dotenv()
12
+ SF_USERNAME = os.getenv("SF_USERNAME")
13
+ SF_PASSWORD = os.getenv("SF_PASSWORD")
14
+ SF_SECURITY_TOKEN = os.getenv("SF_SECURITY_TOKEN")
15
+ PUBLIC_URL_BASE = os.getenv("PUBLIC_URL_BASE", "https://your-public-host.com/public_uploads")
16
 
17
+ # Validate Salesforce credentials
18
+ if not all([SF_USERNAME, SF_PASSWORD, SF_SECURITY_TOKEN]):
19
+ raise ValueError("Missing Salesforce credentials. Set SF_USERNAME, SF_PASSWORD, and SF_SECURITY_TOKEN in environment variables.")
20
+
21
+ # Initialize Salesforce connection
22
+ try:
23
+ sf = Salesforce(
24
+ username=SF_USERNAME,
25
+ password=SF_PASSWORD,
26
+ security_token=SF_SECURITY_TOKEN,
27
+ domain='login'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  )
29
+ except Exception as e:
30
+ print(f"Salesforce connection failed: {str(e)}")
31
+ raise
32
 
33
+ # Valid milestones
34
+ VALID_MILESTONES = ["Foundation", "Walls Erected", "Planning", "Completed"]
35
+
36
+ # Mock AI prediction
37
+ def mock_ai_model(image):
38
+ img = image.convert("RGB")
39
+ max_size = 1024
40
+ img.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
41
+ milestone = random.choice(VALID_MILESTONES)
42
+ completion_percent = random.choice([10, 30, 50, 80, 100])
43
+ confidence_score = round(random.uniform(0.85, 0.95), 2)
44
+ return milestone, completion_percent, confidence_score
45
+
46
+ # Gradio function
47
+ def process_image(image, project_name):
48
+ try:
49
+ if image is None:
50
+ return "Error: Please upload an image to proceed.", "Pending", "", "", 0
51
+
52
+ img = Image.open(image)
53
+ image_size_mb = os.path.getsize(image) / (1024 * 1024)
54
+ if image_size_mb > 20:
55
+ return "Error: Image size exceeds 20MB.", "Failure", "", "", 0
56
+ if not str(image).lower().endswith(('.jpg', '.jpeg', '.png')):
57
+ return "Error: Only JPG/PNG images are supported.", "Failure", "", "", 0
58
+
59
+ # Save image to public folder
60
+ upload_dir = "public_uploads"
61
+ os.makedirs(upload_dir, exist_ok=True)
62
+ unique_id = datetime.now().strftime("%Y%m%d%H%M%S")
63
+ image_filename = f"{unique_id}_{os.path.basename(image)}"
64
+ saved_image_path = os.path.join(upload_dir, image_filename)
65
+ shutil.copy(image, saved_image_path)
66
+
67
+ # Publicly accessible URL (replace base with deployed static site URL)
68
+ image_url = f"{PUBLIC_URL_BASE}/{image_filename}"
69
+
70
+ # AI Prediction
71
+ milestone, percent_complete, confidence_score = mock_ai_model(img)
72
+
73
+ # Format timestamp
74
+ formatted_timestamp = datetime.now().strftime("%d/%m/%Y, %I:%M %p")
75
+
76
+ # Salesforce record
77
+ record = {
78
+ "Name__c": project_name,
79
+ "Current_Milestone__c": milestone,
80
+ "Completion_Percentage__c": percent_complete,
81
+ "Last_Updated_On__c": formatted_timestamp,
82
+ "Upload_Status__c": "Success",
83
+ "Comments__c": f"AI Prediction: {milestone} with {confidence_score * 100:.1f}% confidence",
84
+ "Last_Updated_Image__c": image_url
85
+ }
86
+
87
+ try:
88
+ sf.Construction__c.create(record)
89
+ except Exception as e:
90
+ return f"Error: Failed to update Salesforce - {str(e)}", "Failure", "", "", 0
91
+
92
+ return (
93
+ f"Success: Milestone: {milestone}, Completion: {percent_complete}%",
94
+ "Success",
95
+ milestone,
96
+ f"Confidence Score: {confidence_score}",
97
+ percent_complete
98
  )
 
99
 
100
+ except Exception as e:
101
+ return f"Error: {str(e)}", "Failure", "", "", 0
102
+
103
+ # Gradio UI
104
+ with gr.Blocks(css=".gradio-container {background-color: #f0f4f8; font-family: Arial;} .title {color: #2c3e50; font-size: 24px; text-align: center;}") as demo:
105
+ gr.Markdown("<h1 class='title'>Construction Milestone Detector</h1>")
106
+ with gr.Row():
107
+ image_input = gr.Image(type="filepath", label="Upload Construction Site Photo (JPG/PNG, ≤ 20MB)")
108
+ project_name_input = gr.Textbox(label="Project Name (Required)", placeholder="e.g. Project_12345")
109
+
110
+ submit_button = gr.Button("Process Image")
111
+ output_text = gr.Textbox(label="Result")
112
+ upload_status = gr.Textbox(label="Upload Status")
113
+ milestone = gr.Textbox(label="Detected Milestone")
114
+ confidence = gr.Textbox(label="Confidence Score")
115
+ progress = gr.Slider(0, 100, label="Completion Percentage", interactive=False, value=0)
116
+
117
+ submit_button.click(
118
+ fn=process_image,
119
+ inputs=[image_input, project_name_input],
120
+ outputs=[output_text, upload_status, milestone, confidence, progress]
121
+ )
122
+
123
+ demo.launch(share=False)