Bhanumani12 commited on
Commit
12c092b
·
verified ·
1 Parent(s): 85491dc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -109
app.py CHANGED
@@ -1,15 +1,4 @@
1
- import gradio as gr
2
- from transformers import pipeline
3
- from simple_salesforce import Salesforce
4
- import os
5
-
6
- # ---------- Salesforce Login ----------
7
- sf = Salesforce(
8
- username=os.getenv("SF_USERNAME"),
9
- password=os.getenv("SF_PASSWORD"),
10
- security_token=os.getenv("SF_SECURITY_TOKEN"),
11
- domain="login"
12
- )
13
 
14
  # ---------- Define Mapping for Model Labels ----------
15
  label_to_issue_type = {
@@ -19,108 +8,46 @@ label_to_issue_type = {
19
  "LABEL_3": "Best Practice"
20
  }
21
 
22
- # ---------- Load Model ----------
23
- code_analyzer = pipeline("text-classification", model="microsoft/codebert-base")
24
-
25
- # ---------- Code Analyzer Function ----------
26
  def analyze_code(code):
27
  if not code.strip():
28
  return "No code provided.", "", ""
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  try:
31
- result = code_analyzer(code)
32
- label = result[0]["label"].strip()
33
- issue_type = label_to_issue_type.get(label, "Error")
34
- suggestion = "Consider refactoring for better performance"
35
- severity = "Medium"
36
-
37
- try:
38
- sf.CodeReviewResult__c.create({
39
- "Name": f"Review_{issue_type}",
40
- "CodeSnippet__c": code,
41
- "IssueType__c": issue_type,
42
- "Suggestion__c": suggestion,
43
- "Severity__c": severity,
44
- })
45
- except Exception as sf_err:
46
- suggestion += f" (⚠️ Failed to log to Salesforce: {str(sf_err)})"
47
-
48
- return issue_type, suggestion, severity
49
-
50
- except Exception as e:
51
- return "Error", f"⚠️ Model failed: {str(e)}", "High"
52
-
53
- # ---------- Metadata Validator ----------
54
- def validate_metadata(metadata):
55
- if not metadata.strip():
56
- return "No metadata provided.", "", ""
57
-
58
- mtype = "Field"
59
- issue = "Unused field detected"
60
- recommendation = "Remove it to improve performance"
61
-
62
- try:
63
- sf.MetadataAuditLog__c.create({
64
- "Name": f"MetadataLog_{mtype}",
65
- "MetadataType__c": mtype,
66
- "IssueDescription__c": issue,
67
- "Recommendation__c": recommendation,
68
- "Status__c": "Open"
69
  })
70
  except Exception as e:
71
- recommendation += f" (⚠️ Failed to log to Salesforce: {str(e)})"
72
-
73
- return mtype, issue, recommendation
74
-
75
- # ---------- NLP Assistant (Flan-T5) ----------
76
- qa_pipeline = pipeline("text2text-generation", model="google/flan-t5-xl")
77
-
78
- def process_nlp_query(query):
79
- if not query.strip():
80
- return "No question provided."
81
-
82
- prompt = (
83
- "You are a certified Salesforce Apex expert. "
84
- "Answer the question below clearly and accurately using Salesforce best practices, terminology, and examples.\n\n"
85
- f"Question: {query.strip()}\n\nAnswer:"
86
- )
87
-
88
- try:
89
- result = qa_pipeline(
90
- prompt,
91
- max_new_tokens=256 # ✅ Fixed warning: avoids conflict with max_length
92
- )
93
-
94
- output = result[0]["generated_text"]
95
- return output.split("Answer:")[-1].strip() if "Answer:" in output else output.strip()
96
-
97
- except Exception as e:
98
- return f"⚠️ AI failed to respond: {str(e)}"
99
-
100
- # ---------- Gradio UI ----------
101
- with gr.Blocks() as demo:
102
- gr.Markdown("# 🤖 Salesforce AI Code Review & Q&A")
103
-
104
- with gr.Tab("Code Review"):
105
- code_input = gr.Textbox(label="Apex / LWC Code", lines=8)
106
- issue_type = gr.Textbox(label="Issue Type")
107
- suggestion = gr.Textbox(label="AI Suggestion")
108
- severity = gr.Textbox(label="Severity")
109
- code_button = gr.Button("Analyze Code")
110
- code_button.click(analyze_code, inputs=code_input, outputs=[issue_type, suggestion, severity])
111
-
112
- with gr.Tab("Metadata Validation"):
113
- metadata_input = gr.Textbox(label="Metadata XML", lines=8)
114
- mtype = gr.Textbox(label="Type")
115
- issue = gr.Textbox(label="Issue")
116
- recommendation = gr.Textbox(label="Recommendation")
117
- metadata_button = gr.Button("Validate Metadata")
118
- metadata_button.click(validate_metadata, inputs=metadata_input, outputs=[mtype, issue, recommendation])
119
-
120
- with gr.Tab("Ask AI (Natural Language)"):
121
- query_input = gr.Textbox(label="Your question", lines=2, placeholder="e.g. What is a trigger?")
122
- response_output = gr.Textbox(label="AI Response", lines=8)
123
- nlp_button = gr.Button("Ask")
124
- nlp_button.click(process_nlp_query, inputs=query_input, outputs=response_output)
125
 
126
- demo.launch()
 
1
+ import random
 
 
 
 
 
 
 
 
 
 
 
2
 
3
  # ---------- Define Mapping for Model Labels ----------
4
  label_to_issue_type = {
 
8
  "LABEL_3": "Best Practice"
9
  }
10
 
 
 
 
 
11
  def analyze_code(code):
12
  if not code.strip():
13
  return "No code provided.", "", ""
14
 
15
+ # --- Simulate classification labels for demo/testing ---
16
+ simulated_labels = ["LABEL_0", "LABEL_1", "LABEL_2", "LABEL_3"]
17
+ label = random.choice(simulated_labels)
18
+ issue_type = label_to_issue_type.get(label, "Error")
19
+
20
+ # Simulated suggestion/severity based on issue type
21
+ suggestions = {
22
+ "Performance": "Consider optimizing loops and database access.",
23
+ "Error": "Add proper error handling and null checks.",
24
+ "Security": "Avoid dynamic SOQL. Use binding variables.",
25
+ "Best Practice": "Refactor for readability and use bulk-safe patterns."
26
+ }
27
+ severities = {
28
+ "Performance": "Medium",
29
+ "Error": "High",
30
+ "Security": "High",
31
+ "Best Practice": "Low"
32
+ }
33
+
34
+ suggestion = suggestions.get(issue_type)
35
+ severity = severities.get(issue_type)
36
+
37
+ # Optional: Logging for debugging
38
+ print(f"[DEBUG] Label: {label} → Issue: {issue_type} | Severity: {severity}")
39
+
40
+ # Log to Salesforce
41
  try:
42
+ sf.CodeReviewResult__c.create({
43
+ "Name": f"Review_{issue_type}",
44
+ "CodeSnippet__c": code,
45
+ "IssueType__c": issue_type,
46
+ "Suggestion__c": suggestion,
47
+ "Severity__c": severity
48
+ # You can also add Developer__c here if needed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  })
50
  except Exception as e:
51
+ suggestion += f" (⚠️ Salesforce error: {str(e)})"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
+ return issue_type, suggestion, severity