Skip to content

Commit

Permalink
Fix code style issues with Black
Browse files Browse the repository at this point in the history
  • Loading branch information
lint-action committed Jul 7, 2024
1 parent 379abf7 commit 2e12c6d
Show file tree
Hide file tree
Showing 9 changed files with 100 additions and 73 deletions.
5 changes: 2 additions & 3 deletions app/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from .gemini_analyzer import CodeAnalyzer
__all__ = [
'CodeAnalyzer'
]

__all__ = ["CodeAnalyzer"]
80 changes: 43 additions & 37 deletions app/gemini_analyzer.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,41 @@
import google.generativeai as genai
from typing import Optional, Union, TypedDict

#for logging
# for logging
import structlog

structlog.stdlib.recreate_defaults()
log = structlog.get_logger(__name__).info(f"module loaded successfully.")


class CodeAnalyzer:
def __init__(self) -> None:
from .gemini_config import AnalyzerConfigs, ResponseData #prevent circular import

self.language: str[Optional] = "python"
self.style_guide: str[Optional] = "google official"
self.gemini_model = genai.GenerativeModel(
AnalyzerConfigs.gemini_models[1],
generation_config={
"response_mime_type": "application/json",
"response_schema": list[ResponseData]
}
)
self._gen_ai_config = genai.configure(api_key=AnalyzerConfigs.genai_api_key)
self._input_code: str = None
self._prompt: str = None
self._response: Union[list, None] = None
self._logger = structlog.get_logger("CodeAnalyzer")

