imkhan107 commited on
Commit
692bd71
·
1 Parent(s): 62c8baf

added more features

Browse files
Files changed (4) hide show
  1. app.py +17 -3
  2. gemini.py +7 -3
  3. handler.py +54 -11
  4. prompts.py +118 -24
app.py CHANGED
@@ -1,4 +1,5 @@
1
  import streamlit as st
 
2
  from handler import *
3
 
4
  def main():
@@ -18,16 +19,29 @@ def main():
18
  with col2:
19
  # Radio buttons for analysis type
20
  analysis_type = st.radio("Choose analysis type:",
21
- ("Code review", "Code refinement", "Unit tests"))
22
 
23
  # Submit button
24
  if st.button("Submit"):
25
  # Process the code and prompt based on analysis_type (implementation omitted for brevity)
26
  if analysis_type == "Code review":
27
- res=code_review(code, prompt)
28
  #st.text_area(label="Result",value=res, height=300)
29
  st.markdown(res)
30
- st.success(f"Code analysis for {analysis_type} submitted successfully!")
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
  if __name__ == "__main__":
33
  main()
 
1
  import streamlit as st
2
+ import time
3
  from handler import *
4
 
5
  def main():
 
19
  with col2:
20
  # Radio buttons for analysis type
21
  analysis_type = st.radio("Choose analysis type:",
22
+ ("Code review", "Code refinement","Documentation", "Unit tests"))
23
 
24
  # Submit button
25
  if st.button("Submit"):
26
  # Process the code and prompt based on analysis_type (implementation omitted for brevity)
27
  if analysis_type == "Code review":
28
+ res=review_code(code, prompt)
29
  #st.text_area(label="Result",value=res, height=300)
30
  st.markdown(res)
31
+ time.sleep(1)
32
+ #st.markdown("Hello ooo")
33
+
34
+ elif analysis_type == "Code refinement":
35
+ res=refine_code(code, prompt)
36
+ #st.text_area(label="Result",value=res, height=300)
37
+ st.markdown(res)
38
+
39
+ elif analysis_type == "Documentation":
40
+ res=generate_documentation(code, prompt)
41
+ #st.text_area(label="Result",value=res, height=300)
42
+ st.markdown(res)
43
+
44
+ st.success(f"Code analysis for {analysis_type} submitted successfully!")
45
 
46
  if __name__ == "__main__":
47
  main()
gemini.py CHANGED
@@ -7,8 +7,8 @@ generation_config=genai.types.GenerationConfig(
7
  # Only one candidate for now.
8
  #candidate_count=1,
9
  #stop_sequences=['x'],
10
- #max_output_tokens=1024,
11
- temperature=1.0
12
  )
13
  class GeminiModel:
14
  """
@@ -35,7 +35,11 @@ class GeminiModel:
35
  def execute(self, prompt: str) -> str:
36
 
37
  try:
38
- response = self.model.generate_content(prompt, generation_config=None)
 
 
 
 
39
  return response.text
40
  except Exception as e:
41
  return f"An error occurred: {e}"
 
7
  # Only one candidate for now.
8
  #candidate_count=1,
9
  #stop_sequences=['x'],
10
+ max_output_tokens=4096,
11
+ temperature=0.1
12
  )
13
  class GeminiModel:
14
  """
 
35
  def execute(self, prompt: str) -> str:
36
 
37
  try:
38
+ total_tokens = self.model.count_tokens(prompt).total_tokens
39
+ print(f"Input tokens: {total_tokens}")
40
+ response = self.model.generate_content(prompt, generation_config=generation_config)
41
+ output_tokens = self.model.count_tokens(response.text).total_tokens
42
+ print(f"Output tokens: {output_tokens}")
43
  return response.text
44
  except Exception as e:
45
  return f"An error occurred: {e}"
handler.py CHANGED
@@ -1,19 +1,62 @@
1
- from gemini import GeminiModel
2
  from prompts import *
3
 
 
 
 
4
 
