Bhanumani12 commited on
Commit
44a607c
·
verified ·
1 Parent(s): 01b1f4a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -35
app.py CHANGED
@@ -34,11 +34,11 @@ severities = {
34
  "Best Practice": "Low"
35
  }
36
 
37
- # ---------- Mock Salesforce Knowledge Base ----------
38
  salesforce_knowledge_base = {
39
- "governor limits soql": "...", # Truncated for brevity
40
- "governor limits dml": "...",
41
- "bulkify apex trigger": "...",
42
  "soql injection": "...",
43
  "lwc best practices": "...",
44
  "batch apex": "..."
@@ -51,27 +51,56 @@ except Exception as e:
51
  print(f"Model loading error: {e}. Falling back to flan-t5-base.")
52
  qa_pipeline = pipeline("text2text-generation", model="google/flan-t5-base")
53
 
54
- # ---------- Local Logging ----------
55
  def log_to_console(data, log_type):
56
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
57
  print(f"[{timestamp}] {log_type} Log: {data}")
58
 
59
- # ---------- Code Analyzer ----------
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  def analyze_code(code):
61
  if not code.strip():
62
  return "No code provided.", "", ""
 
63
  label = random.choice(list(label_to_issue_type.keys()))
64
  issue_type = label_to_issue_type[label]
65
  suggestion = suggestions[issue_type]
66
  severity = severities[issue_type]
67
- log_data = {
 
68
  "Name": f"Review_{issue_type}",
69
- "CodeSnippet": code,
70
- "IssueType": issue_type,
71
- "Suggestion": suggestion,
72
- "Severity": severity
73
  }
74
- log_to_console(log_data, "Code Review")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  return issue_type, suggestion, severity
76
 
77
  # ---------- Metadata Validator ----------
@@ -93,13 +122,20 @@ def validate_metadata(metadata):
93
 
94
  # ---------- Salesforce Chatbot ----------
95
  conversation_history = []
 
96
  def salesforce_chatbot(query, history=[]):
97
  global conversation_history
98
  if not query.strip():
99
  return "Please provide a valid Salesforce-related question."
100
- salesforce_keywords = [ "apex", "soql", "trigger", "lwc", "governor limits", "dml", "metadata", "batch apex", "api", "profile", "workflow", "custom object", "record type", "sfdc", "force.com" ]
101
- if not any(keyword in query.lower() for keyword in salesforce_keywords):
102
- return "Please ask a Salesforce-related question (e.g., about Apex, SOQL, LWC, or Salesforce platform features)."
 
 
 
 
 
 
103
  query_key = query.lower().strip()
104
  for kb_key, kb_answer in salesforce_knowledge_base.items():
105
  if kb_key in query_key:
@@ -107,21 +143,25 @@ def salesforce_chatbot(query, history=[]):
107
  conversation_history = conversation_history[-6:]
108
  log_to_console({"Question": query, "Answer": kb_answer}, "Chatbot Query")
109
  return kb_answer
 
110
  history_summary = "\n".join([f"User: {q}\nAssistant: {a}" for q, a in conversation_history[-4:]])
111
  prompt = f"""
112
  You are an expert Salesforce developer...
 
113
  Conversation History:
114
  {history_summary}
 
115
  Question: {query.strip()}
116
  Answer:
117
  """
 
118
  try:
119
  result = qa_pipeline(prompt, max_new_tokens=1024, do_sample=False, temperature=0.1, top_k=50)
120
  output = result[0]["generated_text"].strip()
121
  if output.startswith("Answer:"):
122
  output = output[7:].strip()
123
  if len(output) < 20:
124
- output = f"I'm sorry, I couldn't find a precise answer for '{query}'. Please check Salesforce docs."
125
  conversation_history.append((query, output))
126
  conversation_history = conversation_history[-6:]
127
  log_to_console({"Question": query, "Answer": output}, "Chatbot Query")
@@ -129,20 +169,7 @@ Answer:
129
  except Exception as e:
130
  return f"⚠️ Error generating response: {str(e)}"
131
 
132
- # ---------- Salesforce Connection ----------
133
- try:
134
- session_id, instance = SalesforceLogin(
135
- username=SF_USERNAME,
136
- password=SF_PASSWORD,
137
- security_token=SF_SECURITY_TOKEN
138
- )
139
- sf = Salesforce(instance=instance, session_id=session_id)
140
- print("✅ Connected to Salesforce successfully")
141
- except Exception as e:
142
- sf = None
143
- print(f"❌ Failed to connect to Salesforce: {e}")
144
-
145
- # ---------- Create Salesforce Record ----------
146
  def create_salesforce_record(object_type, field_name, field_value):
147
  if not sf:
148
  return "Salesforce connection not established."
@@ -161,7 +188,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
161
  gr.Markdown("# 🤖 Advanced Salesforce AI Code Review & Chatbot")
162
 
163
  with gr.Tab("Code Review"):
164
- code_input = gr.Textbox(label="Apex / LWC Code", lines=8, placeholder="Enter code here")
165
  issue_type = gr.Textbox(label="Issue Type")
166
  suggestion = gr.Textbox(label="AI Suggestion")
167
  severity = gr.Textbox(label="Severity")
@@ -169,7 +196,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
169
  code_button.click(analyze_code, inputs=code_input, outputs=[issue_type, suggestion, severity])
170
 
171
  with gr.Tab("Metadata Validation"):
172
- metadata_input = gr.Textbox(label="Metadata XML", lines=8)
173
  mtype = gr.Textbox(label="Type")
174
  issue = gr.Textbox(label="Issue")
175
  recommendation = gr.Textbox(label="Recommendation")
@@ -178,7 +205,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
178
 
179
  with gr.Tab("Salesforce Chatbot"):
180
  chatbot_output = gr.Chatbot(label="Conversation History", height=400)
181
- query_input = gr.Textbox(label="Your Question")
182
  with gr.Row():
183
  chatbot_button = gr.Button("Ask")
184
  clear_button = gr.Button("Clear Chat")
@@ -186,7 +213,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
186
 
187
  def update_chatbot(query, chat_history):
188
  if not query.strip():
189
- return chat_history, "Please enter a question."
190
  response = salesforce_chatbot(query, chat_history)
191
  chat_history.append((query, response))
192
  return chat_history, ""
@@ -200,7 +227,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
200
  clear_button.click(fn=clear_chat, inputs=None, outputs=[chatbot_output, query_input])
201
 
202
  with gr.Tab("Create Salesforce Record"):
203
- gr.Markdown("### 📇 Create a New Salesforce Record")
204
  object_type = gr.Textbox(label="Object API Name", placeholder="e.g., Account")
205
  field_name = gr.Textbox(label="Field API Name", placeholder="e.g., Name")
206
  field_value = gr.Textbox(label="Field Value", placeholder="e.g., Test Company")
 
34
  "Best Practice": "Low"
35
  }
