Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,18 +1,135 @@
|
|
| 1 |
-
|
| 2 |
import random
|
| 3 |
import gradio as gr
|
| 4 |
from datetime import datetime
|
| 5 |
from transformers import pipeline
|
| 6 |
from simple_salesforce import Salesforce, SalesforceLogin, SFType
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
#
|
| 9 |
-
|
| 10 |
-
# ---------- Salesforce Connection Setup ----------
|
| 11 |
-
# Replace these with your actual Salesforce credentials or use environment variables for security
|
| 12 |
-
SF_USERNAME = "your_username@example.com"
|
| 13 |
-
SF_PASSWORD = "your_password"
|
| 14 |
-
SF_SECURITY_TOKEN = "your_security_token"
|
| 15 |
-
|
| 16 |
try:
|
| 17 |
session_id, instance = SalesforceLogin(
|
| 18 |
username=SF_USERNAME,
|
|
@@ -25,59 +142,51 @@ except Exception as e:
|
|
| 25 |
sf = None
|
| 26 |
print(f"❌ Failed to connect to Salesforce: {e}")
|
| 27 |
|
| 28 |
-
# ----------
|
| 29 |
def create_salesforce_record(object_type, field_name, field_value):
|
| 30 |
if not sf:
|
| 31 |
return "Salesforce connection not established."
|
| 32 |
-
|
| 33 |
try:
|
| 34 |
sobject = SFType(object_type, sf.session_id, sf.sf_instance)
|
| 35 |
result = sobject.create({field_name: field_value})
|
| 36 |
if result.get("success"):
|
| 37 |
-
return f"✅ Record created
|
| 38 |
else:
|
| 39 |
return f"❌ Failed to create record: {result}"
|
| 40 |
except Exception as e:
|
| 41 |
return f"⚠️ Error: {str(e)}"
|
| 42 |
|
| 43 |
-
# [Your existing functions: analyze_code, validate_metadata, salesforce_chatbot, etc. remain unchanged]
|
| 44 |
-
|
| 45 |
# ---------- Gradio UI ----------
|
| 46 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 47 |
gr.Markdown("# 🤖 Advanced Salesforce AI Code Review & Chatbot")
|
| 48 |
|
| 49 |
-
# Tab 1: Code Review
|
| 50 |
with gr.Tab("Code Review"):
|
| 51 |
-
code_input = gr.Textbox(label="Apex / LWC Code", lines=8, placeholder="Enter
|
| 52 |
issue_type = gr.Textbox(label="Issue Type")
|
| 53 |
suggestion = gr.Textbox(label="AI Suggestion")
|
| 54 |
severity = gr.Textbox(label="Severity")
|
| 55 |
code_button = gr.Button("Analyze Code")
|
| 56 |
code_button.click(analyze_code, inputs=code_input, outputs=[issue_type, suggestion, severity])
|
| 57 |
|
| 58 |
-
# Tab 2: Metadata Validation
|
| 59 |
with gr.Tab("Metadata Validation"):
|
| 60 |
-
metadata_input = gr.Textbox(label="Metadata XML", lines=8
|
| 61 |
mtype = gr.Textbox(label="Type")
|
| 62 |
issue = gr.Textbox(label="Issue")
|
| 63 |
recommendation = gr.Textbox(label="Recommendation")
|
| 64 |
metadata_button = gr.Button("Validate Metadata")
|
| 65 |
metadata_button.click(validate_metadata, inputs=metadata_input, outputs=[mtype, issue, recommendation])
|
| 66 |
|
| 67 |
-
# Tab 3: Salesforce Chatbot
|
| 68 |
with gr.Tab("Salesforce Chatbot"):
|
| 69 |
-
gr.Markdown("### Ask a Salesforce Question\nGet expert answers on Apex, SOQL, LWC, and more!")
|
| 70 |
chatbot_output = gr.Chatbot(label="Conversation History", height=400)
|
| 71 |
-
query_input = gr.Textbox(label="Your Question"
|
| 72 |
with gr.Row():
|
| 73 |
chatbot_button = gr.Button("Ask")
|
| 74 |
clear_button = gr.Button("Clear Chat")
|
| 75 |
-
|
| 76 |
chat_state = gr.State(value=[])
|
| 77 |
|
| 78 |
def update_chatbot(query, chat_history):
|
| 79 |
if not query.strip():
|
| 80 |
-
return chat_history, "Please enter a
|
| 81 |
response = salesforce_chatbot(query, chat_history)
|
| 82 |
chat_history.append((query, response))
|
| 83 |
return chat_history, ""
|
|
@@ -90,17 +199,14 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 90 |
chatbot_button.click(fn=update_chatbot, inputs=[query_input, chat_state], outputs=[chatbot_output, query_input])
|
| 91 |
clear_button.click(fn=clear_chat, inputs=None, outputs=[chatbot_output, query_input])
|
| 92 |
|
| 93 |
-
# Tab 4: Create Salesforce Record
|
| 94 |
with gr.Tab("Create Salesforce Record"):
|
| 95 |
gr.Markdown("### 📇 Create a New Salesforce Record")
|
| 96 |
-
object_type = gr.Textbox(label="
|
| 97 |
field_name = gr.Textbox(label="Field API Name", placeholder="e.g., Name")
|
| 98 |
field_value = gr.Textbox(label="Field Value", placeholder="e.g., Test Company")
|
| 99 |
create_button = gr.Button("Create Record")
|
| 100 |
record_result = gr.Textbox(label="Result")
|
| 101 |
-
|
| 102 |
create_button.click(create_salesforce_record, inputs=[object_type, field_name, field_value], outputs=record_result)
|
| 103 |
|
| 104 |
-
# ---------- Start UI ----------
|
| 105 |
if __name__ == "__main__":
|
| 106 |
demo.launch()
|
|
|
|
| 1 |
+
import os
|
| 2 |
import random
|
| 3 |
import gradio as gr
|
| 4 |
from datetime import datetime
|
| 5 |
from transformers import pipeline
|
| 6 |
from simple_salesforce import Salesforce, SalesforceLogin, SFType
|
| 7 |
+
from dotenv import load_dotenv
|
| 8 |
+
|
| 9 |
+
# ---------- Load Environment Variables ----------
|
| 10 |
+
load_dotenv()
|
| 11 |
+
SF_USERNAME = os.getenv("SF_USERNAME")
|
| 12 |
+
SF_PASSWORD = os.getenv("SF_PASSWORD")
|
| 13 |
+
SF_SECURITY_TOKEN = os.getenv("SF_SECURITY_TOKEN")
|
| 14 |
+
|
| 15 |
+
# ---------- Label Mapping ----------
|
| 16 |
+
label_to_issue_type = {
|
| 17 |
+
"LABEL_0": "Performance",
|
| 18 |
+
"LABEL_1": "Error",
|
| 19 |
+
"LABEL_2": "Security",
|
| 20 |
+
"LABEL_3": "Best Practice"
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
suggestions = {
|
| 24 |
+
"Performance": "Consider optimizing loops and database access. Use collections to reduce SOQL queries.",
|
| 25 |
+
"Error": "Add proper error handling and null checks. Use try-catch blocks effectively.",
|
| 26 |
+
"Security": "Avoid dynamic SOQL. Use binding variables to prevent SOQL injection.",
|
| 27 |
+
"Best Practice": "Refactor for readability and use bulk-safe patterns, such as processing records in batches."
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
severities = {
|
| 31 |
+
"Performance": "Medium",
|
| 32 |
+
"Error": "High",
|
| 33 |
+
"Security": "High",
|
| 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": "..."
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
# ---------- Load QnA Model ----------
|
| 48 |
+
try:
|
| 49 |
+
qa_pipeline = pipeline("text2text-generation", model="google/flan-t5-large")
|
| 50 |
+
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 ----------
|
| 78 |
+
def validate_metadata(metadata):
|
| 79 |
+
if not metadata.strip():
|
| 80 |
+
return "No metadata provided.", "", ""
|
| 81 |
+
mtype = "Field"
|
| 82 |
+
issue = "Unused field detected"
|
| 83 |
+
recommendation = "Remove it to improve performance or document its purpose."
|
| 84 |
+
log_data = {
|
| 85 |
+
"Name": f"MetadataLog_{mtype}",
|
| 86 |
+
"MetadataType": mtype,
|
| 87 |
+
"IssueDescription": issue,
|
| 88 |
+
"Recommendation": recommendation,
|
| 89 |
+
"Status": "Open"
|
| 90 |
+
}
|
| 91 |
+
log_to_console(log_data, "Metadata Validation")
|
| 92 |
+
return mtype, issue, recommendation
|
| 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:
|
| 106 |
+
conversation_history.append((query, kb_answer))
|
| 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")
|
| 128 |
+
return output
|
| 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,
|
|
|
|
| 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."
|
|
|
|
| 149 |
try:
|
| 150 |
sobject = SFType(object_type, sf.session_id, sf.sf_instance)
|
| 151 |
result = sobject.create({field_name: field_value})
|
| 152 |
if result.get("success"):
|
| 153 |
+
return f"✅ Record created in {object_type} with ID: {result['id']}"
|
| 154 |
else:
|
| 155 |
return f"❌ Failed to create record: {result}"
|
| 156 |
except Exception as e:
|
| 157 |
return f"⚠️ Error: {str(e)}"
|
| 158 |
|
|
|
|
|
|
|
| 159 |
# ---------- Gradio UI ----------
|
| 160 |
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")
|
| 168 |
code_button = gr.Button("Analyze Code")
|
| 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")
|
| 176 |
metadata_button = gr.Button("Validate Metadata")
|
| 177 |
metadata_button.click(validate_metadata, inputs=metadata_input, outputs=[mtype, issue, recommendation])
|
| 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")
|
|
|
|
| 185 |
chat_state = gr.State(value=[])
|
| 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, ""
|
|
|
|
| 199 |
chatbot_button.click(fn=update_chatbot, inputs=[query_input, chat_state], outputs=[chatbot_output, query_input])
|
| 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")
|
| 207 |
create_button = gr.Button("Create Record")
|
| 208 |
record_result = gr.Textbox(label="Result")
|
|
|
|
| 209 |
create_button.click(create_salesforce_record, inputs=[object_type, field_name, field_value], outputs=record_result)
|
| 210 |
|
|
|
|
| 211 |
if __name__ == "__main__":
|
| 212 |
demo.launch()
|