5
- def code_review(code,c_prompt=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- if code is None or len(code)< 5 or code.isspace():
8
- return "No Code Provided"
9
-
10
  if c_prompt is not None and len(c_prompt) > 30:
11
- prompt=custom_prompt(code.strip(),c_prompt.strip())
12
  else:
13
- prompt=default_gemini_prompt(code.strip())
14
-
15
-
16
- model=GeminiModel()
17
- res= model.execute(prompt)
 
 
 
 
18
  return res
 
 
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gemini
2
  from prompts import *
3
 
4
+ def review_code(code, c_prompt=None):
5
+ if code is None or len(code) < 5 or code.isspace():
6
+ raise InvalidCodeException("No code provided")
7
 
8
+ if c_prompt is not None and len(c_prompt) > 30:
9
+ prompt = custom_review_prompt(code.strip(), c_prompt.strip())
10
+ else:
11
+ #prompt = validation_prompt(code.strip())
12
+ prompt = default_review_prompt1(code.strip())
13
+
14
+ model = gemini.GeminiModel()
15
+ try:
16
+ res = model.execute(prompt)
17
+ except Exception as e:
18
+ raise CodeReviewException(str(e))
19
+
20
+ return res
21
+
22
+ def refine_code(code, c_prompt=None):
23
+ if code is None or len(code) < 5 or code.isspace():
24
+ raise InvalidCodeException("No code provided")
25
 
 
 
 
26
  if c_prompt is not None and len(c_prompt) > 30:
27
+ prompt = custom_review_prompt(code.strip(), c_prompt.strip())
28
  else:
29
+ #prompt = validation_prompt(code.strip())
30
+ prompt = default_refine_prompt(code.strip())
31
+
32
+ model = gemini.GeminiModel()
33
+ try:
34
+ res = model.execute(prompt)
35
+ except Exception as e:
36
+ raise CodeReviewException(str(e))
37
+
38
  return res
39
+
40
+ def generate_documentation(code,c_prompt):
41
 
42
+ if code is None or len(code) < 5 or code.isspace():
43
+ raise InvalidCodeException("No code provided")
44
+
45
+ if c_prompt is not None and len(c_prompt) > 30:
46
+ prompt = custom_review_prompt(code.strip(), c_prompt.strip())
47
+ else:
48
+ prompt = default_doc_prompt(code.strip())
49
+
50
+ model = gemini.GeminiModel()
51
+ try:
52
+ res = model.execute(prompt)
53
+ except Exception as e:
54
+ raise CodeReviewException(str(e))
55
+
56
+ return res
57
+
58
+ class InvalidCodeException(Exception):
59
+ pass
60
+
61
+ class CodeReviewException(Exception):
62
+ pass
prompts.py CHANGED
@@ -1,5 +1,7 @@
1
- TASK="As an experienced software developer responsible for code review and feedback, review the following python code by considering the best practices given in the guidelines below and provide your Observations and Suggestions."
2
- INSTRUCTIONS="""Take a deep breath before providing the feedback and thoroughly understand the code logic.
 
 
3
  Avoid verbosity and repetition in your feedback, focussing on essential points and offering valuable suggestions.
4
  Add your own observations and suggestions as needed, and only include comments that are neccessary for clarity and improvement.
5
  If you have specific code suggestions, ensure they are correct and aligned with the best practices.
@@ -33,18 +35,18 @@ Race conditions have been handled
33
  Locks are acquired and released in the right order to prevent deadlocks, even in error handling code.
34
  All methods are commented in clear language
35
  """
36
-
37
  STEPS="""Follow the steps in the same order:
38
  1. Understand the code logic and structure.
39
- 2. Notedown the observations based on the guodelines given above.
40
  3. Give suggestions for improving the code.
41
  4. Give an example of Final improved code.
42
  """
43
 
44
- def default_gemini_prompt(code, guidelines=None):
45
  if guidelines is None:
46
  guidelines=GUIDELINES
47
- prompt=f"""<Task>: {TASK}
48
  <Instructions>: {INSTRUCTIONS}
49
 
50
  <Guidelines>: {guidelines}
@@ -57,34 +59,126 @@ def default_gemini_prompt(code, guidelines=None):
57
  return prompt
58
 
59
 
60
- def prompt2(code):
61
- prompt=f"""
62
- <task>: As an experienced software developer responsible for code review and feedback, review the following code by considering the best practices given in the guidelines below and provide your Observations and Suggestions
63
- Code: {code}
64
 
65
- The following custom guidelines should be considered during the review:
 
 
 
 
 
 
 
66
 
67
- {GUIDELINES}
68
 
69
- Starting from the beginning of the code, analyze each line following a chain of thoughts. Consider the purpose of the code, its readability, efficiency, and adherence to the listed custom guidelines.
70
 
71
- For each line, provide feedback that includes:
 
72
 
73
- * Whether the code achieves its intended purpose.
74
- * If there are any readability issues or areas for improvement.
75
- * Suggestions for optimization or alternative approaches (if applicable).
76
- * If there are any violations of the custom guidelines.
77
 
78
- Break down your review into a step-by-step process, explaining your reasoning at each point. Maintain a clear and concise tone throughout the review.
79
- Add your own observations and suggestions as needed, and only include comments that are neccessary for clarity and improvement.
80
- If you have specific code suggestions, ensure they are correct and aligned with the best practices
81
 
82
- **Overall Recommendation:**
83
 
84
- Based on your analysis, provide an overall recommendation for the code. This could be approval with minor suggestions, approval with moderate changes, or rejection with a clear explanation for required improvements.
85
  """
86
 
87
  return prompt
88
 
89
- def custom_prompt(c_prompt,code):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  return f'{c_prompt}\n<Code>: {code}'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ROLE="You are an experienced python software developer responsible for code review and feedback."
2
+ TASK="Review the following python code by considering the best practices given in the guidelines below and provide your Observations and Suggestions."
3
+ INSTRUCTIONS="""Identify the code. If no code is present then say 'No code given'.
4
+ Take a deep breath before providing the feedback and thoroughly understand the code logic.
5
  Avoid verbosity and repetition in your feedback, focussing on essential points and offering valuable suggestions.
6
  Add your own observations and suggestions as needed, and only include comments that are neccessary for clarity and improvement.
7
  If you have specific code suggestions, ensure they are correct and aligned with the best practices.
 
35
  Locks are acquired and released in the right order to prevent deadlocks, even in error handling code.
36
  All methods are commented in clear language
37
  """
38
+ #First check whether the given input contains any code snippet or not.
39
  STEPS="""Follow the steps in the same order:
40
  1. Understand the code logic and structure.
41
+ 2. Notedown the observations based on the guidelines given above.
42
  3. Give suggestions for improving the code.
43
  4. Give an example of Final improved code.
44
  """
45
 
46
+ def default_review_prompt1(code, guidelines=None):
47
  if guidelines is None:
48
  guidelines=GUIDELINES
49
+ prompt=f"""<Task>: {ROLE} {TASK}
50
  <Instructions>: {INSTRUCTIONS}
51
 
52
  <Guidelines>: {guidelines}
 
59
  return prompt
60
 
61
 
62
+ def default_review_prompt2(code):
 
 
 
63
 
64
+ prompt=f"""<Task>: {ROLE} {TASK}
65
+ <Intsructions>: Analyze the provided code and identify the key components (classes, functions, modules).
66
+ 1. Analyze each key component following chain of thoughts. Consider the purpose of the component, its readability, efficiency, and adherence to the listed custom guidelines.
67
+ 2. Break down your review into a step-by-step process, explaining your reasoning at each point. Maintain a clear and concise tone throughout the review.
68
+ 3. Add your own observations and suggestions as needed, and only include comments that are neccessary for clarity and improvement.
69
+ 4. Highlight serious violations.
70
+ 5. Give suggestions for improving the code.
71
+ 6. Give an example of Final improved code.
72
 
73
+ <Guidelines>: {GUIDELINES}
74
 
75
+ <Steps to follow>: {STEPS}
76
 
77
+ <code>: {code}
78
+ """
79
 
80
+ promptt=f"""
81
+ <task>: {ROLE} Review the following code by considering the best practices given in the guidelines below.
82
+ <Guidelines>: {GUIDELINES}
 
83
 
 
 
 
84
 
 
85
 
86
+ <Code>: {code}
87
  """
88
 
89
  return prompt
90
 
91
+ def default_review_prompt3(code):
92
+ prompt= f"""Conduct a comprehensive code review of the provided Python script, focusing on its structure, functionality, and adherence to best practices.\
93
+ The script is designed to automate a specific task, and your review should assess its efficiency, readability, and maintainability.
94
+
95
+ <Guidelines for the Code Review>:
96
+ - Understand the script: Check whether the script contains a python script or not.
97
+ - Structure and Organization: Evaluate the script's overall structure and organization. Is the code logically divided into functions or sections? Are there any redundant or unnecessary sections?
98
+ - Declare constants as applicable: Make sure constants are declared whenever applicable.
99
+ - Functionality and Correctness: Assess the script's functionality and correctness. Does it perform the intended task correctly? Are there any potential errors or edge cases that could cause issues?
100
+ - Readability and Code Quality: Evaluate the script's readability and code quality. Are the variable names descriptive and consistent? Are there any unnecessary comments or redundant code?
101
+ - Efficiency and Performance: Analyze the script's efficiency and performance. Are there any opportunities to optimize the code for better performance or reduce computational complexity?
102
+ - Best Practices and Conventions: Check the script's adherence to best practices and coding conventions. Are there any deviations from standard Python coding conventions or best practices?
103
+ - Error Handling and Debugging: Evaluate the script's error handling and debugging capabilities. Are there any try-except blocks or logging statements to handle potential errors?
104
+ - Code Duplication and Redundancy: Identify any duplicated or redundant code sections. Are there any opportunities to refactor the code to reduce duplication?
105
+ - Security and Vulnerabilities: Assess the script's security and potential vulnerabilities. Are there any sensitive data or user input handling that could lead to security issues?
106
+ - Documentation and Comments: Evaluate the script's documentation and comments. Are there any clear and concise comments explaining the code's purpose and functionality?
107
+ - Testing and Validation: Suggest any additional testing or validation steps to ensure the script's correctness and reliability.
108
+
109
+ <Deliverables>:
110
+ A detailed report summarizing the code review findings, including any suggestions for improvement.
111
+ A revised version of the script incorporating the recommended changes and improvements.
112
+
113
+ <Script>: {code}
114
+ """
115
+
116
+
117
+ return prompt
118
+
119
+
120
+ def custom_review_prompt(c_prompt,code):
121
  return f'{c_prompt}\n<Code>: {code}'
122
+
123
+ def default_refine_prompt(code):
124
+ prompt= f"""You are an expert software engineer and your task is to refine and optimize the code provided below while ensuring accuracy and functionality are maintained.
125
+ Please follow the guidelines on best practices outlined to refine the code's efficiency and readability.
126
+
127
+ <Guidelines on Best Practices>:
128
+ - Use Intention-Revealing Names
129
+ - Declare constants as applicable
130
+ - Don't Repeat Yourself (Avoid Duplication)
131
+ - Explain yourself in code
132
+ - Make sure the code formatting is applied
133
+ - Use Exceptions rather than Return codes
134
+ - Don't return Null
135
+ - Favor the use of standard exceptions
136
+ - Don't ignore exceptions
137
+ - Check parameters for validity
138
+ - Return empty arrays or collections, not nulls
139
+ - Minimize the accessibility of classes and members
140
+ - In public classes, use accessor methods, not public fields
141
+ - Minimize the scope of local variables
142
+ - Refer to objects by their interfaces
143
+ - Adhere to generally accepted naming conventions
144
+ - Avoid finalizers
145
+ - Synchronize access to shared mutable data
146
+ - Valid unit test cases exist
147
+ - Objects accessed by multiple threads are accessed only through a lock, or synchronized methods.
148
+ - Race conditions have been handled
149
+ - Locks are acquired and released in the right order to prevent deadlocks, even in error handling code.
150
+ - All methods are commented in clear language
151
+ - Use List Comprehension: Consider using list comprehension wherever possible.
152
+ - Error Handling: Implement error handling to handle cases where the input is invalid.
153
+ - Function Modularity: If possible, break down the code into smaller, more modular functions for better code organization.
154
+ - Docstrings: Include clear and concise docstrings to describe the purpose of functions and any parameters they accept.
155
+ - Variable Naming: Use descriptive variable names to improve code readability.
156
+ - Efficient Algorithms: Opt for efficient algorithms and data structures to improve performance where possible.
157
+ - Testing: Conduct thorough testing to ensure the optimized code produces the same results as the original.
158
+
159
+ Your expertise in refining and optimizing this code will greatly enhance its efficiency and maintain its functionality.
160
+
161
+ <Deliverables>:
162
+ A refined and optimized version of the code.
163
+
164
+ <Code>: {code}
165
+ """
166
+
167
+ return prompt
168
+
169
+
170
+ def default_doc_prompt(code):
171
+
172
+
173
+ prompt= f""""For the following python code:\n{code}\n"
174
+ "Generate proper formal documentation."
175
+ "The documentation should describe what the code does and explain the functionality."
176
+ "Include all details which should go in formal documentation"
177
+ """
178
+ return prompt
179
+
180
+ def validation_prompt(code, guidelines=None):
181
+ prompt=f"""Check if the below input contains code snippets or not. Return only Yes or NO and nothing else.
182
+ Input: {code}
183
+ """
184
+ return prompt