36
 
37
+ # ---------- Mock Knowledge Base ----------
38
  salesforce_knowledge_base = {
39
+ "governor limits soql": "In Salesforce, the governor limit for SOQL queries is 100 per synchronous transaction and 200 per asynchronous transaction.",
40
+ "governor limits dml": "The governor limit for DML statements is 150 per transaction.",
41
+ "bulkify apex trigger": "...", # Truncated for brevity
42
  "soql injection": "...",
43
  "lwc best practices": "...",
44
  "batch apex": "..."
 
51
  print(f"Model loading error: {e}. Falling back to flan-t5-base.")
52
  qa_pipeline = pipeline("text2text-generation", model="google/flan-t5-base")
53
 
54
+ # ---------- Logging ----------
55
  def log_to_console(data, log_type):
56
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
57
  print(f"[{timestamp}] {log_type} Log: {data}")
58
 
59
+ # ---------- Salesforce Connection ----------
60
+ try:
61
+ session_id, instance = SalesforceLogin(
62
+ username=SF_USERNAME,
63
+ password=SF_PASSWORD,
64
+ security_token=SF_SECURITY_TOKEN
65
+ )
66
+ sf = Salesforce(instance=instance, session_id=session_id)
67
+ print("✅ Connected to Salesforce successfully")
68
+ except Exception as e:
69
+ sf = None
70
+ print(f"❌ Failed to connect to Salesforce: {e}")
71
+
72
+ # ---------- Code Analyzer (Salesforce Integration) ----------
73
  def analyze_code(code):
74
  if not code.strip():
75
  return "No code provided.", "", ""
76
+
77
  label = random.choice(list(label_to_issue_type.keys()))
78
  issue_type = label_to_issue_type[label]
79
  suggestion = suggestions[issue_type]
80
  severity = severities[issue_type]
81
+
82
+ review_data = {
83
  "Name": f"Review_{issue_type}",
84
+ "CodeSnippet__c": code,
85
+ "IssueType__c": issue_type,
86
+ "Suggestion__c": suggestion,
87
+ "Severity__c": severity
88
  }
89
+
90
+ log_to_console(review_data, "Code Review")
91
+
92
+ if sf:
93
+ try:
94
+ result = sf.CodeReviewResult__c.create(review_data)
95
+ if result.get("success"):
96
+ log_to_console({"Salesforce Record ID": result["id"]}, "Salesforce Create")
97
+ else:
98
+ log_to_console(result, "Salesforce Error")
99
+ except Exception as e:
100
+ log_to_console({"Salesforce Exception": str(e)}, "Salesforce Error")
101
+ else:
102
+ log_to_console("Salesforce not connected.", "Salesforce Error")
103
+
104
  return issue_type, suggestion, severity
105
 
106
  # ---------- Metadata Validator ----------
 
122
 
123
  # ---------- Salesforce Chatbot ----------
124
  conversation_history = []
125
+
126
  def salesforce_chatbot(query, history=[]):
127
  global conversation_history
128
  if not query.strip():
129
  return "Please provide a valid Salesforce-related question."
130
+
131
+ salesforce_keywords = [
132
+ "apex", "soql", "trigger", "lwc", "aura", "visualforce", "salesforce", "governor limits",
133
+ "dml", "metadata", "batch apex", "queueable", "future method", "api", "sfdc"
134
+ ]
135
+
136
+ if not any(keyword.lower() in query.lower() for keyword in salesforce_keywords):
137
+ return "Please ask a Salesforce-related question."
138
+
139
  query_key = query.lower().strip()
140
  for kb_key, kb_answer in salesforce_knowledge_base.items():
141
  if kb_key in query_key:
 
143
  conversation_history = conversation_history[-6:]
144
  log_to_console({"Question": query, "Answer": kb_answer}, "Chatbot Query")
145
  return kb_answer
146
+
147
  history_summary = "\n".join([f"User: {q}\nAssistant: {a}" for q, a in conversation_history[-4:]])
148
  prompt = f"""
149
  You are an expert Salesforce developer...
150
+
151
  Conversation History:
152
  {history_summary}
153
+
154
  Question: {query.strip()}
155
  Answer:
156
  """
157
+
158
  try:
159
  result = qa_pipeline(prompt, max_new_tokens=1024, do_sample=False, temperature=0.1, top_k=50)
160
  output = result[0]["generated_text"].strip()
161
  if output.startswith("Answer:"):
162
  output = output[7:].strip()
163
  if len(output) < 20:
164
+ output = f"I'm sorry, I couldn't find a precise answer for '{query}'. Please refer to Salesforce docs."
165
  conversation_history.append((query, output))
166
  conversation_history = conversation_history[-6:]
167
  log_to_console({"Question": query, "Answer": output}, "Chatbot Query")
 
169
  except Exception as e:
170
  return f"⚠️ Error generating response: {str(e)}"
171
 
172
+ # ---------- Create Salesforce Record (Generic Manual Entry) ----------
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  def create_salesforce_record(object_type, field_name, field_value):
174
  if not sf:
175
  return "Salesforce connection not established."
 
188
  gr.Markdown("# 🤖 Advanced Salesforce AI Code Review & Chatbot")
189
 
190
  with gr.Tab("Code Review"):
191
+ code_input = gr.Textbox(label="Apex / LWC Code", lines=8, placeholder="Enter your Apex or LWC code here")
192
  issue_type = gr.Textbox(label="Issue Type")
193
  suggestion = gr.Textbox(label="AI Suggestion")
194
  severity = gr.Textbox(label="Severity")
 
196
  code_button.click(analyze_code, inputs=code_input, outputs=[issue_type, suggestion, severity])
197
 
198
  with gr.Tab("Metadata Validation"):
199
+ metadata_input = gr.Textbox(label="Metadata XML", lines=8, placeholder="Enter your metadata XML here")
200
  mtype = gr.Textbox(label="Type")
201
  issue = gr.Textbox(label="Issue")
202
  recommendation = gr.Textbox(label="Recommendation")
 
205
 
206
  with gr.Tab("Salesforce Chatbot"):
207
  chatbot_output = gr.Chatbot(label="Conversation History", height=400)
208
+ query_input = gr.Textbox(label="Your Question", placeholder="e.g., How do I bulkify an Apex trigger?")
209
  with gr.Row():
210
  chatbot_button = gr.Button("Ask")
211
  clear_button = gr.Button("Clear Chat")
 
213
 
214
  def update_chatbot(query, chat_history):
215
  if not query.strip():
216
+ return chat_history, "Please enter a valid question."
217
  response = salesforce_chatbot(query, chat_history)
218
  chat_history.append((query, response))
219
  return chat_history, ""
 
227
  clear_button.click(fn=clear_chat, inputs=None, outputs=[chatbot_output, query_input])
228
 
229
  with gr.Tab("Create Salesforce Record"):
230
+ gr.Markdown("### 📇 Manually Create Salesforce Record")
231
  object_type = gr.Textbox(label="Object API Name", placeholder="e.g., Account")
232
  field_name = gr.Textbox(label="Field API Name", placeholder="e.g., Name")
233
  field_value = gr.Textbox(label="Field Value", placeholder="e.g., Test Company")