Rekham1110 commited on
Commit
53f2658
·
verified ·
1 Parent(s): 807468f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -114
app.py CHANGED
@@ -1,122 +1,90 @@
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
-
16
- # Validate Salesforce credentials
17
- if not all([SF_USERNAME, SF_PASSWORD, SF_SECURITY_TOKEN]):
18
- raise ValueError("Missing Salesforce credentials. Set SF_USERNAME, SF_PASSWORD, and SF_SECURITY_TOKEN in environment variables.")
19
-
20
- # Initialize Salesforce connection
21
- try:
22
- sf = Salesforce(
23
- username=SF_USERNAME,
24
- password=SF_PASSWORD,
25
- security_token=SF_SECURITY_TOKEN,
26
- domain='login'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  )
28
- except Exception as e:
29
- print(f"Salesforce connection failed: {str(e)}")
30
- raise
31
-
32
- # Valid milestones
33
- VALID_MILESTONES = ["Foundation", "Walls Erected", "Planning", "Completed"]
34
-
35
- # Mock AI prediction
36
- def mock_ai_model(image):
37
- img = image.convert("RGB")
38
- max_size = 1024
39
- img.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
40
- milestone = random.choice(VALID_MILESTONES)
41
- completion_percent = random.choice([10, 30, 50, 80, 100])
42
- confidence_score = round(random.uniform(0.85, 0.95), 2)
43
- return milestone, completion_percent, confidence_score
44
-
45
- # Gradio function
46
- def process_image(image, project_name):
47
- try:
48
- if image is None:
49
- return "Error: Please upload an image to proceed.", "Pending", "", "", 0
50
-
51
- img = Image.open(image)
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
55
- if not str(image).lower().endswith(('.jpg', '.jpeg', '.png')):
56
- return "Error: Only JPG/PNG images are supported.", "Failure", "", "", 0
57
-
58
- # Save image to public folder for URL generation
59
- upload_dir = "public_uploads"
60
- os.makedirs(upload_dir, exist_ok=True)
61
- unique_id = datetime.now().strftime("%Y%m%d%H%M%S")
62
- image_filename = f"{unique_id}_{os.path.basename(image)}"
63
- saved_image_path = os.path.join(upload_dir, image_filename)
64
- shutil.copy(image, saved_image_path)
65
-
66
- # Create public URL assuming you're serving /public_uploads/ via static web server (e.g., on localhost or external host)
67
- public_url_base = os.getenv("PUBLIC_URL_BASE", "http://localhost:7860/public_uploads")
68
- image_url = f"{public_url_base}/{image_filename}"
69
-
70
- # Predict
71
- milestone, percent_complete, confidence_score = mock_ai_model(img)
72
-
73
- # Construct Salesforce record
74
- record = {
75
- "Name__c": project_name,
76
- "Current_Milestone__c": milestone,
77
- "Completion_Percentage__c": percent_complete,
78
- "Last_Updated_On__c": datetime.now().isoformat(),
79
- "Upload_Status__c": "Success",
80
- "Comments__c": f"AI Prediction: {milestone} with {confidence_score*100}% confidence",
81
- "Last_Updated_Image__c": image_url
82
- }
83
-
84
- try:
85
- sf.Construction__c.create(record)
86
- except Exception as e:
87
- return f"Error: Failed to update Salesforce - {str(e)}", "Failure", "", "", 0
88
-
89
- return (
90
- f"Success: Milestone: {milestone}, Completion: {percent_complete}%",
91
- "Success",
92
- milestone,
93
- f"Confidence Score: {confidence_score}",
94
- percent_complete
95
- )
96
-
97
- except Exception as e:
98
- return f"Error: {str(e)}", "Failure", "", "", 0
99
 
100
  # Gradio UI
101
- with gr.Blocks(css=".gradio-container {background-color: #f0f4f8; font-family: Arial;} .title {color: #2c3e50; font-size: 24px; text-align: center;}") as demo:
102
- gr.Markdown("<h1 class='title'>Construction Milestone Detector</h1>")
103
- with gr.Row():
104
- image_input = gr.Image(type="filepath", label="Upload Construction Site Photo (JPG/PNG, ≤ 20MB)")
105
- project_name_input = gr.Textbox(label="Project Name (Required)", placeholder="e.g. Project_12345")
106
-
107
- submit_button = gr.Button("Process Image")
108
- output_text = gr.Textbox(label="Result")
109
- upload_status = gr.Textbox(label="Upload Status")
110
- milestone = gr.Textbox(label="Detected Milestone")
111
- confidence = gr.Textbox(label="Confidence Score")
112
- progress = gr.Slider(0, 100, label="Completion Percentage", interactive=False, value=0)
113
-
114
- submit_button.click(
115
- fn=process_image,
116
- inputs=[image_input, project_name_input],
117
- outputs=[output_text, upload_status, milestone, confidence, progress]
118
- )
119
-
120
- demo.launch(share=False)
121
-
122
 
 
 
 
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="/")