Spaces:
Runtime error
Runtime error
email_verification
#1
by mayureshagashe2105 - opened
Files changed (16)
- TechdocsAPI/backend/__init__.py+39-17
- TechdocsAPI/backend/core/ConfigEnv.py+1-2
- TechdocsAPI/backend/core/ExceptionHandlers.py-6
- TechdocsAPI/backend/core/Exceptions.py+1-13
- TechdocsAPI/backend/services/auth/__init__.py+1-2
- TechdocsAPI/backend/services/auth/ops.py+18-19
- TechdocsAPI/backend/services/auth/utils/functools.pyDeleted-9
- TechdocsAPI/backend/utils/Gemini_Prompt.txtDeleted-177
- TechdocsAPI/backend/utils/prompt.txt+7-8
- TechdocsAPI/requirements.txt+2-5
- scripts/test.py+11-13
- temp.pyDeleted-21
- testing/logs_2024_01_07_16_08_04.logDeleted-23
- testing/pack/DBQueries.py+61-29
- testing/pack/functools.py+72-39
- testing/test.py+29-7
7 unmodified lines8910111213141516171819202122232 unmodified lines26272829303132333435363738394041424344454647484950517 unmodified linesfrom backend.utils import DBConnectionfrom backend.core.ConfigEnv import configfrom langchain_community.llms import Clarifaifrom langchain.chains import LLMChainfrom langchain.prompts import PromptTemplateapp = FastAPI(title="Techdocs",version="V0.0.1",description="API for automatic code documentation generation!",)from backend import router2 unmodified linestest_conn = DBConnection.get_client().get_server_info()# send prompt wizardcoderLM-70b-instruct-GGUF modelwith 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 = prompt | llmapp.state.llmchain = llmchainapp.state.templates = Jinja2Templates(directory="./backend/templates")except mysql.connector.Error as err:raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(err))7 unmodified lines8910111213141516171819202122232 unmodified lines2627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737 unmodified linesfrom backend.utils import DBConnectionfrom backend.core.ConfigEnv import configfrom langchain.llms import Clarifaifrom langchain.chains import LLMChainfrom langchain.prompts import PromptTemplatefrom fastapi_mail import ConnectionConfig, FastMailapp = FastAPI(title="Techdocs",version="V0.0.1",description="API for automatic code documentation generation!")from backend import router2 unmodified linestest_conn = DBConnection.get_client().get_server_info()# send prompt wizardcoderLM-70b-instruct-GGUF modelwith 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 = llmchainconf = ConnectionConfig(MAIL_USERNAME=config.MAIL_USERNAME,MAIL_PASSWORD=config.MAIL_PASSWORD,MAIL_FROM=config.MAIL_FROM,MAIL_PORT=587,MAIL_SERVER="smtp.gmail.com",MAIL_STARTTLS=True,MAIL_SSL_TLS=False,TEMPLATE_FOLDER="backend/templates",USE_CREDENTIALS = True,VALIDATE_CERTS = True# MAIL_TLS=True,# MAIL_SSL=False)app.state.mail_client = FastMail(conf)app.state.templates = Jinja2Templates(directory="./backend/templates")except mysql.connector.Error as err:raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(err))
13 unmodified lines141516171819202122232425262713 unmodified linesJWT_SECRET_KEY:strJWT_REFRESH_SECRET_KEY:strJWT_VERIFICATION_SECRET_KEY:str# GOOGLE_API_KEY:strAPP_ID:strUSER_ID:strMODEL_ID:strCLARIFAI_PAT:strMODEL_VERSION_ID:strMAIL_SERVER_URL:strMAIL_USERNAME:strMAIL_PASSWORD:strMAIL_FROM:str13 unmodified lines1415161718192021222324252613 unmodified linesJWT_SECRET_KEY:strJWT_REFRESH_SECRET_KEY:strJWT_VERIFICATION_SECRET_KEY:str# OPENAI_KEY:strAPP_ID:strUSER_ID:strMODEL_ID:strCLARIFAI_PAT:strMODEL_VERSION_ID:strMAIL_USERNAME:strMAIL_PASSWORD:strMAIL_FROM:str
18 unmodified lines19202122232425262728293018 unmodified linescontent=repr(exec))@app.exception_handler(EmailNotSentException)async def email_not_sent(request: Request, exec: EmailNotSentException):return JSONResponse(status_code=status.HTTP_403_FORBIDDEN,content=repr(exec))@app.exception_handler(InvalidCredentialsException)async def handle_login_failed(request: Request, exec: InvalidCredentialsException):return JSONResponse(status_code=status.HTTP_403_FORBIDDEN,18 unmodified lines19202122232418 unmodified linescontent=repr(exec))@app.exception_handler(InvalidCredentialsException)async def handle_login_failed(request: Request, exec: InvalidCredentialsException):return JSONResponse(status_code=status.HTTP_403_FORBIDDEN,
53 unmodified lines5455565758596061626364656667686953 unmodified linesself.status = 'EmailNotVerifiedException'def __repr__(self):return "exception.EmailNotVerifiedException()"class EmailNotSentException(Exception):def __init__(self):self.set_statuses()super(EmailNotSentException, self).__init__()def set_statuses(self):self.status = 'EmailNotSentException'def __repr__(self):return "exception.EmailNotSentException()"53 unmodified lines5455565753 unmodified linesself.status = 'EmailNotVerifiedException'def __repr__(self):return "exception.EmailNotVerifiedException()"
123from .ops import *from .utils.JWTBearer import *from .utils.functools import *12from .ops import *from .utils.JWTBearer import *
123456 unmodified lines121314151617181913 unmodified lines3334353637383940414243444546474849505152535455565754 unmodified lines11211311411511611711811 unmodified lines1301311321331341351361377 unmodified lines1451461471481491501516 unmodified lines1581591601611621633 unmodified lines167168169from .utils.auth_funcs import *from .utils.functools import *from .utils.JWTBearer import *from backend.models import *from backend.services.db.utils.DBQueries import DBQueries6 unmodified linesfrom pydantic import ValidationErrorfrom jose import jwt# BASE_URL = "http://127.0.0.1:8000"BASE_URL = "https://caffeinecrew-techdocs.hf.space"async def ops_signup(bgtasks: BackgroundTasks, response_result: GeneralResponse, data: UserAuth):"""Wrapper method to handle signup process.13 unmodified lines# user with the entered credentials already existsraise ExistingUserException(response_result)verifiction_token = Auth.create_access_token(f"{data.username} {data.email}", secret_name='VERIFICATION')verification_link = f"{BASE_URL}/auth/verify/{verifiction_token}"email_body_params = {"username": data.username,"verify_link": verification_link}details = {"recipients": [data.email],"subject": "Welcome to Techdocs:[Account Verification]","template_name": "email_verification.html","template_kwargs": email_body_params}status = post_request(url=config.MAIL_SERVER_URL, data=details, headers=None)if status != 200:raise EmailNotSentException()DBQueries.insert_to_database('auth', (data.username, Auth.get_password_hash(data.password), "", 0),['username', 'password', 'email', 'is_verified'])54 unmodified linesapikey = APIKey(api_key=apikey)return apikeydef ops_inference(source_code:str,api_key:str,username:str):response_result = GeneralResponse.get_instance(data={},11 unmodified linesdef generate_docstring(source_code_message: str):llm_response = app.state.llmchain.invoke({"instruction": source_code_message})print(llm_response)docstring = Inference(docstr=llm_response)7 unmodified linespayload = jwt.decode(token, config.JWT_VERIFICATION_SECRET_KEY, algorithms=[config.ALGORITHM])token_data = TokenPayload(**payload)if datetime.fromtimestamp(token_data.exp)< datetime.now():return app.state.templates.TemplateResponse("verification_failure.html", context={"request": request})6 unmodified linesprint(registered_email[0][0])if registered_email[0][0]:return app.state.templates.TemplateResponse("verification_failure.html", context={"request": request})DBQueries.update_data_in_database('auth','is_verified',f"username='{username}'", (True,))DBQueries.update_data_in_database('auth','email',f"username='{username}'", email)3 unmodified linesexcept (jwt.JWTError, ValidationError):return app.state.templates.TemplateResponse("verification_failure.html", context={"request": request})12346 unmodified lines1112131415161718192013 unmodified lines3435363738394041424344454647484950515253545554 unmodified lines11011111211311411511611711 unmodified lines1291301311321331341357 unmodified lines1431441451461471486 unmodified lines1551561571581591601613 unmodified lines165166167168from .utils.auth_funcs import *from .utils.JWTBearer import *from backend.models import *from backend.services.db.utils.DBQueries import DBQueries6 unmodified linesfrom pydantic import ValidationErrorfrom jose import jwtfrom fastapi_mail import MessageSchema, MessageType# import openai# from transformers import RobertaTokenizer, T5ForConditionalGenerationasync def ops_signup(bgtasks: BackgroundTasks, response_result: GeneralResponse, data: UserAuth):"""Wrapper method to handle signup process.13 unmodified lines# user with the entered credentials already existsraise ExistingUserException(response_result)verifiction_token = Auth.create_access_token(f"{data.username} {data.email}", secret_name='VERIFICATION')verification_link = f"http://localhost:8000/auth/verify/{verifiction_token}"email_body_params = {"username": data.username,"verify_link": verification_link}message = MessageSchema(subject="Welcome to Techdocs:[Account Verification]",recipients=[data.email], # List of recipients, as many as you can passtemplate_body=email_body_params,subtype=MessageType.html)bgtasks.add_task(app.state.mail_client.send_message, message=message, template_name="email_verification.html")# await app.state.mail_client.send_message(message=message, template_name="email_verification.html")DBQueries.insert_to_database('auth', (data.username, Auth.get_password_hash(data.password), "", 0),['username', 'password', 'email', 'is_verified'])54 unmodified linesapikey = APIKey(api_key=apikey)return apikeydef ops_inference(source_code:str,api_key:str,username:str):response_result = GeneralResponse.get_instance(data={},11 unmodified linesdef generate_docstring(source_code_message: str):llm_response = app.state.llmchain.run({"instruction": source_code_message})docstring = Inference(docstr=llm_response)7 unmodified linespayload = jwt.decode(token, config.JWT_VERIFICATION_SECRET_KEY, algorithms=[config.ALGORITHM])token_data = TokenPayload(**payload)if datetime.fromtimestamp(token_data.exp)< datetime.now():return app.state.templates.TemplateResponse("verification_failure.html", context={"request": request})6 unmodified linesprint(registered_email[0][0])if registered_email[0][0]:return app.state.templates.TemplateResponse("verification_failure.html", context={"request": request})DBQueries.update_data_in_database('auth','is_verified',f"username='{username}'", (True,))DBQueries.update_data_in_database('auth','email',f"username='{username}'", email)3 unmodified linesexcept (jwt.JWTError, ValidationError):return app.state.templates.TemplateResponse("verification_failure.html", context={"request": request})
123456789import requestsfrom typing import Any, Dictimport json
def post_request(url: str, data: Dict[str, Any], headers: Dict[str, str]=None): json_data = json.dumps(data) headers = {'Content-type': 'application/json', 'Accept': 'application/json'} response = requests.post(url, data=json_data, headers=headers) return response.status_code123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177<|im_start|>userYou are an expert Code Documentation writer. Your job is to document Python codebases. The Documentation should be in "Goolge Style Python Docstrings". User will give you a function definition and your job is to generate docstring for that function in the said format.Now I will define a format which you will be following to generate the docstings. For each function definition, you will generate the following:1. Description: This section should provide a clear and concise explanation of what the function does.2. Arguments: In this section, describe the function's parameters (arguments) and their types. Include both mandatory and optional arguments. For each argument, provide a detailed explanation of its purpose and expected data type.3. Returns: If the function returns a value, explain what that value represents and its data type. If the function doesn't return anything (i.e., it has a None return type), mention that explicitly.4. Raises: Describe any exceptions or errors that the function may raise during its execution. Specify the conditions under which these exceptions might occur.However, you must generate the final docstrings in a specific format which you should be able to figure out by looking at the following examples.
Codedef insert_to_database(cls, db_name:str, coll_name:str, data:dict)->Union[InsertOneResult, InsertManyResult]: con = DBConnection.get_client() mydb = con[db_name] mycol = mydb[coll_name]
if isinstance(data, list): return mycol.insert_many(data) else: return mycol.insert_one(data)
"""insert a single record or iterable of records to the database.
Args: db_name (str): name of the database coll_name (str): name of the collection data (dict): data to be inserted
Returns: An instance of class: pymongo.results.InsertOneResult or pymongo.results.InsertManyResult"""
Codedef signup(response_result: FrontendResponseModel, data: Union[UserAuth,BulkSignup]): if isinstance(data, UserAuth): # querying database to check if user already exist user = DBQueries.filtered_db_search("Auth", data.role, [], AADHAR=data.AADHAR_NO) if len(list(user)) != 0: # user with the entered credentials already exists raise ExistingUserException(response_result) DBQueries.insert_to_database("Auth", data.role, userinfo) # saving user to database response_result['status'] = f'success' response_result['message'] = [f'User with this AADHAR NO created successfully']
else: AADHAR_NOS = data.AADHAR_NOS passwords = data.passwords village_name = data.village_name
users = DBQueries.filtered_db_search("Auth", role_manager.user, ["_id","password","village_name"], search_idxs="AADHAR":"$in":AADHAR_NOS) users = [user["AADHAR"] for user in users]
invalid_users = [] valid_users = [] users_created = []
for user in zip(AADHAR_NOS,passwords): if user[0] in users: invalid_users.append(user[0]) else: userinfo["AADHAR"] = user[0] userinfo["password"] = Auth.get_password_hash(user[1]) valid_users.append(userinfo) users_created.append(user[0])
if len(valid_users)!=0: DBQueries.insert_to_database("Auth", role_manager.user, valid_users) # saving user to database response_result['status'] = f'success' response_result['message'] = [f'Users created successfully'] else: response_result['status'] = f'failure' response_result['message'] = [f'No users created']
"""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."""
Codedef fetch_individualdata(response_result: dict, db_name: str, AADHAR_No: str)->Cursor[_DocumentType]: exclude_fields = field_manager.get_form_fields(FormData, exclude=["fam_info"]) exclude_fields += ["_id","timestamp","volunteer_id"] indivdata = [docs for docs in DBQueries.filtered_db_search(db_name,collection_names["fam_data"],exclude_fields,search_idxs="fam_info.AADHAR_No":AADHAR_No)] if len(indivdata) == 0: raise InfoNotFoundException(response_result, "person with this id does not exist in the database") fam_members = [doc for doc in indivdata[0]["fam_info"] if doc["AADHAR_No"] == AADHAR_No]
return fam_members[0]
"""Wrapper function to fetch individual data from the database. Args: response_result (dict): response result to be returned in case of error. db_name (str): name of the database. AADHAR_No (str): id of the respondent. Returns: Cursor[_DocumentType]: A cursor containing the data of the individual fetched from the database."""
Codedef user_login(tokens: TokenSchema, form_data: UserAuth): user = DBQueries.filtered_db_search("Auth", form_data.role, ['_id'], AADHAR=form_data.AADHAR_NO) data = list(user) if len(data) == 0: # no such users in the database raise LoginFailedException(tokens)
if not Auth.verify_password(form_data.password, data[0]['password']) or \ not Auth.verify_village_name(data[0]['village_name'], form_data.village_name): # incorrect credentials raise LoginFailedException(tokens)
# successful login sub = form_data.AADHAR_NO + "_" + form_data.role + "_" + form_data.village_name tokens['access_token'] = Auth.create_access_token(sub) tokens['refresh_token'] = Auth.create_refresh_token(sub) tokens['status'] = 'login successful' tokens['role'] = form_data.role
"""Wrapper method to handle sign-ins and generating `access_tokens`.
Args: tokens: TokenSchema. A TypedDict to return `access_token`, `refresh_access_tokens`, `status`, and `role` related information to grant genuine users their respective level of authorization according to the maintained hierarchy. form_data: UserAuth. Sign-in credentials entered by the users at the time of signing in.
Raises: LoginFailedException: If no user with entered credentials exists."""
Codedef token_validation(token: str) -> bool: try: payload = jwt.decode( token, settings.JWT_SECRET_KEY, algorithms=[settings.ALGORITHM] ) token_data = TokenPayload(**payload)
if datetime.fromtimestamp(token_data.exp) < datetime.now(): return False
except(jwt.JWTError, ValidationError): return False
return True
"""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."""
Code{instruction} <|im_end|><|im_start|>assistant1234567891011121314151617<|im_start|>userYou are an expert Code Documentation writer. Your job is to document Python codebases. The Documentation should be in "Goolge Style Python Docstrings". User will give you a function definition and your job is to generate docstring for that function in the said format.Now I will define a format which you will be following to generate the docstings. For each function definition, you will generate the following:1. Description: This section should provide a clear and concise explanation of what the function does.2. Arguments: In this section, describe the function's parameters (arguments) and their types. Include both mandatory and optional arguments. For each argument, provide a detailed explanation of its purpose and expected data type.3. Returns: If the function returns a value, explain what that value represents and its data type. If the function doesn't return anything (i.e., it has a None return type), mention that explicitly.4. Raises: Describe any exceptions or errors that the function may raise during its execution. Specify the conditions under which these exceptions might occur.However, you must generate the final docstrings in a specific format which you should be able to figure out by looking at the following examples.Please follow Google docstring style guidelines to generate a docstring for the query function given by the user.Instructions: {instruction}Your task is to generate a docstring for the above query.Your Response: <|im_end|><|im_start|>assistant12345678910111213141516You are an AI Coding Assistant, and your role is to create comprehensive and highly informative docstrings for Python functions entered by the user. A well-structured docstring is essential for helping developers understand and use the function effectively. A standard Python docstring typically consists of the following sections:1. Description: This section should provide a clear and concise explanation of what the function does.2. Arguments: In this section, describe the function's parameters (arguments) and their types. Include both mandatory and optional arguments. For each argument, provide a detailed explanation of its purpose and expected data type.3. Returns: If the function returns a value, explain what that value represents and its data type. If the function doesn't return anything (i.e., it has a None return type), mention that explicitly.4. Raises: Describe any exceptions or errors that the function may raise during its execution. Specify the conditions under which these exceptions might occur.Please follow Google docstring style guidelines to generate a docstring for the query function given by the user.Instructions: {instruction}Your task is to generate a docstring for the above query.Response:
4 unmodified lines567891011121314154 unmodified linespython-jose[cryptography]passlib[bcrypt]mysql-connector-pythonmysql# langchain-google-genaipydantic[email]langchainlangchain-communityPillowjinja2clarifai4 unmodified lines567891011124 unmodified linespython-jose[cryptography]passlib[bcrypt]mysql-connector-pythonpydantic[email]langchainclarifaiPillowfastapi_mail==1.3.1
1234567891011121314151617181910 unmodified lines3031323334353637383940419 unmodified lines515253545556from dotenv import load_dotenvload_dotenv()import osimport mysql.connectorfrom mysql.connector import errorcodeconfig = {"host": os.environ.get("HOSTNAME"),"user": os.environ.get("UID"),"password": os.environ.get("PASSWORD"),"database": os.environ.get("DATABASE"),}print(os.environ.get("HOSTNAME"))try:cnx = mysql.connector.connect(**config)10 unmodified linescursor.execute("DROP TABLE IF EXISTS api_key")cursor.execute("DROP TABLE IF EXISTS auth")cursor.execute("CREATE TABLE IF NOT EXISTS auth(username VARCHAR(15) PRIMARY KEY, password TEXT, email VARCHAR(50))")cursor.execute("CREATE TABLE IF NOT EXISTS api_key(username VARCHAR(15),apikey TEXT, FOREIGN KEY (username) REFERENCES auth(username))")cursor.execute("ALTER TABLE auth ADD is_verified BOOLEAN NOT NULL DEFAULT(false)")# QUERY = ('INSERT INTO {coll_name} '9 unmodified lines# for i in cursor.fetchall():# print(i)cnx.commit()cursor.close()cnx.close()12345678910111213141516171810 unmodified lines29303132333435369 unmodified lines464748495051525354from dotenv import load_dotenvload_dotenv()import osimport mysql.connectorfrom mysql.connector import errorcodeconfig={'host':os.environ.get("HOSTNAME"),'user':os.environ.get("UID"),'password':os.environ.get("PASSWORD"),'database':os.environ.get("DATABASE")}print(config)try:cnx = mysql.connector.connect(**config)10 unmodified linescursor.execute("DROP TABLE IF EXISTS api_key")cursor.execute("DROP TABLE IF EXISTS auth")cursor.execute("CREATE TABLE IF NOT EXISTS auth(username VARCHAR(15) PRIMARY KEY, password TEXT, email VARCHAR(50))")cursor.execute("CREATE TABLE IF NOT EXISTS api_key(username VARCHAR(15),apikey TEXT, FOREIGN KEY (username) REFERENCES auth(username))")cursor.execute("ALTER TABLE auth ADD is_verified BOOLEAN NOT NULL DEFAULT(false)")# QUERY = ('INSERT INTO {coll_name} '9 unmodified lines# for i in cursor.fetchall():# print(i)cnx.commit()cursor.close()cnx.close()
123456789101112131415161718192021import requestsimport json
def post_request(url, data, headers=None): data = json.dumps(data) headers = {'Content-type': 'application/json', 'Accept': 'application/json'} response = requests.post(url, data=data, headers=headers) return response.status_code, response.json()
email_body_params = { "username": "mayo", "verify_link": "new hai yeh bro agar ye aya toh maja aya"}details = { "recipients": ["mayureshagashe2002@outlook.com", "alfatrion123@gmail.com"], "subject": "Welcome to Techdocs:[Account Verification]", "template_name": "email_verification.html", "template_kwargs": email_body_params }print(post_request("https://api.techdocs.caffienecrewhacks.tech/api/send", details))12345678910111213141516171819202122232024-01-07 16:08:04,077:INFO:Logs generated at "testing\logs_2024_01_07_16_08_04.log". For detailed logs check the file.2024-01-07 16:08:04,078:INFO:Docstrings generation started for "testing/*.py" files2024-01-07 16:08:04,078:INFO:Working on "testing\*.py"2024-01-07 16:08:04,093:INFO:Working on "testing\test.py"2024-01-07 16:08:07,627:INFO:Docstring generated for def add2024-01-07 16:08:07,629:INFO:==================================================2024-01-07 16:08:07,631:INFO:Docstrings generation completed for "testing\.*py". Time Taken: 0:00:03.5521572024-01-07 16:08:07,632:INFO:>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>2024-01-07 16:08:07,632:INFO:Working on "testing\pack\*.py"2024-01-07 16:08:07,635:INFO:Working on "testing\pack\DBQueries.py"2024-01-07 16:08:13,942:INFO:Docstring generated for def insert_to_database2024-01-07 16:08:18,222:INFO:Docstring generated for def fetch_data_from_database2024-01-07 16:08:25,204:INFO:Docstring generated for def update_data_in_database2024-01-07 16:08:25,206:INFO:==================================================2024-01-07 16:08:25,207:INFO:Working on "testing\pack\functools.py"2024-01-07 16:08:30,500:INFO:Docstring generated for def get_access_token2024-01-07 16:08:34,476:INFO:Docstring generated for def request_inference2024-01-07 16:08:40,210:INFO:Docstring generated for def update_file2024-01-07 16:08:45,481:INFO:Docstring generated for def issue_api_key2024-01-07 16:08:50,504:INFO:Docstring generated for def signup2024-01-07 16:08:50,507:INFO:==================================================2024-01-07 16:08:50,508:INFO:Docstrings generation completed for "testing\pack\.*py". Time Taken: 0:00:42.8754582024-01-07 16:08:50,508:INFO:>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>8 unmodified lines9101112131415161718192021222324257 unmodified lines333435363738394041424344454647487 unmodified lines565758596061626364656667686970717273747576777879808 unmodified lines@classmethoddef insert_to_database(cls, table_name: str, data: Union[Tuple, List[Tuple]], cols: List[str]=None):"""Wrapper method to insert data to the database.Args:table_name (str): Name of the table in the database.data (Union[Tuple, List[Tuple]]): Data to be inserted in the table. It can be a single tuple or a list of tuples.cols (List[str], optional): List of columns in the table. If not provided, all columns will be used.Raises:ValidationError: If data is not a tuple or a list of tuples.InternalServerError: If an error occurs while inserting data to the database."""con = DBConnection.get_client()cursor = con.cursor()QUERY = f"INSERT INTO {{table_name}} ({','.join(cols)}) VALUES ".format(table_name=table_name)7 unmodified lines@classmethoddef fetch_data_from_database(cls, table_name: str, cols_to_fetch: Union[str, List[str]], where_clause: str=None):"""Method to fetch data from database using a SQL query.Args:table_name: str. Name of the table to fetch data from.cols_to_fetch: Union[str, List[str]]. Columns to fetch from the table.where_clause: str. Optional. Where clause to filter the data.Returns:List. List of tuples containing the fetched data."""con = DBConnection.get_client()cursor = con.cursor()if isinstance(cols_to_fetch, str):7 unmodified lines@classmethoddef 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):"""Updates the values of the columns in the table defined by `table_name`where the condition defined by `where_clause` is met.Args:table_name: str. Name of the table.cols_to_update: Union[str, List[str]]. Column/s to be updated. If asingle column is to be updated, pass it as a string.If multiple columns are to be updated, pass them as alist of strings.where_clause: str. Conditions to be met by the rows to be updated.If no condition is to be imposed, pass it as None.new_values: Union[str, List[str]]. New values to be set in thecolumns. If a single column is to be updated, pass thenew value as a string. If multiple columns are to beupdated, pass the new values as a list of strings.Returns:bool. True if update was successful, False otherwise."""con = DBConnection.get_client()cursor = con.cursor()if isinstance(cols_to_update, str):8 unmodified lines91011121314151617181920212223242526272829303132333435363738397 unmodified lines47484950515253545556575859606162636465666768697071727374757677787980818283847 unmodified lines92939495969798991001011021031041051061071081091101111128 unmodified lines@classmethoddef insert_to_database(cls, table_name: str, data: Union[Tuple, List[Tuple]], cols: List[str]=None):"""This method is used to insert data into a specified table in the database.Args:table_name (str): The name of the table into which data will be inserted.data (Union[Tuple, List[Tuple]]): The data to be inserted into the table. This can be a tuple or a list of tuples, where each tuple represents a row of data.cols (List[str], optional): A list of column names in the table. If not provided, the method will assume that all columns are included. Defaults to None.Raises:NoneReturns:None"""'\n This method is used to insert data into a specified table in the database.\n\n Args:\n table_name (str): The name of the table into which data will be inserted.\n data (Union[Tuple, List[Tuple]]): The data to be inserted into the table. This can be a tuple or a list of tuples, where each tuple represents a row of data.\n cols (List[str], optional): A list of column names in the table. If not provided, the method will assume that all columns are included. Defaults to None.\n\n Raises:\n None\n\n Returns:\n None\n\n ''\n This method is used to insert data into a specified table in the database.\n\n Args:\n table_name (str): The name of the table into which data will be inserted.\n data (Union[Tuple, List[Tuple]]): The data to be inserted into the table. This can be a tuple or a list of tuples, where each tuple represents a row of data.\n cols (List[str], optional): A list of column names in the table. If not provided, the method will assume that all columns are included. Defaults to None.\n\n Raises:\n None\n\n Returns:\n None\n\n ''\n This method is used to insert data into a specified table in the database.\n\n Args:\n table_name (str): The name of the table into which data will be inserted.\n data (Union[Tuple, List[Tuple]]): The data to be inserted into the table. This can be a tuple or a list of tuples, where each tuple represents a row of data.\n cols (List[str], optional): A list of column names in the table. If not provided, the method will assume that all columns are included. Defaults to None.\n\n Raises:\n None\n\n Returns:\n None\n\n ''\n This method is used to insert data into a specified table in the database.\n\n Args:\n table_name (str): The name of the table into which data will be inserted.\n data (Union[Tuple, List[Tuple]]): The data to be inserted into the table. This can be a tuple or a list of tuples, where each tuple represents a row of data.\n cols (List[str], optional): A list of column names in the table. If not provided, the method will assume that all columns are included. Defaults to None.\n\n Raises:\n None\n\n Returns:\n None\n\n ''\n This method is used to insert data into a specified table in the database.\n\n Args:\n table_name (str): The name of the table into which data will be inserted.\n data (Union[Tuple, List[Tuple]]): The data to be inserted into the table. This can be a tuple or a list of tuples, where each tuple represents a row of data.\n cols (List[str], optional): A list of column names in the table. If not provided, the method will assume that all columns are included. Defaults to None.\n\n Raises:\n None\n\n Returns:\n None\n\n ''\n This method is used to insert data into a specified table in the database.\n\n Args:\n table_name (str): The name of the table into which data will be inserted.\n data (Union[Tuple, List[Tuple]]): The data to be inserted into the table. This can be a tuple or a list of tuples, where each tuple represents a row of data.\n cols (List[str], optional): A list of column names in the table. If not provided, the method will assume that all columns are included. Defaults to None.\n\n Raises:\n None\n\n Returns:\n None\n\n ''\n This method is used to insert data into a specified table in the database.\n\n Args:\n table_name (str): The name of the table into which data will be inserted.\n data (Union[Tuple, List[Tuple]]): The data to be inserted into the table. This can be a tuple or a list of tuples, where each tuple represents a row of data.\n cols (List[str], optional): A list of column names in the table. If not provided, the method will assume that all columns are included. Defaults to None.\n\n Raises:\n None\n\n Returns:\n None\n\n ''\n This method is used to insert data into a specified table in the database.\n\n Args:\n table_name (str): The name of the table into which data will be inserted.\n data (Union[Tuple, List[Tuple]]): The data to be inserted into the table. This can be a tuple or a list of tuples, where each tuple represents a row of data.\n cols (List[str], optional): A list of column names in the table. If not provided, the method will assume that all columns are included. Defaults to None.\n\n Raises:\n None\n\n Returns:\n None\n\n ''\n This method is used to insert data into a specified table in the database.\n\n Args:\n table_name (str): The name of the table into which data will be inserted.\n data (Union[Tuple, List[Tuple]]): The data to be inserted into the table. This can be a tuple or a list of tuples, where each tuple represents a row of data.\n cols (List[str], optional): A list of column names in the table. If not provided, the method will assume that all columns are included. Defaults to None.\n\n Raises:\n None\n\n Returns:\n None\n ''\n This method is used to insert data into a specified table in the database.\n\n Args:\n table_name (str): The name of the table into which data will be inserted.\n data (Union[Tuple, List[Tuple]]): The data to be inserted into the table. This can be a tuple or a list of tuples.\n cols (List[str], optional): A list of column names in the table. If not provided, the method will assume that all columns are included. Defaults to None.\n\n Raises:\n None\n\n Returns:\n None\n 'con = DBConnection.get_client()cursor = con.cursor()QUERY = f"INSERT INTO {{table_name}} ({','.join(cols)}) VALUES ".format(table_name=table_name)7 unmodified lines@classmethoddef fetch_data_from_database(cls, table_name: str, cols_to_fetch: Union[str, List[str]], where_clause: str=None):"""This method is a class method that fetches data from a specified table in the database based on the provided column names and,optionally, a WHERE clause.Args:- table_name: A string representing the name of the table from which to fetch data.- cols_to_fetch: A string or a list of strings representing the column(s) to fetch from the table. If a single string,it will be treated as a comma-separated list of column names.- where_clause: An optional string representing a WHERE clause to filter the fetched data. Defaults to None.Returns:- cursor.fetchall(): A list of tuples representing the fetched data. Each tuple corresponds to a row in the result set,and contains the values of the fetched columns in the order specified.Raises:- No exceptions are explicitly raised by this method. However, underlying database operations may raise exceptions, whichare not handled or propagated by this method. It is the responsibility of the caller to handle any exceptions that may occur."""'\n This method is a class method that fetches data from a specified table in the database based on the provided column names and,\n optionally, a WHERE clause.\n\n Args:\n - table_name: A string representing the name of the table from which to fetch data.\n - cols_to_fetch: A string or a list of strings representing the column(s) to fetch from the table. If a single string,\n it will be treated as a comma-separated list of column names.\n - where_clause: An optional string representing a WHERE clause to filter the fetched data. Defaults to None.\n\n Returns:\n - cursor.fetchall(): A list of tuples representing the fetched data. Each tuple corresponds to a row in the result set,\n and contains the values of the fetched columns in the order specified.\n\n Raises:\n - No exceptions are explicitly raised by this method. However, underlying database operations may raise exceptions, which\n are not handled or propagated by this method. It is the responsibility of the caller to handle any exceptions that may occur.\n\n ''\n This method is a class method that fetches data from a specified table in the database based on the provided column names and,\n optionally, a WHERE clause.\n\n Args:\n - table_name: A string representing the name of the table from which to fetch data.\n - cols_to_fetch: A string or a list of strings representing the column(s) to fetch from the table. If a single string,\n it will be treated as a comma-separated list of column names.\n - where_clause: An optional string representing a WHERE clause to filter the fetched data. Defaults to None.\n\n Returns:\n - cursor.fetchall(): A list of tuples representing the fetched data. Each tuple corresponds to a row in the result set,\n and contains the values of the fetched columns in the order specified.\n\n Raises:\n - No exceptions are explicitly raised by this method. However, underlying database operations may raise exceptions, which\n are not handled or propagated by this method. It is the responsibility of the caller to handle any exceptions that may occur.\n\n ''\n This method is a class method that fetches data from a specified table in the database based on the provided column names and,\n optionally, a WHERE clause.\n\n Args:\n - table_name: A string representing the name of the table from which to fetch data.\n - cols_to_fetch: A string or a list of strings representing the column(s) to fetch from the table. If a single string,\n it will be treated as a comma-separated list of column names.\n - where_clause: An optional string representing a WHERE clause to filter the fetched data. Defaults to None.\n\n Returns:\n - cursor.fetchall(): A list of tuples representing the fetched data. Each tuple corresponds to a row in the result set,\n and contains the values of the fetched columns in the order specified.\n\n Raises:\n - No exceptions are explicitly raised by this method. However, underlying database operations may raise exceptions, which\n are not handled or propagated by this method. It is the responsibility of the caller to handle any exceptions that may occur.\n\n ''\n This method is a class method that fetches data from a specified table in the database based on the provided column names and,\n optionally, a WHERE clause.\n\n Args:\n - table_name: A string representing the name of the table from which to fetch data.\n - cols_to_fetch: A string or a list of strings representing the column(s) to fetch from the table. If a single string,\n it will be treated as a comma-separated list of column names.\n - where_clause: An optional string representing a WHERE clause to filter the fetched data. Defaults to None.\n\n Returns:\n - cursor.fetchall(): A list of tuples representing the fetched data. Each tuple corresponds to a row in the result set,\n and contains the values of the fetched columns in the order specified.\n\n Raises:\n - No exceptions are explicitly raised by this method. However, underlying database operations may raise exceptions, which\n are not handled or propagated by this method. It is the responsibility of the caller to handle any exceptions that may occur.\n\n ''\n This method is a class method that fetches data from a specified table in the database based on the provided column names and,\n optionally, a WHERE clause.\n\n Args:\n - table_name: A string representing the name of the table from which to fetch data.\n - cols_to_fetch: A string or a list of strings representing the column(s) to fetch from the table. If a single string,\n it will be treated as a comma-separated list of column names.\n - where_clause: An optional string representing a WHERE clause to filter the fetched data. Defaults to None.\n\n Returns:\n - cursor.fetchall(): A list of tuples representing the fetched data. Each tuple corresponds to a row in the result set,\n and contains the values of the fetched columns in the order specified.\n\n Raises:\n - No exceptions are explicitly raised by this method. However, underlying database operations may raise exceptions, which\n are not handled or propagated by this method. It is the responsibility of the caller to handle any exceptions that may occur.\n\n ''\n This method is a class method that fetches data from a specified table in the database based on the provided column names and,\n optionally, a WHERE clause.\n\n Args:\n - table_name: A string representing the name of the table from which to fetch data.\n - cols_to_fetch: A string or a list of strings representing the column(s) to fetch from the table. If a single string,\n it will be treated as a comma-separated list of column names.\n - where_clause: An optional string representing a WHERE clause to filter the fetched data. Defaults to None.\n\n Returns:\n - cursor.fetchall(): A list of tuples representing the fetched data. Each tuple corresponds to a row in the result set,\n and contains the values of the fetched columns in the order specified.\n\n Raises:\n - No exceptions are explicitly raised by this method. However, underlying database operations may raise exceptions, which\n are not handled or propagated by this method. It is the responsibility of the caller to handle any exceptions that may occur.\n\n ''\n This method is a class method that fetches data from a specified table in the database based on the provided column names and,\n optionally, a WHERE clause.\n\n Args:\n - table_name: A string representing the name of the table from which to fetch data.\n - cols_to_fetch: A string or a list of strings representing the column(s) to fetch from the table. If a single string,\n it will be treated as a comma-separated list of column names.\n - where_clause: An optional string representing a WHERE clause to filter the fetched data. Defaults to None.\n\n Returns:\n - cursor.fetchall(): A list of tuples representing the fetched data. Each tuple corresponds to a row in the result set,\n and contains the values of the fetched columns in the order specified.\n\n Raises:\n - No exceptions are explicitly raised by this method. However, underlying database operations may raise exceptions, which\n are not handled or propagated by this method. It is the responsibility of the caller to handle any exceptions that may occur.\n\n ''\n This method is a class method that fetches data from a specified table in the database based on the provided column names and,\n optionally, a WHERE clause.\n\n Args:\n - table_name: A string representing the name of the table from which to fetch data.\n - cols_to_fetch: A string or a list of strings representing the column(s) to fetch from the table. If a single string,\n it will be treated as a comma-separated list of column names.\n - where_clause: An optional string representing a WHERE clause to filter the fetched data. Defaults to None.\n\n Returns:\n - cursor.fetchall(): A list of tuples representing the fetched data. Each tuple corresponds to a row in the result set,\n and contains the values of the fetched columns in the order specified.\n\n Raises:\n - No exceptions are explicitly raised by this method. However, underlying database operations may raise exceptions, which\n are not handled or propagated by this method. It is the responsibility of the caller to handle any exceptions that may occur.\n\n ''\n This method is a class method that fetches data from a specified table in the database based on the provided column names and,\n optionally, a WHERE clause.\n\n Args:\n - table_name: A string representing the name of the table from which to fetch data.\n - cols_to_fetch: A string or a list of strings representing the column(s) to fetch from the table. If a single string,\n it will be treated as a comma-separated list of column names.\n - where_clause: An optional string representing a WHERE clause to filter the fetched data. Defaults to None.\n\n Returns:\n - cursor.fetchall(): A list of tuples representing the fetched data. Each tuple corresponds to a row in the result set,\n and contains the values of the fetched columns in the order specified.\n\n Raises:\n - No exceptions are explicitly raised by this method. However, underlying database operations may raise exceptions, which\n are not handled or propagated by this method. It is the responsibility of the caller to handle any exceptions that may occur.\n ''\n This method is a class method that fetches data from a specified table in the database based on the provided column names and,\n optionally, a WHERE clause.\n\n Args:\n - table_name: A string representing the name of the table from which to fetch data.\n - cols_to_fetch: A string or a list of strings representing the column(s) to fetch from the table. If a single string,\n it will be treated as a comma-separated list of column names.\n - where_clause: An optional string representing a WHERE clause to filter the fetched data. Defaults to None.\n\n Returns:\n - cursor.fetchall(): A list of tuples representing the fetched data. Each tuple corresponds to a row in the result set,\n and contains the values of the fetched columns in the order specified.\n\n Raises:\n - No exceptions are explicitly raised by this method. However, underlying database operations may raise exceptions, which\n are not handled or propagated by this method. It is the responsibility of the caller to handle any exceptions that may occur.\n ''\n This method is a class method that fetches data from a specified table in the database based on the provided column names and,\n optionally, a WHERE clause.\n\n Args:\n - table_name: A string representing the name of the table from which to fetch data.\n - cols_to_fetch: A string or a list of strings representing the column(s) to fetch from the table. If a single string,\n it will be treated as a comma-separated list of column names.\n - where_clause: An optional string representing a WHERE clause to filter the fetched data. Defaults to None.\n\n Returns:\n - cursor.fetchall(): A list of tuples representing the fetched data. Each tuple corresponds to a row in the result set,\n and contains the values of the fetched columns in the order specified.\n\n Raises:\n - No exceptions are explicitly raised by this method. However, underlying database operations may raise exceptions, which\n are not handled or propagated by this method. It is the responsibility of the caller to handle any exceptions that may occur.\n ''\n This method is a class method that fetches data from a specified table in the database based on the provided column names and,\n optionally, a WHERE clause.\n\n Args:\n - table_name: A string representing the name of the table from which to fetch data.\n - cols_to_fetch: A string or a list of strings representing the column(s) to fetch from the table. If a single string,\n it will be treated as a comma-separated list of column names.\n - where_clause: An optional string representing a WHERE clause to filter the fetched data. Defaults to None.\n\n Returns:\n - cursor.fetchall(): A list of tuples representing the fetched data. Each tuple corresponds to a row in the result set,\n and contains the values of the fetched columns in the order specified.\n\n Raises:\n - No exceptions are explicitly raised by this method. However, underlying database operations may raise exceptions, which\n are not handled or propagated by this method. It is the responsibility of the caller to handle any exceptions that may occur.\n ''\n This method is a class method that fetches data from a specified table in the database based on the provided column names and,\n optionally, a WHERE clause.\n\n Args:\n - table_name: A string representing the name of the table from which to fetch data.\n - cols_to_fetch: A string or a list of strings representing the column(s) to fetch from the table. If a single string,\n it will be treated as a comma-separated list of column names.\n - where_clause: An optional string representing a WHERE clause to filter the fetched data. Defaults to None.\n\n Returns:\n - cursor.fetchall(): A list of tuples representing the fetched data. Each tuple corresponds to a row in the result set,\n and contains the values of the fetched columns in the order specified.\n\n Raises:\n - No exceptions are explicitly raised by this method. However, underlying database operations may raise exceptions, which\n are not handled or propagated by this method. It is the responsibility of the caller to handle any exceptions that may occur.\n 'con = DBConnection.get_client()cursor = con.cursor()if isinstance(cols_to_fetch, str):7 unmodified lines@classmethoddef 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):"""This method updates the data in a specified table in the database.Args:table_name (str): The name of the table in which the data needs to be updated.cols_to_update (Union[str, List[str]]): The column(s) to be updated. If a single string, it should end with '=%s'. If a list, it should contain strings, each ending with '=%s'.where_clause (str, optional): The WHERE clause of the SQL query. Defaults to None.new_values (Union[str, List[str]], optional): The new values to be updated in the columns. If a single string, it should be a list of new values. If a list, it should contain the new values for each column. Defaults to None.Returns:bool: Returns True if the data is successfully updated in the database.Raises:Exception: If the database connection fails or the query execution fails."""con = DBConnection.get_client()cursor = con.cursor()if isinstance(cols_to_update, str):
2 unmodified lines3456789101112131415169 unmodified lines2627282930313233343536373839404142439 unmodified lines5354555657585960616263646566676869707172737475767778798081824 unmodified lines878889909192939495969798991001011021032 unmodified linesBASE_URL = 'https://caffeinecrew-techdocs.hf.space'def get_access_token(data, return_refresh_token=False):"""Authenticates and returns the access token.Args:data: dict. User login credentials.Returns:str. The access token."""try:url = BASE_URL + '/auth/login'headers = {'accept': 'application/json'}9 unmodified linesreturn Nonedef request_inference(config, code_block, max_retries=1):"""Request for inference from an external model.Args:config: Config. Configuration dictionary with model credentials,api key, and access token.code_block: str. Code block for which inference is requested.max_retries: int, optional. Number of retries to be made in caseof failure. Defaults to 1.Returns:str: Docstring generated from the model."""if max_retries == 0:return Noneurl = BASE_URL + '/api/inference'9 unmodified linesreturn request_inference(config, code_block, max_retries=max_retries - 1)def update_file(file_path, docstr_code):"""insert a single record or iterable of records to the database.Args:db_name (str): name of the databasecoll_name (str): name of the collectiondata (dict): data to be insertedReturns:An instance of class: pymongo.results.InsertOneResult orpymongo.results.InsertManyResult"""with open(file_path, 'w', errors='ignore') as file:file.write(docstr_code)def issue_api_key(config):"""Issues an API key for a valid userArgs:config (dict): Config dictionary containing `username` and `access_token`of the user.Raises:Exception: If API key generation fails."""try:headers = {'accept': 'application/json', 'Authorization': f"Bearer {config['access_token']}"}response = requests.put(url=BASE_URL + '/auth/regenerate_api_key', headers=headers, data=json.dumps({'username': config['username']}))4 unmodified linesprint(f'$ {e}')def signup(config):"""Sends a request to the server to create a new user account.Args:config (dict): A dictionary containing the following keys:- 'username': The username of the new user.- 'email': The email address of the new user.- 'password': The password of the new user.Raises:Exception: If the request fails or the status code is not 200."""try:headers = {'accept': 'application/json'}response = requests.post(url=BASE_URL + '/auth/signup', headers=headers, data=json.dumps(config))2 unmodified lines345678910111213141516171819202122239 unmodified lines333435363738394041424344454647484950515253545556579 unmodified lines6768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081094 unmodified lines1141151161171181191201211221231241251261271281291301311321331341351362 unmodified linesBASE_URL = 'https://caffeinecrew-techdocs.hf.space'def get_access_token(data, return_refresh_token=False):"""This function sends a POST request to the specified URL to get an access token.Arguments:data (dict): A dictionary containing the credentials required for authentication.return_refresh_token (bool, optional): A flag to indicate if the refresh token should be returned. Defaults to False.Returns:str or tuple: If return_refresh_token is False, the function returns the access token as a string. If return_refresh_token is True, the function returns a tuple containing the access token and the refresh token.Raises:Exception: If an error occurs during the execution of the function, an Exception is raised."""'\n This function sends a POST request to the specified URL to get an access token.\n \n Arguments:\n data (dict): A dictionary containing the credentials required for authentication.\n return_refresh_token (bool, optional): A flag to indicate if the refresh token should be returned. Defaults to False.\n \n Returns:\n str or tuple: If return_refresh_token is False, the function returns the access token as a string. If return_refresh_token is True, the function returns a tuple containing the access token and the refresh token.\n \n Raises:\n Exception: If an error occurs during the execution of the function, an Exception is raised.\n ''\n This function sends a POST request to the specified URL to get an access token.\n \n Arguments:\n data (dict): A dictionary containing the credentials required for authentication.\n return_refresh_token (bool, optional): A flag to indicate if the refresh token should be returned. Defaults to False.\n \n Returns:\n str or tuple: If return_refresh_token is False, the function returns the access token as a string. If return_refresh_token is True, the function returns a tuple containing the access token and the refresh token.\n \n Raises:\n Exception: If an error occurs during the execution of the function, an Exception is raised.\n 'try:url = BASE_URL + '/auth/login'headers = {'accept': 'application/json'}9 unmodified linesreturn Nonedef request_inference(config, code_block, max_retries=1):"""Usage: request_inference(config, code_block, max_retries=1)Purpose:This function sends a POST request to the API server to perform code inference.Arguments:- config (dict): A dictionary containing the necessary authentication details like 'access_token', 'api_key' and 'username'.- code_block (str): The code block that needs to be inferenced.- max_retries (int, optional): The maximum number of times the function should retry in case of an error. Defaults to 1.Returns:- str: The docstring of the inferenced code block.Raises:- Exception: If the maximum number of retries (specified by max_retries) is reached and the API server still returns an error.""""\nUsage: request_inference(config, code_block, max_retries=1)\n\nPurpose:\nThis function sends a POST request to the API server to perform code inference.\n\nArguments:\n- config (dict): A dictionary containing the necessary authentication details like 'access_token', 'api_key' and 'username'.\n- code_block (str): The code block that needs to be inferenced.\n- max_retries (int, optional): The maximum number of times the function should retry in case of an error. Defaults to 1.\n\nReturns:\n- str: The docstring of the inferenced code block.\n\nRaises:\n- Exception: If the maximum number of retries (specified by max_retries) is reached and the API server still returns an error.\n""\nUsage: request_inference(config, code_block, max_retries=1)\n\nPurpose:\nThis function sends a POST request to the API server to perform code inference.\n\nArguments:\n- config (dict): A dictionary containing the necessary authentication details like 'access_token', 'api_key' and 'username'.\n- code_block (str): The code block that needs to be inferenced.\n- max_retries (int, optional): The maximum number of times the function should retry in case of an error. Defaults to 1.\n\nReturns:\n- str: The docstring of the inferenced code block.\n\nRaises:\n- Exception: If the maximum number of retries (specified by max_retries) is reached and the API server still returns an error.\n"if max_retries == 0:return Noneurl = BASE_URL + '/api/inference'9 unmodified linesreturn request_inference(config, code_block, max_retries=max_retries - 1)def update_file(file_path, docstr_code):"""This function updates the docstring of a Python file.Arguments:file_path (str): The path of the Python file to be updated.docstr_code (str): The new docstring to be written to the file.Returns:NoneRaises:FileNotFoundError: If the specified file does not exist.IOError: If there is an error while writing to the file."""'\n This function performs some operation on the given arguments.\n\n Arguments:\n arg1 (int): The first argument. A positive integer.\n arg2 (float): The second argument. A positive floating point number.\n arg3 (str): The third argument. A string containing only alphabets.\n arg4 (bool): The fourth argument. A boolean value.\n\n Returns:\n None\n\n Raises:\n TypeError: If any argument is not of the expected type.\n ValueError: If arg1 is less than or equal to zero, or if arg2 is not a positive number, or if arg3 contains any non-alphabetic character, or if arg4 is not a boolean value.\n ''\n This function updates the docstring of a Python file.\n\n Arguments:\n file_path (str): The path of the Python file to be updated.\n docstr_code (str): The new docstring to be written to the file.\n\n Returns:\n None\n\n Raises:\n FileNotFoundError: If the specified file does not exist.\n IOError: If there is an error while writing to the file.\n 'with open(file_path, 'w', errors='ignore') as file:file.write(docstr_code)def issue_api_key(config):"""This function generates a new API key for the given user.Arguments:config: dict, A dictionary containing the user's configuration details.- access_token: str, The user's access token.- username: str, The user's username.Returns:None, Prints the new API key to the console.Raises:Exception, If the API key generation fails. The error message will be printed to the console.""""\n This function generates a new API key for the given user.\n\n Arguments:\n config: dict, A dictionary containing the user's configuration details.\n - access_token: str, The user's access token.\n - username: str, The user's username.\n\n Returns:\n None, Prints the new API key to the console.\n\n Raises:\n Exception, If the API key generation fails. The error message will be printed to the console.\n\n ""\n This function generates a new API key for the given user.\n\n Arguments:\n config: A dictionary containing the user's configuration details.\n - access_token: str, The user's access token.\n - username: str, The user's username.\n\n Returns:\n None, prints the new API key to the console.\n\n Raises:\n Exception, If the API key generation fails. The error message will be printed to the console.\n "try:headers = {'accept': 'application/json', 'Authorization': f"Bearer {config['access_token']}"}response = requests.put(url=BASE_URL + '/auth/regenerate_api_key', headers=headers, data=json.dumps({'username': config['username']}))4 unmodified linesprint(f'$ {e}')def signup(config):"""This function is used to sign up a user with the provided configuration.Arguments:config: dictA dictionary containing the user's signup information.Returns:NoneRaises:ExceptionIf the username or email already exists.If there's a general error during the sign up process.""""\n This function is used to sign up a user with the provided configuration.\n\n Arguments:\n config: dict\n A dictionary containing the user's signup information.\n\n Returns:\n None\n\n Raises:\n Exception\n If the username or email already exists.\n If there's a general error during the sign up process.\n "'\ndef signup(config: dict) -> None:\n 'try:headers = {'accept': 'application/json'}response = requests.post(url=BASE_URL + '/auth/signup', headers=headers, data=json.dumps(config))
1234567891011def add(a, b):"""Computes and returns the sum of two numbers.Args:a (int): The first number.b (int): The second number.Returns:int: The sum of a and b."""return a + b123456789101112131415161718192021222324252627282930313233def add(a, b):"""This function adds two integers.Arguments:a (int): The first integer to be added.b (int): The second integer to be added.Returns:int: The sum of the two integers."""'\n This function adds two integers.\n\n Arguments:\n a (int): The first integer to be added.\n b (int): The second integer to be added.\n\n Returns:\n int: The sum of the two integers.\n ''\n This function adds two integers.\n\n Arguments:\n a (int): The first integer to be added.\n b (int): The second integer to be added.\n\n Returns:\n int: The sum of the two integers.\n ''\n This function adds two integers.\n\n Arguments:\n a (int): The first integer to be added.\n b (int): The second integer to be added.\n\n Returns:\n int: The sum of the two integers.\n ''\n This function adds two integers.\n\n Arguments:\n a (int): The first integer to be added.\n b (int): The second integer to be added.\n\n Returns:\n int: The sum of the two integers.\n ''\n This function adds two integers.\n\n Arguments:\n a (int): The first integer to be added.\n b (int): The second integer to be added.\n\n Returns:\n int: The sum of the two integers.\n ''\n This function adds two integers.\n\n Arguments:\n a (int): The first integer to be added.\n b (int): The second integer to be added.\n\n Returns:\n int: The sum of the two integers.\n ''\n This function adds two integers.\n\n Arguments:\n a (int): The first integer to be added.\n b (int): The second integer to be added.\n\n Returns:\n int: The sum of the two integers.\n ''\n This function adds two integers.\n\n Arguments:\n a (int): The first integer to be added.\n b (int): The second integer to be added.\n\n Returns:\n int: The sum of the two integers.\n ''\n This function adds two integers.\n\n Arguments:\n a (int): The first integer to be added.\n b (int): The second integer to be added.\n\n Returns:\n int: The sum of the two integers.\n ''\n This function adds two numbers.\n\n Arguments:\n a (int): The first number to be added.\n b (int): The second number to be added.\n\n Returns:\n int: The sum of the two numbers.\n ''\n This function adds two numbers.\n\n Arguments:\n a (int): The first number to be added.\n b (int): The second number to be added.\n\n Returns:\n int: The sum of the two numbers.\n ''\n This function adds two numbers.\n\n Arguments:\n a (int): The first number to be added.\n b (int): The second number to be added.\n\n Returns:\n int: The sum of the two numbers.\n ''\n This function adds two numbers.\n\n Arguments:\n a (int): The first number to be added.\n b (int): The second number to be added.\n\n Returns:\n int: The sum of the two numbers.\n ''\n This function adds two numbers.\n\n Arguments:\n a (int): The first number to be added.\n b (int): The second number to be added.\n\n Returns:\n int: The sum of the two numbers.\n ''\n This function adds two numbers.\n\n Arguments:\n a (int): The first number to be added.\n b (int): The second number to be added.\n\n Returns:\n int: The sum of the two numbers.\n ''\n This function adds two numbers.\n\n Arguments:\n a (int): The first number to be added.\n b (int): The second number to be added.\n\n Returns:\n int: The sum of the two numbers.\n ''\n This function adds two numbers.\n\n Arguments:\n a (int): The first number to be added.\n b (int): The second number to be added.\n\n Returns:\n int: The sum of the two numbers.\n ''\n This function adds two numbers.\n\n Arguments:\n a (int): The first number to be added.\n b (int): The second number to be added.\n\n Returns:\n int: The sum of the two numbers.\n ''\n This function adds two numbers.\n\n Arguments:\n a (int): The first number to be added.\n b (int): The second number to be added.\n\n Returns:\n int: The sum of the two numbers.\n ''\n This function adds two numbers.\n\n Arguments:\n a (int): The first number to be added.\n b (int): The second number to be added.\n\n Returns:\n int: The sum of the two numbers.\n ''\n This function adds two numbers.\n\n Arguments:\n a (int): The first number to be added.\n b (int): The second number to be added.\n\n Returns:\n int: The sum of the two numbers.\n 'return a + b
TechdocsAPI/backend/__init__.py+39-17
TechdocsAPI/backend/core/ConfigEnv.py+1-2
TechdocsAPI/backend/core/ExceptionHandlers.py-6
TechdocsAPI/backend/core/Exceptions.py+1-13
TechdocsAPI/backend/services/auth/__init__.py+1-2
TechdocsAPI/backend/services/auth/ops.py+18-19
TechdocsAPI/backend/services/auth/utils/functools.pyDeleted-9
TechdocsAPI/backend/utils/Gemini_Prompt.txtDeleted-177
TechdocsAPI/backend/utils/prompt.txt+7-8
TechdocsAPI/requirements.txt+2-5
scripts/test.py+11-13
temp.pyDeleted-21
testing/logs_2024_01_07_16_08_04.logDeleted-23
testing/pack/DBQueries.py+61-29
testing/pack/functools.py+72-39
testing/test.py+29-7