lokeshloki143 commited on
Commit
f8bc9fc
·
verified ·
1 Parent(s): 2b7c615

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -72
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import gradio as gr
2
  import logging
3
  from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
@@ -5,18 +6,35 @@ import os
5
  from fastapi import FastAPI
6
  from pydantic import BaseModel
7
  from simple_salesforce import Salesforce
8
- import json
 
 
 
9
 
10
  # Configure logging
11
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
12
 
13
- # Load Hugging Face token from environment variable
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  HF_TOKEN = os.getenv("HF_TOKEN")
15
  if not HF_TOKEN:
16
  logging.warning("HF_TOKEN not set. Attempting to load public models only.")
17
 
18
  # Model configuration
19
- MODEL_PATH = "your_username/fine_tuned_bart_construction" # Replace with your actual model path
20
  FALLBACK_MODEL = "facebook/bart-large" # Fallback public model
21
 
22
  try:
@@ -36,35 +54,13 @@ except Exception as e:
36
  logging.error(f"Failed to load fallback model {FALLBACK_MODEL}: {fallback_e}")
37
  raise fallback_e
38
 
39
- # Salesforce connection
40
- def get_salesforce_connection():
41
- try:
42
- sf_username = os.getenv("onteddugeetha104@gmail.com")
43
- sf_password = os.getenv("9032590825g@")
44
- sf_security_token = os.getenv("tTPLQduw8wDpxdKOMJ3d9dM3o")
45
-
46
- if not all([sf_username, sf_password, sf_security_token]):
47
- logging.error("Salesforce credentials missing in environment variables")
48
- raise ValueError("Salesforce credentials not configured")
49
-
50
- sf = Salesforce(
51
- username=sf_username,
52
- password=sf_password,
53
- security_token=sf_security_token
54
- )
55
- logging.info("Connected to Salesforce successfully")
56
- return sf
57
- except Exception as e:
58
- logging.error(f"Failed to connect to Salesforce: {e}")
59
- raise e
60
-
61
  # Define input model for FastAPI
62
  class ChecklistInput(BaseModel):
63
  role: str = "Supervisor"
64
  project_id: str = "Unknown"
65
  project_name: str = "Unknown Project"
66
  milestones: str = "No milestones provided"
67
- coaching_record_id: str = None # Optional Salesforce record ID
68
 
69
  # Initialize FastAPI
70
  app = FastAPI()
@@ -72,22 +68,8 @@ app = FastAPI()
72
  @app.post("/generate")
73
  async def generate_checklist(data: ChecklistInput):
74
  try:
75
- # Connect to Salesforce
76
- sf = get_salesforce_connection()
77
-
78
- # Fetch milestones from Project__c if project_id is provided
79
- milestones = data.milestones
80
- if data.project_id != "Unknown":
81
- try:
82
- project = sf.query(f"SELECT Milestones__c FROM Project__c WHERE Id = '{data.project_id}'")
83
- if project["totalSize"] > 0:
84
- milestones = project["records"][0]["Milestones__c"] or milestones
85
- logging.info(f"Fetched milestones for project {data.project_id}: {milestones}")
86
- except Exception as e:
87
- logging.warning(f"Failed to fetch project milestones: {e}")
88
-
89
  # Prepare input for the model
90
- inputs = f"Role: {data.role} Project: {data.project_id} ({data.project_name}) Milestones: {milestones}"
91
  logging.info(f"Generating checklist for inputs: {inputs[:100]}...")
92
 
93
  # Tokenize and generate
@@ -98,17 +80,18 @@ async def generate_checklist(data: ChecklistInput):
98
  # Static tips (replace with model-generated tips after fine-tuning)
99
  tips = "1. Prioritize safety checks\n2. Review milestones\n3. Log progress"
100
 
101
- # Update Salesforce record if coaching_record_id is provided
102
- if data.coaching_record_id:
103
  try:
104
- sf.Supervisor_AI_Coaching__c.update(data.coaching_record_id, {
105
- "Daily_Checklist__c": checklist,
106
- "Suggested_Tips__c": tips,
107
- "Engagement_Score__c": 10 # Increment or set as needed
 
108
  })
109
- logging.info(f"Updated Salesforce record {data.coaching_record_id}")
110
- except Exception as e:
111
- logging.error(f"Failed to update Salesforce record: {e}")
112
 