def analyze_code(self) -> Union[list, None]:
'''
This method analyzes the input code and generates a style guide using the Gemini model.
'''
try:
prompt = f"""Analyze the following {self.language} code according to {self.style_guide} style guidelines:
def __init__(self) -> None:
from .gemini_config import (
AnalyzerConfigs,
ResponseData,
) # prevent circular import

self.language: str[Optional] = "python"
self.style_guide: str[Optional] = "google official"
self.gemini_model = genai.GenerativeModel(
AnalyzerConfigs.gemini_models[1],
generation_config={
"response_mime_type": "application/json",
"response_schema": list[ResponseData],
},
)
self._gen_ai_config = genai.configure(api_key=AnalyzerConfigs.genai_api_key)
self._input_code: str = None
self._prompt: str = None
self._response: Union[list, None] = None
self._logger = structlog.get_logger("CodeAnalyzer")

def analyze_code(self) -> Union[list, None]:
"""
This method analyzes the input code and generates a style guide using the Gemini model.
"""
try:
prompt = f"""Analyze the following {self.language} code according to {self.style_guide} style guidelines:
```{self.language}
{self._input_code}
Expand All @@ -44,17 +48,19 @@ def analyze_code(self) -> Union[list, None]:
3. Prioritize Only the most critical issues for readability and maintainability.
"""

model = self.gemini_model
response = model.generate_content(prompt)
model = self.gemini_model
response = model.generate_content(prompt)

# Extract and format the style guide from the response
# You will need to implement parsing logic here based on Gemini's response format

# Extract and format the style guide from the response
# You will need to implement parsing logic here based on Gemini's response format
style_guide = (
response.text
) # Adjust this based on the actual response structure
self._logger.info("Style guide generated successfully.")
# self._logger.info(style_guide)
return style_guide

style_guide = response.text # Adjust this based on the actual response structure
self._logger.info("Style guide generated successfully.")
#self._logger.info(style_guide)
return style_guide

except Exception as e:
self._logger.error(f"Error generating style guide: {e}")
return None
except Exception as e:
self._logger.error(f"Error generating style guide: {e}")
return None
36 changes: 25 additions & 11 deletions app/gemini_config.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,39 @@
import os
import streamlit as st
from typing_extensions import TypedDict


class AnalyzerConfigs:
'''
"""
This class contains configuration settings for the CodeAnalyzer class.
'''
"""

gemini_models: list = [
"gemini-1.5-flash",
"gemini-1.5-pro", #INFO : https://ai.google.dev/gemini-api/docs/json-mode?lang=python
"gemini-1.5-flash",
"gemini-1.5-pro", # INFO : https://ai.google.dev/gemini-api/docs/json-mode?lang=python
]
famous_languages: list = [
"Python",
"Java",
"JavaScript",
"C++",
"C#",
"Ruby",
"Go",
"Swift",
"Rust",
]
famous_languages: list = ["Python", "Java", "JavaScript", "C++", "C#", "Ruby", "Go", "Swift", "Rust"]
genai_api_key: str = st.secrets["GENAI_API_KEY"]
style_guides: dict = {
'google style': 'https://google.github.io/styleguide/pyguide.html',
'pep8': 'https://pep8.org/'
"google style": "https://google.github.io/styleguide/pyguide.html",
"pep8": "https://pep8.org/",
}



class ResponseData(TypedDict):
'''
"""
For schema based responses like `JSON`
'''
"""

line: int
message: str

8 changes: 5 additions & 3 deletions app/gemini_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@
import json
from gemini_analyzer import CodeAnalyzer


def main():
code = sys.argv[1]
analyzer = CodeAnalyzer()
analyzer.setCode(code)
style_guide = analyzer.analyze_code()
if style_guide:
print(json.dumps({'style_guide': style_guide}))
print(json.dumps({"style_guide": style_guide}))
else:
print(json.dumps({'error': 'Analysis failed'}))
print(json.dumps({"error": "Analysis failed"}))


if __name__ == '__main__':
if __name__ == "__main__":
main()
3 changes: 2 additions & 1 deletion examples/class.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed

def bark(self):
print("Woof!")


my_dog = Dog("Buddy", "Golden Retriever")
my_dog.bark()
5 changes: 3 additions & 2 deletions examples/greet.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
def greet(name):
"""Greets the person with the given name."""
"""Greets the person with the given name."""

print("Hello,", name)

print("Hello,", name)

greet("Alice")
8 changes: 5 additions & 3 deletions examples/sum.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
def calculate_sum( a , b): # Intentional spacing issues
def calculate_sum(a, b): # Intentional spacing issues
"""This function calculates the sum of two numbers."""
result=a+b
return result # Incorrect indentation
result = a + b


return result # Incorrect indentation

print(calculate_sum(10, 5))
16 changes: 9 additions & 7 deletions server.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,23 @@

app = Flask(__name__)

@app.route('/analyze', methods=['POST'])

@app.route("/analyze", methods=["POST"])
def analyze():
data = request.get_json()
code = data['code']
code = data["code"]

analyzer = CodeAnalyzer()
analyzer._input_code = code
style_guide = analyzer.analyze_code()
processed_stule_guide = json.loads(style_guide)
issues = {'issues':processed_stule_guide}
issues = {"issues": processed_stule_guide}
if style_guide:
#data = json.loads(style_guide) # Convert string to dictionary
return jsonify({'style_guide' : issues}), 200
# data = json.loads(style_guide) # Convert string to dictionary
return jsonify({"style_guide": issues}), 200
else:
return jsonify({'error': 'Analysis failed'}), 500
return jsonify({"error": "Analysis failed"}), 500


if __name__ == '__main__':
if __name__ == "__main__":
app.run(port=5000)
12 changes: 6 additions & 6 deletions streamlit.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

if st.button("Analyze"):
if code_input:
with st.spinner('Analyzing...'):
with st.spinner("Analyzing..."):
code_handler._input_code = code_input
response = code_handler.analyze_code()
data = json.loads(response)
Expand All @@ -20,16 +20,16 @@
try:
for items in data["issues"]:
with st.expander(f"Line `{items['line']}`"):
st.write(items['message'])
st.write(items["message"])
except:
pass

# JSON output
st.subheader("Raw API response : ")
with st.expander(f"Expand"):
st.json(response) # Display the Gemini-generated style guide

time.sleep(5)

else:
st.warning("Please paste your code to analyze.")
st.warning("Please paste your code to analyze.")

0 comments on commit 2e12c6d

Please sign in to comment.