Skip to content

Commit

Permalink
Inspect package coded
Browse files Browse the repository at this point in the history
  • Loading branch information
hrshdhgd committed Feb 9, 2024
1 parent 52ccb6f commit ed9e9e0
Show file tree
Hide file tree
Showing 5 changed files with 129 additions and 76 deletions.
8 changes: 4 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,10 @@ extend-ignore = [
line-length = 120

# Allow autofix for all enabled rules (when `--fix`) is provided.
fixable = ["ALL"]
lint.fixable = ["ALL"]

# Select or ignore from https://beta.ruff.rs/docs/rules/
select = [
lint.select = [
"B", # bugbear
"D", # pydocstyle
"E", # pycodestyle errors
Expand All @@ -63,10 +63,10 @@ select = [
"W", # Warning
]

unfixable = []
lint.unfixable = []
target-version = "py310"

[tool.ruff.mccabe]
[tool.ruff.lint.mccabe]
# Unlike Flake8, default to a complexity level of 10.
max-complexity = 10

Expand Down
15 changes: 6 additions & 9 deletions src/codergpt/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import click

from codergpt import __version__
from codergpt.main import start
from codergpt.main import CoderGPT

__all__ = [
"main",
Expand Down Expand Up @@ -36,14 +36,11 @@ def main(verbose: int, quiet: bool):


@main.command()
def run():
"""Run the CoderGPT's demo command."""
start()


def explore():
"""Explore the code."""
print("Exploring the code.")
@click.argument("path", type=click.Path(exists=True))
def inspect(path: str):
"""Inspect pckage to show file-language-map."""
coder = CoderGPT()
coder.inspect_package(path=path)


if __name__ == "__main__":
Expand Down
7 changes: 7 additions & 0 deletions src/codergpt/constants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
"""All constants used in the package."""

from pathlib import Path

SRC = Path(__file__).resolve().parents[1]
PACKAGE_DIR = SRC / "codergpt"
EXTENSION_MAP_FILE = PACKAGE_DIR / "extensions.yaml"
48 changes: 48 additions & 0 deletions src/codergpt/extensions.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
language-map:
".py": "Python"
".js": "JavaScript"
".java": "Java"
".c": "C"
".cpp": "C++"
".html": "HTML"
".css": "CSS"
".php": "PHP"
".rb": "Ruby"
".rs": "Rust"
".go": "Go"
".swift": "Swift"
".kt": "Kotlin"
".ts": "TypeScript"
".sh": "Shell"
".json": "JSON"
".xml": "XML"
".yml": "YAML"
".yaml": "YAML"
".sql": "SQL"
".pl": "Perl"
".lua": "Lua"
".r": "R"
".cs": "C#"
".m": "Objective-C"
".scala": "Scala"
".groovy": "Groovy"
".dart": "Dart"
".jsx": "JSX"
".tsx": "TSX"
".h": "C Header"
".hpp": "C++ Header"
".hh": "C++ Header"
".hxx": "C++ Header"
".mjs": "ES Module"
".cjs": "CommonJS"
".svelte": "Svelte"
".vue": "Vue"
".elm": "Elm"
".erl": "Erlang"
".ex": "Elixir"
".exs": "Elixir"
".zig": "Zig"
".nim": "Nim"
".cr": "Crystal"
".v": "V"
".vala": "Vala"
127 changes: 64 additions & 63 deletions src/codergpt/main.py
Original file line number Diff line number Diff line change
@@ -1,75 +1,76 @@
"""Main python file."""


import os
from pathlib import Path
from typing import Dict, Set, Union
from typing import Dict, Union

import yaml
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI


# Define a function to determine the programming language from a file extension.
def get_language_from_extension(ext: Set[str]) -> Dict[str, str]:
"""Get language from file extension."""
# Initialize the ChatOpenAI object with an API key from the environment variables.
llm = ChatOpenAI(openai_api_key=os.environ.get("OPENAI_API_KEY"))

# Create a prompt template with predefined messages to set the context for the AI.
# Here, we tell the AI that it is a "world class software developer".
prompt = ChatPromptTemplate.from_messages(
[("system", "You are world class software developer."), ("user", "{input}")]
)

# Combine the prompt template with the ChatOpenAI object to create a chain.
# This chain will be used to send the input to the AI in the correct context.
chain = prompt | llm

# Invoke the chain with the specific input asking about the programming language
# associated with the given file extension. The input is formatted to include the
# file extension in the question and requests a one-word response.
response = chain.invoke(
{
"input": f"Given the file extensions {ext},\
return just programming language name e.g. 'Python' or 'JavaScript'."
}
)
return response.content


def inspecting_code(path: Union[str, Path]) -> Dict[str, str]:
"""Inspecting the code and returning a mapping of files to their languages."""
print("Inspecting the code.")

# Initialize an empty dictionary to store the results
file_language_map = {}

# Convert path to Path object if it's a string
path = Path(path)

# Check if the path is a directory or a file
if path.is_dir():
# Iterate over all files in the directory and subdirectories
for file in path.rglob("*.*"):
language = get_language_from_extension(file.suffix)
file_language_map[str(file)] = language
elif path.is_file():
# Get the language for the single file
language = get_language_from_extension(path.suffix)
file_language_map[str(path)] = language
else:
print(f"The path {path} is neither a file nor a directory.")
from codergpt.constants import EXTENSION_MAP_FILE


class CoderGPT:
"""CoderGPT class."""

def __init__(self):
"""Initialize the CoderGPT class."""
# Initialize the ChatOpenAI object with an API key from the environment variables.
self.llm = ChatOpenAI(openai_api_key=os.environ.get("OPENAI_API_KEY"))
# Create a prompt template with predefined messages to set the context for the AI.
# Here, we tell the AI that it is a "world class software developer".
self.prompt = ChatPromptTemplate.from_messages(
[("system", "You are world class software developer."), ("user", "{input}")]
)
# Combine the prompt template with the ChatOpenAI object to create a chain.
# This chain will be used to send the input to the AI in the correct context.
self.chain = self.prompt | self.llm

# # Invoke the chain with the specific input asking about the programming language
# # associated with the given file extension. The input is formatted to include the
# # file extension in the question and requests a one-word response.
# response = chain.invoke(
# {
# "input": f"Given the file extensions {ext},\
# return just programming language name e.g. 'Python' or 'JavaScript'."
# }
# )

def inspect_package(self, path: Union[str, Path]) -> Dict[str, str]:
"""Inspecting the code and returning a mapping of files to their languages."""
print("Inspecting the code.")

with open(EXTENSION_MAP_FILE, "r") as file:
extension_to_language = yaml.safe_load(file)

# Initialize an empty dictionary to store the results
file_language_map = {}

# Convert path to Path object if it's a string
path = Path(path)

# Check if the path is a directory or a file
if path.is_dir():
# Iterate over all files in the directory and subdirectories
file_language_map = {
str(file): extension_to_language["language-map"].get(file.suffix)
for file in path.rglob("*.*")
if extension_to_language["language-map"].get(file.suffix) is not None
}

elif path.is_file():
# Get the language for the single file
language = extension_to_language["language-map"].get(path.suffix)
if language is not None:
file_language_map[str(path)] = language

else:
print(f"The path {path} is neither a file nor a directory.")
return file_language_map
return file_language_map

return file_language_map


def start():
"""Entry point function."""
path = Path("src")
language_map = inspecting_code(path)
print(language_map)


if __name__ == "__main__":
start()
coder = CoderGPT()
coder.inspect_package("src")

0 comments on commit ed9e9e0

Please sign in to comment.