113
  logging.info("Checklist and tips generated successfully")
114
  return {
@@ -120,49 +103,44 @@ async def generate_checklist(data: ChecklistInput):
120
  return {"error": str(e)}
121
 
122
  # Gradio interface function
123
- def gradio_generate_checklist(role, project_id, project_name, milestones, coaching_record_id=""):
124
  try:
125
- sf = get_salesforce_connection()
126
-
127
- # Fetch milestones if project_id is valid
128
- if project_id:
129
- project = sf.query(f"SELECT Milestones__c FROM Project__c WHERE Id = '{project_id}'")
130
- if project["totalSize"] > 0:
131
- milestones = project["records"][0]["Milestones__c"] or milestones
132
-
133
  inputs = f"Role: {role} Project: {project_id} ({project_name}) Milestones: {milestones}"
134
  input_ids = tokenizer(inputs, return_tensors="pt", max_length=128, truncation=True).input_ids
135
  outputs = model.generate(input_ids, max_length=128, num_beams=4, early_stopping=True)
136
  checklist = tokenizer.decode(outputs[0], skip_special_tokens=True)
137
  tips = "1. Prioritize safety checks\n2. Review milestones\n3. Log progress"
138
 
139
- if coaching_record_id:
140
- sf.Supervisor_AI_Coaching__c.update(coaching_record_id, {
141
- "Daily_Checklist__c": checklist,
142
- "Suggested_Tips__c": tips,
143
- "Engagement_Score__c": 10
 
 
144
  })
145
-
146
- return checklist, tips
147
  except Exception as e:
148
- return f"Error: {str(e)}", ""
149
 
150
  # Define Gradio interface
151
  iface = gr.Interface(
152
  fn=gradio_generate_checklist,
153
  inputs=[
154
  gr.Textbox(label="Role", value="Supervisor"),
155
- gr.Textbox(label="Project ID", value=""),
156
  gr.Textbox(label="Project Name", value="Building A"),
157
  gr.Textbox(label="Milestones", value="Complete foundation by 5/15"),
158
- gr.Textbox(label="Coaching Record ID", value="")
159
  ],
160
  outputs=[
161
  gr.Textbox(label="Checklist"),
162
- gr.Textbox(label="Tips")
 
163
  ],
164
  title="AI Coach for Site Supervisors",
165
- description="Generate daily checklists and tips, with Salesforce integration."
166
  )
167
 
168
  # Mount FastAPI to Gradio
@@ -174,4 +152,5 @@ if __name__ == "__main__":
174
  logging.info("Gradio interface launched successfully")
175
  except Exception as e:
176
  logging.error(f"Failed to launch Gradio interface: {e}")
177
- raise e
 
 
1
+ ```python
2
  import gradio as gr
3
  import logging
4
  from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
 
6
  from fastapi import FastAPI
7
  from pydantic import BaseModel
8
  from simple_salesforce import Salesforce
9
+ from dotenv import load_dotenv
10
+
11
+ # Load environment variables from .env
12
+ load_dotenv()
13
 
14
  # Configure logging
15
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
16
 
17
+ # Salesforce connection
18
+ def get_salesforce_connection():
19
+ try:
20
+ sf = Salesforce(
21
+ username=os.getenv("SF_USERNAME"),
22
+ password=os.getenv("SF_PASSWORD"),
23
+ security_token=os.getenv("SF_SECURITY_TOKEN")
24
+ )
25
+ logging.info("Salesforce connection established successfully")
26
+ return sf
27
+ except Exception as e:
28
+ logging.error(f"Failed to connect to Salesforce: {e}")
29
+ raise e
30
+
31
+ # Load Hugging Face token
32
  HF_TOKEN = os.getenv("HF_TOKEN")
33
  if not HF_TOKEN:
34
  logging.warning("HF_TOKEN not set. Attempting to load public models only.")
35
 
36
  # Model configuration
37
+ MODEL_PATH = "your_actual_username/fine_tuned_bart_construction" # Replace with your model path
38
  FALLBACK_MODEL = "facebook/bart-large" # Fallback public model
39
 
40
  try:
 
54
  logging.error(f"Failed to load fallback model {FALLBACK_MODEL}: {fallback_e}")
55
  raise fallback_e
56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  # Define input model for FastAPI
58
  class ChecklistInput(BaseModel):
59
  role: str = "Supervisor"
60
  project_id: str = "Unknown"
61
  project_name: str = "Unknown Project"
62
  milestones: str = "No milestones provided"
63
+ record_id: str = None # Salesforce record ID for updates
64
 
65
  # Initialize FastAPI
66
  app = FastAPI()
 
68
  @app.post("/generate")
69
  async def generate_checklist(data: ChecklistInput):
70
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  # Prepare input for the model
72
+ inputs = f"Role: {data.role} Project: {data.project_id} ({data.project_name}) Milestones: {data.milestones}"
73
  logging.info(f"Generating checklist for inputs: {inputs[:100]}...")
74
 
75
  # Tokenize and generate
 
80
  # Static tips (replace with model-generated tips after fine-tuning)
81
  tips = "1. Prioritize safety checks\n2. Review milestones\n3. Log progress"
82
 
83
+ # Update Salesforce record if record_id is provided
84
+ if data.record_id:
85
  try:
86
+ sf = get_salesforce_connection()
87
+ sf.Supervisor_AI_Coaching__c.update(data.record_id, {
88
+ 'Daily_Checklist__c': checklist,
89
+ 'Suggested_Tips__c': tips,
90
+ 'Engagement_Score__c': 10 if not sf.Supervisor_AI_Coaching__c.get(data.record_id).get('Engagement_Score__c') else sf.Supervisor_AI_Coaching__c.get(data.record_id).get('Engagement_Score__c') + 10
91
  })
92
+ logging.info(f"Updated Salesforce record {data.record_id}")
93
+ except Exception as sf_e:
94
+ logging.error(f"Failed to update Salesforce: {sf_e}")
95
 
96
  logging.info("Checklist and tips generated successfully")
97
  return {
 
103
  return {"error": str(e)}
104
 
105
  # Gradio interface function
106
+ def gradio_generate_checklist(role, project_id, project_name, milestones, record_id=""):
107
  try:
 
 
 
 
 
 
 
 
108
  inputs = f"Role: {role} Project: {project_id} ({project_name}) Milestones: {milestones}"
109
  input_ids = tokenizer(inputs, return_tensors="pt", max_length=128, truncation=True).input_ids
110
  outputs = model.generate(input_ids, max_length=128, num_beams=4, early_stopping=True)
111
  checklist = tokenizer.decode(outputs[0], skip_special_tokens=True)
112
  tips = "1. Prioritize safety checks\n2. Review milestones\n3. Log progress"
113
 
114
+ # Update Salesforce if record_id is provided
115
+ if record_id:
116
+ sf = get_salesforce_connection()
117
+ sf.Supervisor_AI_Coaching__c.update(record_id, {
118
+ 'Daily_Checklist__c': checklist,
119
+ 'Suggested_Tips__c': tips,
120
+ 'Engagement_Score__c': 10 if not sf.Supervisor_AI_Coaching__c.get(record_id).get('Engagement_Score__c') else sf.Supervisor_AI_Coaching__c.get(record_id).get('Engagement_Score__c') + 10
121
  })
122
+ return checklist, tips, f"Updated Salesforce record {record_id}"
123
+ return checklist, tips, "No Salesforce update (record_id not provided)"
124
  except Exception as e:
125
+ return f"Error: {str(e)}", "", ""
126
 
127
  # Define Gradio interface
128
  iface = gr.Interface(
129
  fn=gradio_generate_checklist,
130
  inputs=[
131
  gr.Textbox(label="Role", value="Supervisor"),
132
+ gr.Textbox(label="Project ID", value="P001"),
133
  gr.Textbox(label="Project Name", value="Building A"),
134
  gr.Textbox(label="Milestones", value="Complete foundation by 5/15"),
135
+ gr.Textbox(label="Salesforce Record ID (optional)", value="")
136
  ],
137
  outputs=[
138
  gr.Textbox(label="Checklist"),
139
+ gr.Textbox(label="Tips"),
140
+ gr.Textbox(label="Salesforce Status")
141
  ],
142
  title="AI Coach for Site Supervisors",
143
+ description="Generate daily checklists and tips, and update Salesforce records."
144
  )
145
 
146
  # Mount FastAPI to Gradio
 
152
  logging.info("Gradio interface launched successfully")
153
  except Exception as e:
154
  logging.error(f"Failed to launch Gradio interface: {e}")
155
+ raise e
156
+ ```