sharmapacific commited on
Commit
e930a2d
1 Parent(s): 81cbca8

Added the complete App

Browse files
Files changed (2) hide show
  1. app.py +143 -0
  2. requirements.txt +11 -0
app.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import google.generativeai as palm
2
+ import gradio as gr
3
+ from pygments import highlight
4
+ from pygments.lexers import get_lexer_by_name
5
+ from pygments.formatters import HtmlFormatter
6
+ import os
7
+ from dotenv import load_dotenv
8
+ import ast
9
+
10
+ # Load environment variables from .env file
11
+ load_dotenv()
12
+
13
+ # Configure the API key
14
+ api_key = os.getenv('Palm_Key')
15
+ palm.configure(api_key=api_key)
16
+
17
+ # List and select the model
18
+ models = [m for m in palm.list_models() if 'generateText' in m.supported_generation_methods]
19
+ model = models[0].name
20
+
21
+ # Function to highlight code
22
+ def format_code_with_syntax_highlighting(code, language):
23
+ try:
24
+ lexer = get_lexer_by_name(language.lower())
25
+ except Exception as e:
26
+ return f"Error in syntax highlighting: {e}"
27
+
28
+ formatter = HtmlFormatter()
29
+ return highlight(code, lexer, formatter)
30
+
31
+ # Define code quality metrics function
32
+ def calculate_code_quality_metrics(code):
33
+ try:
34
+ tree = ast.parse(code)
35
+ num_lines = len(code.splitlines())
36
+ num_nodes = len(list(ast.walk(tree)))
37
+ num_functions = sum(isinstance(node, ast.FunctionDef) for node in ast.walk(tree))
38
+ cyclomatic_complexity = num_functions * 2
39
+
40
+ metrics = {
41
+ "Number of Lines": num_lines,
42
+ "Number of AST Nodes": num_nodes,
43
+ "Number of Functions": num_functions,
44
+ "Cyclomatic Complexity (Approximate)": cyclomatic_complexity
45
+ }
46
+ return metrics
47
+ except Exception as e:
48
+ return f"Error in analyzing code quality: {e}"
49
+
50
+ # Enhanced example explanations
51
+ sample_code_explanations = """
52
+ ----------------------------
53
+ Example 1: Python Code Snippet
54
+ def multiply_elements(lst, factor):
55
+ return [x * factor for x in lst]
56
+
57
+ numbers = [1, 2, 3, 4]
58
+ result = multiply_elements(numbers, 3)
59
+ print(result)
60
+ Correct output: [3, 6, 9, 12]
61
+ Code Explanation: The function `multiply_elements` multiplies each element in the list `lst` by the given `factor`. The list comprehension `[x * factor for x in lst]` creates a new list with each element multiplied by `factor`. In this case, each number in `numbers` is multiplied by `3`, resulting in `[3, 6, 9, 12]`.
62
+ -----------------------------
63
+
64
+ Example 2: Python Code Snippet
65
+ def filter_even_numbers(nums):
66
+ return [num for num in nums if num % 2 == 0]
67
+
68
+ values = [10, 15, 20, 25, 30]
69
+ filtered = filter_even_numbers(values)
70
+ print(filtered)
71
+ Correct output: [10, 20, 30]
72
+ Code Explanation: The function `filter_even_numbers` filters out the odd numbers from the list `nums`, returning only the even numbers. The list comprehension `[num for num in nums if num % 2 == 0]` includes only numbers divisible by `2`. Thus, from the list `values`, the even numbers `[10, 20, 30]` are returned.
73
+ ------------------------------
74
+ """
75
+
76
+
77
+ def generate_completion(code_section, language, detail_depth, req_type):
78
+ prompt = f"""
79
+ Your task is to act as a {language} Code {req_type}.
80
+ I'll give you a Code Snippet.
81
+ Your job is to {('explain the Code Snippet step-by-step' if req_type == 'Explainer' else 'provide refactoring suggestions and improvements' if req_type == 'Refactoring' else 'generate unit test cases for the code' if req_type == 'Unit Test Cases' else 'provide code quality metrics')}.
82
+ Break down the code into as many steps as possible.
83
+ Share intermediate checkpoints & steps along with results.
84
+ Explanation detail level: {detail_depth}
85
+ Few good examples of {language} code output between #### separator:
86
+ ####
87
+ {sample_code_explanations}
88
+ ####
89
+ Code Snippet is shared below, delimited with triple backticks:
90
+ ```
91
+ {code_section}
92
+ ```
93
+ """
94
+
95
+ try:
96
+ completion = palm.generate_text(
97
+ model=model,
98
+ prompt=prompt,
99
+ temperature=0,
100
+ max_output_tokens=500,
101
+ )
102
+ response = completion.result
103
+ if not response:
104
+ return "Unable to generate output. Try a different code snippet"
105
+ return response
106
+ except Exception as e:
107
+ return f"An error occurred: {e}"
108
+
109
+ # Custom processing function to add syntax highlighting
110
+ def process_function(code_section, language, detail_depth, req_type):
111
+ if req_type == "Code Quality Metrics":
112
+ metrics = calculate_code_quality_metrics(code_section)
113
+ formatted_code = format_code_with_syntax_highlighting(code_section, language)
114
+ return formatted_code, metrics
115
+ else:
116
+ response = generate_completion(code_section, language, detail_depth, req_type)
117
+ formatted_code = format_code_with_syntax_highlighting(code_section, language)
118
+ return formatted_code, response
119
+
120
+ # Define app UI with Gradio
121
+ iface = gr.Interface(
122
+ fn=process_function,
123
+ inputs=[
124
+ gr.Textbox(label="Insert Code Snippet", lines=10, placeholder="Paste your code snippet here..."),
125
+ gr.Dropdown(label="Select Programming Language", choices=["python", "java", "javascript"], value="python"),
126
+ gr.Radio(label="Explanation Detail Level", choices=["Brief", "Detailed"], value="Detailed"),
127
+ gr.Radio(label="Request Type", choices=["Explainer", "Refactoring", "Unit Test Cases", "Code Quality Metrics"], value="Explainer")
128
+ ],
129
+ outputs=[
130
+ gr.HTML(label="Formatted Code Snippet"),
131
+ gr.Textbox(label="Response", lines=20)
132
+ ],
133
+ title="Code Explainer, Refactoring Suggestions, Unit Test Cases Generator and Code Quality Metrics using Palm model",
134
+ description="Paste a code snippet, select the programming language, explanation detail level, and request type",
135
+ examples=[
136
+ ["x = [1,2,3,4,5]\ny = [i*i for i in x if i%2==0]\nprint(y)", "python", "Detailed", "Explainer"],
137
+ ["import math\n\n" "def calculate_area(radius):\n" " return math.pi * radius * radius\n\n" "radius_list = [3, 5, 7]\n" "area_list = list(map(calculate_area, radius_list))\n" "print(area_list)", "python", "Detailed", "Refactoring"],
138
+ ["def add(a, b):\n return a + b", "python", "Detailed", "Unit Test Cases"],
139
+ ["def add(a, b):\n return a + b", "python", "Detailed", "Code Quality Metrics"]
140
+ ]
141
+ )
142
+
143
+ iface.launch(share=True, debug=True)
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ google-generativeai==0.1.0
2
+ gradio==3.5.0
3
+ requests==2.28.2
4
+ numpy==1.25.0
5
+ pandas==2.0.3
6
+ pytest==7.4.0
7
+ flake8==6.0.0
8
+ radon==6.0.1
9
+ python-dotenv
10
+ pygments
11
+ httpx==0.23.0