Spaces:
Runtime error
Runtime error
Commit Β·
2ecc792
1
Parent(s): 5267759
Separated the backend and frontend
Browse filesFiles changed (31)
- .devcontainer/devcontainer.jsonDeleted-33
- TechdocsAPI/.gitattributesAdded+35
- TechdocsAPI/DockerfileAdded+11
- TechdocsAPI/README.mdAdded+48
- TechdocsAPI/app.pyAdded+1
- TechdocsAPI/backend/__init__.pyAdded+49
- TechdocsAPI/backend/core/ConfigEnv.pyAdded+32
- TechdocsAPI/backend/core/ExceptionHandlers.pyAdded+27
- TechdocsAPI/backend/core/Exceptions.pyAdded+45
- TechdocsAPI/backend/core/__init__.pyAdded
- TechdocsAPI/backend/models/__init__.pyAdded+3
- TechdocsAPI/backend/models/auth.pyAdded+32
- TechdocsAPI/backend/models/generic.pyAdded+14
- TechdocsAPI/backend/models/inference.pyAdded+6
- TechdocsAPI/backend/router.pyAdded+65
- TechdocsAPI/backend/services/__init__.pyAdded
- TechdocsAPI/backend/services/auth/__init__.pyAdded+2
- TechdocsAPI/backend/services/auth/ops.pyAdded+109
- TechdocsAPI/backend/services/auth/utils/JWTBearer.pyAdded+75
- TechdocsAPI/backend/services/auth/utils/auth_funcs.pyAdded+171
- TechdocsAPI/backend/services/db/__init__.pyAdded
- TechdocsAPI/backend/services/db/utils/DBQueries.pyAdded+66
- TechdocsAPI/backend/utils/DBConnection.pyAdded+57
- TechdocsAPI/backend/utils/__init__.pyAdded+1
- TechdocsAPI/backend/utils/prompt.txtAdded+11
- TechdocsAPI/backend/utils/scopes.pyAdded+3
- TechdocsAPI/requirements.txtAdded+10
- Login.py β frontend/Login.pyRenamed+1-1
- pages/Code.py β frontend/pages/Code.pyRenamed+2-2
- requirements.txt β frontend/requirements.txtRenamed
- π‘_Home.py β frontend/π‘_Home.pyRenamed+1-1
123456789101112131415161718192021222324252627282930313233{ "name": "Python 3", // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile "image": "mcr.microsoft.com/devcontainers/python:1-3.11-bullseye", "customizations": { "codespaces": { "openFiles": [ "README.md", "frontend/π‘_Home.py" ] }, "vscode": { "settings": {}, "extensions": [ "ms-python.python", "ms-python.vscode-pylance" ] } }, "updateContentCommand": "[ -f packages.txt ] && sudo apt update && sudo apt upgrade -y && sudo xargs apt install -y <packages.txt; [ -f requirements.txt ] && pip3 install --user -r requirements.txt; pip3 install --user streamlit; echo 'β
Packages installed and Requirements met'", "postAttachCommand": { "server": "streamlit run frontend/π‘_Home.py --server.enableCORS false --server.enableXsrfProtection false" }, "portsAttributes": { "8501": { "label": "Application", "onAutoForward": "openPreview" } }, "forwardPorts": [ 8501 ]}1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text1234567891011FROM python:3.11
WORKDIR /backend
COPY ./requirements.txt /backend/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /backend/requirements.txt
COPY . .
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748---title: TechdocsAPIemoji: π’colorFrom: greencolorTo: greensdk: dockerpinned: false---
# Techdocs: A code documentation generator
## Introduction
**Code Documentation Generation** is a tool that generates documentation for your code. It is a simple tool that can be used by anyone who wants to generate documentation for their code. It leverages the power of **OpenAI GPT-3, Huggingface Transformers, Langchain and Clarifai** to generate documentation for your code.
To use the application, you need to provide your code as input. The tool will analyze your code and generate documentation for it. The documentation will include comments, descriptions, parameters, return values, examples, and more.
It is a useful tool for developers who want to document their code without spending too much time and effort. It can help you improve the readability, maintainability, and quality of your code. It can also help you share your code with others more easily.
## Installation> Download zip or Clone the repository and run the following command in the terminal to install the required packages.
> We recommend using a virtual environment for the installation.
```bash$ git clone https://github.com/HemanthSai7/Techdocs$ cd Techdocs$ pip install -r requirements.txt$ -- Run backend$ uvicorn app:app --reload ```
## Tech Stack Used
## Team Members| Name | Github || --- | --- || Mayuresh Agashe | [Mayuresh Agashe](https://github.com/mayureshagashe2105) || Hemanth Sai Garladinne | [Hemanth Sai Garladinne](https://github.com/HemanthSai7) |1from backend import app12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import mysql.connectorfrom mysql.connector import errorcode
from fastapi import FastAPI, statusfrom fastapi.exceptions import HTTPException
from backend.utils import DBConnectionfrom backend.core.ConfigEnv import config
from langchain.llms import Clarifaifrom langchain.chains import LLMChainfrom langchain.prompts import PromptTemplate
app = FastAPI(title="Techdocs", version="V0.0.1", description="API for automatic code documentation generation!" )
from backend import router
try: dbconnection = DBConnection() test_conn = DBConnection.get_client().get_server_info()
# send prompt wizardcoderLM-70b-instruct-GGUF model with open("backend/utils/prompt.txt",'r') as f: prompt = f.read()
prompt = PromptTemplate(template=prompt, input_variables=['instruction'])
llm = Clarifai( pat = config.CLARIFAI_PAT, user_id = config.USER_ID, app_id = config.APP_ID, model_id = config.MODEL_ID, model_version_id=config.MODEL_VERSION_ID, )
llmchain = LLMChain( prompt=prompt, llm=llm ) app.state.llmchain = llmchain
except mysql.connector.Error as err: raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(err))
1234567891011121314151617181920212223242526272829303132"""Config class for handling env variables."""from functools import lru_cache
from pydantic import BaseSettings
class Settings(BaseSettings): HOSTNAME: str DATABASE: str UID: str PASSWORD: str ALGORITHM:str JWT_SECRET_KEY:str JWT_REFRESH_SECRET_KEY:str # OPENAI_KEY:str APP_ID:str USER_ID:str MODEL_ID:str CLARIFAI_PAT:str MODEL_VERSION_ID:str class Config: env_file = ".env"
@lru_cache()def get_settings(): return Settings()
config = get_settings()123456789101112131415161718192021222324252627from backend import appfrom .Exceptions import *
from fastapi.responses import JSONResponsefrom fastapi.requests import Requestfrom fastapi import status
@app.exception_handler(ExistingUserException)async def handle_existing_user_found(request: Request, exec: ExistingUserException): return JSONResponse(status_code=status.HTTP_226_IM_USED, content=repr(exec) )
@app.exception_handler(InvalidCredentialsException)async def handle_login_failed(request: Request, exec: InvalidCredentialsException): return JSONResponse(status_code=status.HTTP_403_FORBIDDEN, content=repr(exec) )
@app.exception_handler(InfoNotFoundException)async def handle_info_not_found(request: Request, exec: InfoNotFoundException): return JSONResponse(status_code=status.HTTP_401_UNAUTHORIZED, content=repr(exec) )123456789101112131415161718192021222324252627282930313233343536373839404142434445import json
from backend.models import GeneralResponse, TokenSchema
class InvalidCredentialsException(Exception): def __init__(self, token_result: GeneralResponse): self.token_result = token_result self.set_statuses() super(InvalidCredentialsException, self).__init__()
def set_statuses(self): self.token_result.status = 'login_failed'
def __repr__(self): return json.dumps(self.token_result)
class ExistingUserException(Exception): def __init__(self, response_result: GeneralResponse): self.response_result = response_result self.set_statuses() super(ExistingUserException, self).__init__()
def set_statuses(self): self.response_result.status = f'failed' self.response_result.message.append(f'user with this AADHAR Number already has an account') self.response_result.message[0] = 'authenticated'
def __repr__(self): return json.dumps(self.response_result) class InfoNotFoundException(Exception): def __init__(self, response_result: GeneralResponse, message: str): self.response_result = response_result self.message = message self.set_statuses() super(InfoNotFoundException, self).__init__(message)
def set_statuses(self): self.response_result['status'] = 'abort' self.response_result['message'][0] = 'authenticated' self.response_result['message'].append(self.message)
def __repr__(self): return json.dumps(self.response_result)123from .auth import *from .generic import *from .inference import *1234567891011121314151617181920212223242526272829303132from pydantic import BaseModel, Field, EmailStrfrom typing import Union, List, Tuple
from .generic import Base
class TokenSchema(Base): access_token: str refresh_token: str
class UserAuth(Base): username: str = Field(..., description="username") password: str = Field(..., min_length=5, max_length=24, description="user password") email: EmailStr
class User(Base): username: str email: EmailStr
class TokenPayload(Base): sub: str = None exp: int = None
class LoginCreds(Base): username: str password: str
class APIKey(Base): api_key: str1234567891011121314from pydantic import BaseModelfrom typing import List
class Base(BaseModel): @classmethod def get_instance(cls, **kwargs): return cls(**kwargs)
class GeneralResponse(Base): status:str message: List[str] data:dict123456from pydantic import BaseModelfrom typing import Listfrom .generic import Base
class Inference(Base): docstr:str1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465from fastapi import Request, Depends, UploadFilefrom fastapi.middleware.cors import CORSMiddleware
from backend import appfrom backend.utils import DBConnectionfrom backend.models import *from backend.services.auth import *
app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
@app.get("/api/response_check", tags=["Resource Server"])def api_response_check(): response_result = GeneralResponse.get_instance(data={}, status="not_allowed", message=["Not authenticated"] )
try: db_msg = "" if DBConnection.is_connected(): db_msg = "Connection Successful to db!" else: db_msg = "Connection failed to db"
response_result.message.append(db_msg)
except Exception as e: print("Exception :", e)
return response_result
@app.post("/auth/signup", summary="Creates new user account", response_model=GeneralResponse, tags=["Auth Server"])async def signup(response: UserAuth): response_result = GeneralResponse.get_instance(data={}, status="not_allowed", message=["Not authenticated"] ) ops_signup(response_result, response)
return response_result
@app.post("/auth/login", summary="Logs in user", response_model=TokenSchema, tags=["Auth Server"])async def login(response:LoginCreds): return ops_login(response)
@app.put("/auth/regenerate_api_key",summary="Forget Password",response_model=APIKey,tags=["Auth Server"],dependencies=[Depends(JWTBearer())])async def regenerate_api_key(access_token: str = Depends(JWTBearer())): user_sub=Auth.get_user_credentials(access_token)
return ops_regenerate_api_key(user_sub)
@app.post("/api/inference", summary="Inference", response_model=Inference, tags=["Resource Server"], dependencies=[Depends(JWTBearer())])async def inference(code_block:str, api_key: str,access_token:str=Depends(JWTBearer())): user_sub=Auth.get_user_credentials(access_token)
print("after res") return ops_inference(code_block,api_key,user_sub)12from .ops import *from .utils.JWTBearer import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109from .utils.auth_funcs import *from .utils.JWTBearer import *from backend.models import *from backend.services.db.utils.DBQueries import DBQueriesfrom backend.core.Exceptions import *from backend import app
# import openai# from transformers import RobertaTokenizer, T5ForConditionalGeneration
def ops_signup(response_result: GeneralResponse, data: UserAuth): """Wrapper method to handle signup process.
Args: response_result: FrontendResponseModel. A TypedDict to return the response captured from the API to the frontend. data: UserAuth. New user's prospective credentials from the frontend to create their account.
Raises: ExistingUserException: If account with entered AADHAR Number already exists. """ # querying database to check if user already exist user = DBQueries.fetch_data_from_database('auth', ['username', 'email'], f"username='{data.username}' OR email='{data.email}'") if len(list(user)) != 0: # user with the entered credentials already exists raise ExistingUserException(response_result) DBQueries.insert_to_database('auth', (data.username, Auth.get_password_hash(data.password), data.email), ['username', 'password', 'email']) response_result.status = 'success' response_result.message = [f'User created successfully']
def ops_login(data:LoginCreds): """Wrapper method to handle login process.
Args: data: LoginCreds. User's credentials from the frontend to login to their account.
Returns: TokenSchema. A Pydantic BaseModel to return the JWT tokens to the frontend.
Raises: InvalidCredentialsException: If account with entered credentials does not exist. """ # querying database to check if user already exist response_result = GeneralResponse.get_instance(data={}, status="not_allowed", message=["Not authenticated"] ) user = DBQueries.fetch_data_from_database('auth', ['username', 'password'], f"username='{data.username}'") user = list(user) if len(user) == 0: # user with the entered credentials does not exist raise InvalidCredentialsException(response_result) user = user[0] if not Auth.verify_password(data.password, user[1]) and Auth.verify_username(data.username, user[0]): # password is incorrect raise InvalidCredentialsException(response_result) # password is correct return TokenSchema(access_token=Auth.create_access_token(data.username), refresh_token=Auth.create_refresh_token(data.username), )
def ops_regenerate_api_key(username:str) -> APIKey:
user_API_entry = DBQueries.fetch_data_from_database('api_key', 'apikey', f"username='{username}'") user_API_entry = list(user_API_entry) apikey = None
if len(user_API_entry) != 0: apikey = APIKey(api_key=Auth.generate_api_key(username)) DBQueries.update_data_in_database('api_key','apikey',f"username='{username}'", apikey.api_key) else: apikey = Auth.generate_api_key(username) DBQueries.insert_to_database('api_key', (username, apikey), ['username', 'apikey']) apikey = APIKey(api_key=apikey) return apikey
def ops_inference(source_code:str,api_key:str,username:str): response_result = GeneralResponse.get_instance(data={}, status="not_allowed", message=["Not authenticated"] )
user=DBQueries.fetch_data_from_database('api_key', ['apikey'], f"username='{username}'") if len(list(user)) == 0: # user with the entered credentials does not exist raise InfoNotFoundException(response_result,"User not found") elif list(user)[0][0]!=api_key: raise InvalidCredentialsException(response_result) def generate_docstring(source_code_message: str):
llm_response = app.state.llmchain.run({"instruction": source_code_message})
docstring = Inference(docstr=llm_response) return docstring
return generate_docstring(source_code)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475"""Custom Authentication & Authorization bearer to authenticate and authorizeusers based on the following factors:1. username2.password3.email
This utility class validates generated JWTs and grants scoped access to usersaccording to their roles."""from backend.core.ConfigEnv import configfrom backend.models import TokenPayload
from datetime import datetime
from fastapi import Request, HTTPExceptionfrom fastapi.security import HTTPBearer, HTTPAuthorizationCredentialsfrom pydantic import ValidationErrorfrom jose import jwt
class JWTBearer(HTTPBearer): """Custom bearer to validate access tokens.
Args: auto_error: bool = True. Internal param to allow auto error detection.
Raises: HHTTPException(403): If authentication scheme is not `Bearer`. HTTPException(403): If the access token is invalid or expired. HTTPException(403): If authorization code is invalid. """ def __init__(self, auto_error: bool = True): super(JWTBearer, self).__init__(auto_error=auto_error)
async def __call__(self, request: Request) -> str: credentials: HTTPAuthorizationCredentials = await super(JWTBearer, self).__call__(request) if credentials: if not credentials.scheme == "Bearer": raise HTTPException(status_code=403, detail="Invalid authentication scheme.") else: is_valid = JWTBearer.token_validation(credentials.credentials) if not is_valid: raise HTTPException(status_code=403, detail="Invalid token or expired token.") return credentials.credentials else: raise HTTPException(status_code=403, detail="Invalid authorization code.")
@staticmethod def token_validation(token: str) -> bool: """Decodes JWTs to check their validity by inspecting expiry and authorization code.
Args: token: str. Authenticated `access_token` of the user.
Returns: bool value to indicate validity of the access tokens.
Raises: jwt.JWTError: If decode fails. ValidationError: If JWTs are not in RFC 7519 standard. """ try: payload = jwt.decode( token, config.JWT_SECRET_KEY, algorithms=[config.ALGORITHM] ) token_data = TokenPayload(**payload)
if datetime.fromtimestamp(token_data.exp) < datetime.now(): return False
except(jwt.JWTError, ValidationError): return False
return True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171"""Utility class to leverage encryption, verification of entered credentialsand generation of JWT access tokens."""from datetime import datetime, timedeltafrom typing import Union, Anyimport secrets
from jose import jwtfrom passlib.context import CryptContextfrom pydantic import ValidationError
from fastapi.exceptions import HTTPException
from backend.core.ConfigEnv import configfrom backend.core.Exceptions import *from backend.models import TokenPayload, TokenSchema
ACCESS_TOKEN_EXPIRE_MINUTES = 30 # 30 minutesREFRESH_TOKEN_EXPIRE_MINUTES = 60 * 24 * 3 # 3 days
class Auth: """Utility class to perform - 1.encryption via `bcrypt` scheme. 2.password hashing 3.verification of credentials and generating access tokens.
Attrs: pwd_context: CryptContext. Helper for hashing & verifying passwords using `bcrypt` algorithm. """ pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
@classmethod def get_password_hash(cls,password: str) -> str: """Encrypts the entered password.
Args: password: str. Entered password.
Returns: returns hashed(encrypted) password string. """ return cls.pwd_context.hash(password)
@classmethod def verify_password(cls, plain_password: str, hashed_password: str) -> bool: """Validates if the entered password matches the actual password.
Args: plain_password: str. Entered password by user. hashed_password: str. hashed password from the database.
Returns: bool value indicating whether the passwords match or not. """ return cls.pwd_context.verify(plain_password, hashed_password)
@staticmethod def verify_username(entered_username: str, db_username: str) -> bool: """Validates if the entered username matches the actual username.
Args: entered_username: str. Entered `username` by user. db_username: str. username from the database.
Returns: bool value indicating whether the village names match or not. """ return entered_username == db_username
@staticmethod def create_access_token(subject: Union[str, Any], expires_delta: int = None) -> str: """Creates JWT access token.
Args: subject: Union[Any, str]. Hash_key to generate access token from. expires_delta: int = None. Expiry time for the JWT.
Returns: encoded_jwt: str. Encoded JWT token from the subject of interest. """ if expires_delta is not None: expires_delta = datetime.utcnow() + expires_delta else: expires_delta = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode = {"exp": expires_delta, "sub": str(subject)} encoded_jwt = jwt.encode(to_encode, config.JWT_SECRET_KEY, config.ALGORITHM) return encoded_jwt
@staticmethod def create_refresh_token(subject: Union[str, Any], expires_delta: int = None) -> str: """Creates JWT refresh access token.
Args: subject: Union[Any, str]. Hash_key to generate access token from. expires_delta: int = None. Expiry time for the JWT.
Returns: encoded_jwt: str. Encoded JWT token from the subject of interest. """ if expires_delta is not None: expires_delta = datetime.utcnow() + expires_delta else: expires_delta = datetime.utcnow() + timedelta(minutes=REFRESH_TOKEN_EXPIRE_MINUTES) to_encode = {"exp": expires_delta, "sub": str(subject)} encoded_jwt = jwt.encode(to_encode, config.JWT_REFRESH_SECRET_KEY, config.ALGORITHM) return encoded_jwt
@staticmethod def generate_access_tokens_from_refresh_tokens(token: str) -> TokenSchema: """Generates a new pair of tokens by implementing rotating refresh_access_tokens.
Args: token: str. Current valid refresh access token.
Returns: tokens: TokenSchema. New tokens with new validity.
Raises: LoginFailedException: If the current refresh access token is invalid. """ tokens = TokenSchema.get_instance( access_token= "", refresh_token= "", ) try: payload = jwt.decode( token, config.JWT_REFRESH_SECRET_KEY, algorithms=[config.ALGORITHM] ) token_data = TokenPayload(**payload) if datetime.fromtimestamp(token_data.exp)< datetime.now(): raise HTTPException(status_code=403, detail="Invalid token or expired token.") except (jwt.JWTError, ValidationError): raise InvalidCredentialsException(tokens) tokens['access_token'] = Auth.create_access_token(token_data.sub) tokens['refresh_token'] = Auth.create_refresh_token(token_data.sub) tokens['status'] = 'login successful' tokens['role'] = token_data.sub.split("_")[1] return tokens
@classmethod def generate_api_key(cls, username: str): return cls.get_password_hash(username + secrets.token_urlsafe(25 - len(username))) @classmethod def get_user_credentials(cls,access_token:str): response_result = GeneralResponse.get_instance(data={}, status="not_allowed", message=["Not authenticated"] ) try: payload = jwt.decode( access_token, config.JWT_SECRET_KEY, algorithms=[config.ALGORITHM] ) token_data = TokenPayload(**payload) return token_data.sub except (jwt.JWTError, ValidationError): raise InvalidCredentialsException(response_result) @classmethod def verify_apikey(cls,user_api_key:str,true_api_key:str): return user_api_key == true_api_key
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566# fix ObjectId & FastApi conflictimport pydanticfrom bson.objectid import ObjectIdpydantic.json.ENCODERS_BY_TYPE[ObjectId]=str
from typing import Union, Tuple, List
from backend.utils import DBConnectionfrom backend.core.Exceptions import *
class DBQueries: @classmethod def insert_to_database(cls, table_name:str, data:Union[Tuple, List[Tuple]], cols:List[str]=None): con = DBConnection.get_client() cursor = con.cursor() QUERY = ('INSERT INTO {table_name} ' f'({",".join(cols)}) ' 'VALUES ' ).format(table_name=table_name) print(data) if isinstance(data, list): QUERY+="("+",".join(["%s" for _ in range(len(data[0]))])+")" cursor.executemany(QUERY, data) else: QUERY+="("+",".join(["%s" for _ in range(len(data))])+")" cursor.execute(QUERY, data) con.commit() @classmethod def fetch_data_from_database(cls,table_name:str,cols_to_fetch:Union[str, List[str]], where_clause:str=None): con = DBConnection.get_client() cursor = con.cursor() if isinstance(cols_to_fetch, str): cols_to_fetch = [cols_to_fetch] cols_to_fetch = ", ".join(cols_to_fetch) QUERY = ('SELECT {cols} FROM {table_name}').format(cols=cols_to_fetch, table_name=table_name) if where_clause: QUERY = QUERY + " WHERE " + where_clause cursor.execute(QUERY) return cursor.fetchall() @classmethod def update_data_in_database(cls, table_name:str, cols_to_update:Union[str, List[str]], where_clause:str=None, new_values:Union[str, List[str]]=None): con = DBConnection.get_client() cursor = con.cursor() if isinstance(cols_to_update, str): cols_to_update = cols_to_update + "=%s" else: cols_to_update = "=%s, ".join(cols_to_update) if isinstance(new_values, str): new_values = [new_values] QUERY = ('UPDATE {table_name} SET {cols}').format(table_name=table_name, cols=cols_to_update) if where_clause: QUERY = QUERY + " WHERE " + where_clause cursor.execute(QUERY, new_values) con.commit() return True
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657""" Import Important Packages"""import mysql.connector
from backend.core.ConfigEnv import config
class DBConnection: """DBConnection Class. It ensures only one instance of the class is created and it is accessible from everywhere. It is used in the design of logging classes, Configuration classes where we need to have only one instance of the class. There is no need to create multiple instances of each operation across all components of application.
Raises: Exception: It raises an exception if the client instance is not created. """ __client = None #This is the client variable that is used to connect to the database _flag = False def __init__(self): """This is the constructor of the class. It is used to create the client variable. It also checks if the client instance is already created. If the client instance is already created, then it does not create a new client instance. """ if DBConnection.__client is not None: raise Exception("This class is a singleton!") else: creds={ 'host':config.HOSTNAME, 'user':config.UID, 'password':config.PASSWORD, 'database':config.DATABASE } DBConnection.__client = mysql.connector.connect(**creds) DBConnection._flag = True
@staticmethod # A static method is a method that is called without creating an instance of the class. def get_client(): """The get_client() function is used to get the client instance.
Returns: DBConnection.__client: It returns the client instance. """ return DBConnection.__client
@classmethod def is_connected(cls)->bool: """property to get the database connection flag. Returns: DBConnection._flag: bool. Connection status to the DB. """ return cls._flag
1from .DBConnection import DBConnection1234567891011You are an AI Coding Assitant and your task is to generate an elaborate, high quality docstring for the query function given by the user. A docstring consists of the following sections:1. Description: Is the description of what the function does. 2. Arguments: 1. Argument Name: Description of the argument and its type. 3. Returns: Description of the return value of the function if any. 4. Raises: Description of the errors that can be raised by the function if any. Instruction: {instruction} Your task is to generate a docstring for the above query.Response:123from typing import Callable
from backend.models import User12345678910fastapi==0.99.1uvicornrequestspydantic==1.10.12python-jose[cryptography]passlib[bcrypt]mysql-connector-pythonpydantic[email]langchainclarifai5 unmodified lines67891011125 unmodified linesdef auth_page():base_url = 'https://hemanthsai7-techdocsapi.hf.space'headers={"accept":"application/json"}5 unmodified lines67891011125 unmodified linesdef auth_page():base_url = 'http://localhost:8000'headers={"accept":"application/json"}
27 unmodified lines2829303132333413 unmodified lines4849505152535427 unmodified linesif st.button("Generate API KEY"):with st.spinner("Generating API Key..."):try:base_url = "https://hemanthsai7-techdocsapi.hf.space"headers={"accept":"application/json", "Authorization": f"Bearer {st.session_state.access_token}"}response = requests.put(url=base_url + "/auth/regenerate_api_key", headers=headers, data=json.dumps({"username":st.session_state.username}))if (response.status_code!=200):13 unmodified linesdef code_page():base_url = 'https://hemanthsai7-techdocsapi.hf.space'def query_post(url, headers, data=None, params=None):response = requests.post(url, data=data, headers=headers, params=params)27 unmodified lines2829303132333413 unmodified lines4849505152535427 unmodified linesif st.button("Generate API KEY"):with st.spinner("Generating API Key..."):try:base_url = "http://localhost:8000"headers={"accept":"application/json", "Authorization": f"Bearer {st.session_state.access_token}"}response = requests.put(url=base_url + "/auth/regenerate_api_key", headers=headers, data=json.dumps({"username":st.session_state.username}))if (response.status_code!=200):13 unmodified linesdef code_page():base_url = 'http://localhost:8000'def query_post(url, headers, data=None, params=None):response = requests.post(url, data=data, headers=headers, params=params)
6 unmodified lines789101112136 unmodified lines# image2=Image.open('assets/logo2.png')st.set_page_config(page_title="DocGup-tea",layout="wide",page_icon="π‘",initial_sidebar_state="expanded",6 unmodified lines789101112136 unmodified lines# image2=Image.open('assets/logo2.png')st.set_page_config(page_title="Techdocs",layout="wide",page_icon="π‘",initial_sidebar_state="expanded",
.devcontainer/devcontainer.jsonDeleted-33
TechdocsAPI/.gitattributesAdded+35
TechdocsAPI/DockerfileAdded+11
TechdocsAPI/README.mdAdded+48
TechdocsAPI/app.pyAdded+1
TechdocsAPI/backend/__init__.pyAdded+49
TechdocsAPI/backend/core/ConfigEnv.pyAdded+32
TechdocsAPI/backend/core/ExceptionHandlers.pyAdded+27
TechdocsAPI/backend/core/Exceptions.pyAdded+45
TechdocsAPI/backend/core/__init__.pyAdded
TechdocsAPI/backend/models/__init__.pyAdded+3
TechdocsAPI/backend/models/auth.pyAdded+32
TechdocsAPI/backend/models/generic.pyAdded+14
TechdocsAPI/backend/models/inference.pyAdded+6
TechdocsAPI/backend/router.pyAdded+65
TechdocsAPI/backend/services/__init__.pyAdded
TechdocsAPI/backend/services/auth/__init__.pyAdded+2
TechdocsAPI/backend/services/auth/ops.pyAdded+109
TechdocsAPI/backend/services/auth/utils/JWTBearer.pyAdded+75
TechdocsAPI/backend/services/auth/utils/auth_funcs.pyAdded+171
TechdocsAPI/backend/services/db/__init__.pyAdded
TechdocsAPI/backend/services/db/utils/DBQueries.pyAdded+66
TechdocsAPI/backend/utils/DBConnection.pyAdded+57
TechdocsAPI/backend/utils/__init__.pyAdded+1
TechdocsAPI/backend/utils/prompt.txtAdded+11
TechdocsAPI/backend/utils/scopes.pyAdded+3
TechdocsAPI/requirements.txtAdded+10
Login.py β frontend/Login.pyRenamed+1-1
pages/Code.py β frontend/pages/Code.pyRenamed+2-2
requirements.txt β frontend/requirements.txtRenamed
π‘_Home.py β frontend/π‘_Home.pyRenamed+1-1