saikumar27 commited on
Commit
7ed7cb4
Β·
verified Β·
1 Parent(s): 7dac154

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -19
app.py CHANGED
@@ -2,18 +2,24 @@ import streamlit as st
2
  import google.generativeai as genai
3
  import re
4
 
5
- # Configure API key
6
  api_key = st.secrets["GOOGLE_API_KEY"]
7
  genai.configure(api_key=api_key)
8
 
9
- # System instruction for AI
10
- system_prompt = """You are a Python code reviewer. Provide feedback on code quality, best practices, and improvements."""
 
 
 
 
 
11
 
12
- # Load the AI model
13
  model = genai.GenerativeModel(model_name="models/gemini-2.0-flash-exp", system_instruction=system_prompt)
14
 
 
15
  def review_code(user_code):
16
- """Function to review Python code using Gemini AI."""
17
  try:
18
  response = model.generate_content(user_code)
19
  if hasattr(response, "text"):
@@ -21,37 +27,43 @@ def review_code(user_code):
21
  elif hasattr(response, "candidates") and response.candidates:
22
  return response.candidates[0].text.strip()
23
  else:
24
- return "Error: Unexpected response format."
25
  except Exception as e:
26
- st.error("An error occurred during code review. Check logs for details.")
27
  st.exception(e)
28
  return None
29
 
30
  # Streamlit UI
31
  st.title("πŸ“’ AI Code Reviewer")
32
- st.write("Enter your Python code below and receive AI-powered feedback.")
33
 
34
  # Text area for user input
35
- user_code = st.text_area("Python Code:", height=200, placeholder="Write or paste your Python code here...")
 
 
 
 
36
 
37
- if st.button("Generate Review") and user_code:
38
  if not user_code.strip():
39
  st.warning("⚠️ Please enter some Python code to review.")
40
  st.stop()
41
 
42
- with st.spinner("Analyzing your code..."):
43
  feedback = review_code(user_code)
44
 
45
  if feedback:
46
- # Using regex to extract code blocks properly
47
- code_blocks = re.split(r'```python|```', feedback)
48
-
49
  with st.expander("πŸ’‘ AI Review Feedback", expanded=True):
50
  for block in code_blocks:
51
- if block.strip():
52
- if "def " in block or "import " in block or "=" in block: # Rough check for code
53
- st.code(block.strip(), language="python")
 
 
54
  else:
55
- st.write(block.strip())
56
  else:
57
- st.error("🚨 Code review failed. Please check your input or try again.")
 
2
  import google.generativeai as genai
3
  import re
4
 
5
+ # Configure API Key
6
  api_key = st.secrets["GOOGLE_API_KEY"]
7
  genai.configure(api_key=api_key)
8
 
9
+ # System Instruction for AI Code Review
10
+ system_prompt = """You are a Python code reviewer. Provide feedback on:
11
+ - Code quality and best practices.
12
+ - Performance optimizations.
13
+ - Readability and maintainability.
14
+ - Security improvements.
15
+ Return formatted responses with clear explanations and Python code blocks when needed."""
16
 
17
+ # Load AI Model
18
  model = genai.GenerativeModel(model_name="models/gemini-2.0-flash-exp", system_instruction=system_prompt)
19
 
20
+ @st.cache_resource
21
  def review_code(user_code):
22
+ """Function to review Python code using Gemini AI with caching."""
23
  try:
24
  response = model.generate_content(user_code)
25
  if hasattr(response, "text"):
 
27
  elif hasattr(response, "candidates") and response.candidates:
28
  return response.candidates[0].text.strip()
29
  else:
30
+ return "❌ Error: Unexpected response format."
31
  except Exception as e:
32
+ st.error("🚨 An error occurred during code review.")
33
  st.exception(e)
34
  return None
35
 
36
  # Streamlit UI
37
  st.title("πŸ“’ AI Code Reviewer")
38
+ st.write("πŸ” Enter your Python code below and receive AI-powered feedback.")
39
 
40
  # Text area for user input
41
+ user_code = st.text_area(
42
+ "πŸ“ Python Code:",
43
+ height=200,
44
+ placeholder="Write or paste your Python code here..."
45
+ )
46
 
47
+ if st.button("πŸš€ Generate Review") and user_code:
48
  if not user_code.strip():
49
  st.warning("⚠️ Please enter some Python code to review.")
50
  st.stop()
51
 
52
+ with st.spinner("πŸ€– Analyzing your code..."):
53
  feedback = review_code(user_code)
54
 
55
  if feedback:
56
+ # Extract Python code blocks and explanations using regex
57
+ code_blocks = re.split(r'```python|```', feedback, flags=re.IGNORECASE)
58
+
59
  with st.expander("πŸ’‘ AI Review Feedback", expanded=True):
60
  for block in code_blocks:
61
+ cleaned_block = block.strip()
62
+ if cleaned_block:
63
+ # Check if the block is code or text
64
+ if re.search(r'\b(def |import |=|return )', cleaned_block): # Detects Python code
65
+ st.code(cleaned_block, language="python")
66
  else:
67
+ st.write(cleaned_block)
68
  else:
69
+ st.error("❌ Code review failed. Please check your input or try again.")