mayureshagashe2105 commited on
Commit
aa7111b
1 Parent(s): 74f3c22

Add logger to CLI

Browse files
techdocs/pyproject.toml CHANGED
@@ -1,13 +1,14 @@
1
  [build-system]
2
  requires = [
3
  "setuptools >= 65",
4
- "wheel >= 0.38"
 
5
  ]
6
  build-backend = "setuptools.build_meta"
7
 
8
  [project]
9
  name = "techdocs"
10
- version = "0.1.5"
11
  description = "Code documentation generation CLI App"
12
  readme = "README.md"
13
  requires-python = ">=3.10"
@@ -21,7 +22,7 @@ scripts = {techdocs = "techdocs.cli:main"}
21
 
22
 
23
  [tool.setuptools]
24
- packages = ["techdocs"]
25
 
26
  [tool.setuptools.package-data]
27
  "*" = ["*.json"]
 
1
  [build-system]
2
  requires = [
3
  "setuptools >= 65",
4
+ "wheel >= 0.38",
5
+ "tqdm >= 4.66.1"
6
  ]
7
  build-backend = "setuptools.build_meta"
8
 
9
  [project]
10
  name = "techdocs"
11
+ version = "0.2.0"
12
  description = "Code documentation generation CLI App"
13
  readme = "README.md"
14
  requires-python = ">=3.10"
 
22
 
23
 
24
  [tool.setuptools]
25
+ packages = ["techdocs", "techdocs.utils"]
26
 
27
  [tool.setuptools.package-data]
28
  "*" = ["*.json"]
techdocs/setup.cfg CHANGED
@@ -1,6 +1,6 @@
1
  [metadata]
2
  name = techdocs
3
- version = 0.1.5
4
 
5
  [options]
6
  packages = techdocs
 
1
  [metadata]
2
  name = techdocs
3
+ version = 0.2.0
4
 
5
  [options]
6
  packages = techdocs
techdocs/setup.py CHANGED
@@ -4,7 +4,7 @@ import glob
4
 
5
  setup(
6
  name='techdocs',
7
- version='0.1.5',
8
  # To provide executable scripts, use entry points in preference to the
9
  # "scripts" keyword. Entry points provide cross-platform support and allow
10
  # pip to create the appropriate form of executable for the target platform.
 
4
 
5
  setup(
6
  name='techdocs',
7
+ version='0.2.0',
8
  # To provide executable scripts, use entry points in preference to the
9
  # "scripts" keyword. Entry points provide cross-platform support and allow
10
  # pip to create the appropriate form of executable for the target platform.
techdocs/techdocs/__init__.py CHANGED
@@ -1 +1 @@
1
- __version__ = "0.1.5"
 
1
+ __version__ = "0.2.0"
techdocs/techdocs/cli.py CHANGED
@@ -10,7 +10,7 @@ def main(log_info: bool = False):
10
  👋 Hi there! Welcome to techdocs. Here are some cool things you can do:
11
 
12
 
13
- 💫 try out a demo with or new GUI 🚀 and explore how to use the CLI:
14
 
15
  ➡️ https://techdocs.streamlit.app/
16
 
 
10
  👋 Hi there! Welcome to techdocs. Here are some cool things you can do:
11
 
12
 
13
+ 💫 try out a demo with our new GUI 🚀 and explore how to use the CLI:
14
 
15
  ➡️ https://techdocs.streamlit.app/
16
 
techdocs/techdocs/ops.py CHANGED
@@ -13,6 +13,7 @@ from .utils.parse import *
13
  parser = argparse.ArgumentParser(
14
  description='Code documentation generation',
15
  epilog="Thanks for using Techdocs")
 
16
  subparsers = parser.add_subparsers(help='subcommands')
17
 
18
 
 
13
  parser = argparse.ArgumentParser(
14
  description='Code documentation generation',
15
  epilog="Thanks for using Techdocs")
16
+ parser.add_argument('--version', action='version', version=f'{techdocs.__version__}')
17
  subparsers = parser.add_subparsers(help='subcommands')
18
 
19
 
techdocs/techdocs/utils/LoggingManager.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import datetime
3
+ import os
4
+ import sys
5
+ import glob
6
+ import tqdm
7
+ from typing import List
8
+ import re
9
+
10
+ class LoggingManager:
11
+ def __init__(self, init_root: str):
12
+ self.logger = logging.getLogger(__name__)
13
+ self.logger.propagate = False
14
+ self.logger.setLevel(logging.INFO)
15
+ self.formatter = logging.Formatter("%(asctime)s:%(levelname)s:%(message)s")
16
+
17
+ self.logs_addr = re.sub(r"\s|:|-", "_", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
18
+ self.logs_addr = os.path.join(init_root, f"logs_{self.logs_addr}.log")
19
+ self.file_handler = logging.FileHandler(self.logs_addr)
20
+ self.file_handler.setFormatter(self.formatter)
21
+ self.logger.addHandler(self.file_handler)
22
+
23
+ self.stream_handler = logging.StreamHandler(sys.stdout)
24
+ self.stream_handler.setFormatter(self.formatter)
25
+ self.logger.addHandler(self.stream_handler)
26
+
27
+ self.logger.info(f'Logs generated at "{self.logs_addr}". For detailed logs check the file.')
28
+ self.logger.info(f'Docstrings generation started for "{init_root}/*.py" files')
29
+
30
+ @property
31
+ def LOGGER(self):
32
+ return self.logger
33
+
34
+ @LOGGER.setter
35
+ def get_logger(self):
36
+ raise NotImplementedError("Cannot set logger")
37
+
38
+ @property
39
+ def set_log_handlers(self):
40
+ raise NotImplementedError("Cannot access applied log handlers")
41
+
42
+ @set_log_handlers.setter
43
+ def set_log_handlers(self, handlers: List[logging.Handler]):
44
+ self.logger.handlers = []
45
+ self.logger.handlers = handlers
46
+
47
+
48
+ def log_curr_state(self, root: str):
49
+ self.set_log_handlers = [self.file_handler]
50
+ self.logger.info(f'Working on "{root}\\*.py"')
51
+
52
+ start = datetime.datetime.now()
53
+ files = glob.glob(os.path.join(root + "/*.py"))
54
+
55
+ for file in tqdm.tqdm(files, desc=f"Working on {root}"):
56
+ self.set_log_handlers = [self.file_handler]
57
+ self.logger.info(f'Working on "{file}"')
58
+ yield file
59
+ logging.info(f'Docstrings generated for "{file}". Time Taken: {datetime.datetime.now() - start}')
60
+ self.line_breaks(dir=False, file=True)
61
+
62
+ self.set_log_handlers = [self.file_handler]
63
+ self.logger.info(f'Docstrings generation completed for "{root}\\.*py". Time Taken: {datetime.datetime.now() - start}')
64
+ self.line_breaks(dir=True, file=False)
65
+
66
+
67
+ def line_breaks(self, dir: bool, file: bool):
68
+ if not dir ^ file:
69
+ raise ValueError("Both dir and file cannot be True or False")
70
+
71
+ if dir:
72
+ self.logger.info(">"*50)
73
+ if file:
74
+ self.logger.info("="*50)
75
+
76
+
77
+
78
+
79
+
80
+
81
+
techdocs/techdocs/utils/parse.py CHANGED
@@ -1,8 +1,11 @@
1
  import ast
2
  import os
3
  import threading
 
 
4
 
5
  from .functools import *
 
6
 
7
 
8
  # Function to extract and print the outermost nested function with line number
@@ -15,7 +18,10 @@ def extract_outermost_function(node, config):
15
  try:
16
  docstr = response.split('"""')
17
  docstring = ast.Expr(value=ast.Str(s=docstr[1]))
18
- print(f"Docstring generated for def {node.name}")
 
 
 
19
  node.body.insert(0, docstring)
20
  except IndexError:
21
  pass
@@ -26,16 +32,15 @@ def extract_outermost_function(node, config):
26
 
27
  # Function to traverse directories recursively and extract functions from Python files
28
  def extract_functions_from_directory(config):
 
 
29
  for root, dirnames, files in os.walk(config["dir"]):
30
- for file in files:
31
- if file.endswith(".py"):
32
- file_path = os.path.join(root, file)
33
- print(file_path)
34
- with open(file_path, "r",errors='ignore') as file:
35
- content = file.read()
36
- parsed = ast.parse(content)
37
- extract_outermost_function(parsed, config)
38
- docstr_code = ast.unparse(parsed)
39
-
40
- write_thread = threading.Thread(target=update_file, args=(file_path, docstr_code))
41
- write_thread.start()
 
1
  import ast
2
  import os
3
  import threading
4
+ import time
5
+ import glob
6
 
7
  from .functools import *
8
+ from .LoggingManager import LoggingManager
9
 
10
 
11
  # Function to extract and print the outermost nested function with line number
 
18
  try:
19
  docstr = response.split('"""')
20
  docstring = ast.Expr(value=ast.Str(s=docstr[1]))
21
+ # print(f"Docstring generated for def {node.name}")
22
+ logging_manager = config.get("logging_manager")
23
+ logging_manager.set_log_handlers = [logging_manager.file_handler]
24
+ logging_manager.LOGGER.info(f"Docstring generated for def {node.name}")
25
  node.body.insert(0, docstring)
26
  except IndexError:
27
  pass
 
32
 
33
  # Function to traverse directories recursively and extract functions from Python files
34
  def extract_functions_from_directory(config):
35
+ logging_manager = LoggingManager(config["dir"])
36
+ config.update({"logging_manager": logging_manager})
37
  for root, dirnames, files in os.walk(config["dir"]):
38
+ for _file in logging_manager.log_curr_state(root):
39
+ file_path = _file
40
+ with open(file_path, "r",errors='ignore') as file:
41
+ content = file.read()
42
+ parsed = ast.parse(content)
43
+ extract_outermost_function(parsed, config)
44
+ docstr_code = ast.unparse(parsed)
45
+ write_thread = threading.Thread(target=update_file, args=(file_path, docstr_code))
46
+ write_thread.start()
 
 
 
testing/DBQueries.py DELETED
@@ -1,51 +0,0 @@
1
- import pydantic
2
- from bson.objectid import ObjectId
3
- pydantic.json.ENCODERS_BY_TYPE[ObjectId] = str
4
- from typing import Union, Tuple, List
5
- from backend.utils import DBConnection
6
- from backend.core.Exceptions import *
7
-
8
- class DBQueries:
9
-
10
- @classmethod
11
- def insert_to_database(cls, table_name: str, data: Union[Tuple, List[Tuple]], cols: List[str]=None):
12
- con = DBConnection.get_client()
13
- cursor = con.cursor()
14
- QUERY = f"INSERT INTO {{table_name}} ({','.join(cols)}) VALUES ".format(table_name=table_name)
15
- if isinstance(data, list):
16
- QUERY += '(' + ','.join(['%s' for _ in range(len(data[0]))]) + ')'
17
- cursor.executemany(QUERY, data)
18
- else:
19
- QUERY += '(' + ','.join(['%s' for _ in range(len(data))]) + ')'
20
- cursor.execute(QUERY, data)
21
- con.commit()
22
-
23
- @classmethod
24
- def fetch_data_from_database(cls, table_name: str, cols_to_fetch: Union[str, List[str]], where_clause: str=None):
25
- con = DBConnection.get_client()
26
- cursor = con.cursor()
27
- if isinstance(cols_to_fetch, str):
28
- cols_to_fetch = [cols_to_fetch]
29
- cols_to_fetch = ', '.join(cols_to_fetch)
30
- QUERY = 'SELECT {cols} FROM {table_name}'.format(cols=cols_to_fetch, table_name=table_name)
31
- if where_clause:
32
- QUERY = QUERY + ' WHERE ' + where_clause
33
- cursor.execute(QUERY)
34
- return cursor.fetchall()
35
-
36
- @classmethod
37
- 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):
38
- con = DBConnection.get_client()
39
- cursor = con.cursor()
40
- if isinstance(cols_to_update, str):
41
- cols_to_update = cols_to_update + '=%s'
42
- else:
43
- cols_to_update = '=%s, '.join(cols_to_update)
44
- if isinstance(new_values, str):
45
- new_values = [new_values]
46
- QUERY = 'UPDATE {table_name} SET {cols}'.format(table_name=table_name, cols=cols_to_update)
47
- if where_clause:
48
- QUERY = QUERY + ' WHERE ' + where_clause
49
- cursor.execute(QUERY, new_values)
50
- con.commit()
51
- return True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
testing/pack/DBQueries.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pydantic
2
+ from bson.objectid import ObjectId
3
+ pydantic.json.ENCODERS_BY_TYPE[ObjectId] = str
4
+ from typing import Union, Tuple, List
5
+ from backend.utils import DBConnection
6
+ from backend.core.Exceptions import *
7
+
8
+ class DBQueries:
9
+
10
+ @classmethod
11
+ def insert_to_database(cls, table_name: str, data: Union[Tuple, List[Tuple]], cols: List[str]=None):
12
+ """
13
+ This method is used to insert data into a specified table in the database.
14
+
15
+ Args:
16
+ table_name (str): The name of the table into which data will be inserted.
17
+ 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.
18
+ 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.
19
+
20
+ Raises:
21
+ None
22
+
23
+ Returns:
24
+ None
25
+
26
+ """
27
+ '\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 '
28
+ '\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 '
29
+ '\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 '
30
+ '\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 '
31
+ '\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 '
32
+ '\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 '
33
+ '\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 '
34
+ '\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 '
35
+ '\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 '
36
+ '\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 '
37
+ con = DBConnection.get_client()
38
+ cursor = con.cursor()
39
+ QUERY = f"INSERT INTO {{table_name}} ({','.join(cols)}) VALUES ".format(table_name=table_name)
40
+ if isinstance(data, list):
41
+ QUERY += '(' + ','.join(['%s' for _ in range(len(data[0]))]) + ')'
42
+ cursor.executemany(QUERY, data)
43
+ else:
44
+ QUERY += '(' + ','.join(['%s' for _ in range(len(data))]) + ')'
45
+ cursor.execute(QUERY, data)
46
+ con.commit()
47
+
48
+ @classmethod
49
+ def fetch_data_from_database(cls, table_name: str, cols_to_fetch: Union[str, List[str]], where_clause: str=None):
50
+ """
51
+ This method is a class method that fetches data from a specified table in the database based on the provided column names and,
52
+ optionally, a WHERE clause.
53
+
54
+ Args:
55
+ - table_name: A string representing the name of the table from which to fetch data.
56
+ - cols_to_fetch: A string or a list of strings representing the column(s) to fetch from the table. If a single string,
57
+ it will be treated as a comma-separated list of column names.
58
+ - where_clause: An optional string representing a WHERE clause to filter the fetched data. Defaults to None.
59
+
60
+ Returns:
61
+ - cursor.fetchall(): A list of tuples representing the fetched data. Each tuple corresponds to a row in the result set,
62
+ and contains the values of the fetched columns in the order specified.
63
+
64
+ Raises:
65
+ - No exceptions are explicitly raised by this method. However, underlying database operations may raise exceptions, which
66
+ are not handled or propagated by this method. It is the responsibility of the caller to handle any exceptions that may occur.
67
+
68
+ """
69
+ '\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 '
70
+ '\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 '
71
+ '\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 '
72
+ '\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 '
73
+ '\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 '
74
+ '\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 '
75
+ '\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 '
76
+ '\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 '
77
+ '\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 '
78
+ '\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 '
79
+ '\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 '
80
+ '\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 '
81
+ '\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 '
82
+ con = DBConnection.get_client()
83
+ cursor = con.cursor()
84
+ if isinstance(cols_to_fetch, str):
85
+ cols_to_fetch = [cols_to_fetch]
86
+ cols_to_fetch = ', '.join(cols_to_fetch)
87
+ QUERY = 'SELECT {cols} FROM {table_name}'.format(cols=cols_to_fetch, table_name=table_name)
88
+ if where_clause:
89
+ QUERY = QUERY + ' WHERE ' + where_clause
90
+ cursor.execute(QUERY)
91
+ return cursor.fetchall()
92
+
93
+ @classmethod
94
+ 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):
95
+ """
96
+ This method updates the data in a specified table in the database.
97
+
98
+ Args:
99
+ table_name (str): The name of the table in which the data needs to be updated.
100
+ 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'.
101
+ where_clause (str, optional): The WHERE clause of the SQL query. Defaults to None.
102
+ 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.
103
+
104
+ Returns:
105
+ bool: Returns True if the data is successfully updated in the database.
106
+
107
+ Raises:
108
+ Exception: If the database connection fails or the query execution fails.
109
+ """
110
+ con = DBConnection.get_client()
111
+ cursor = con.cursor()
112
+ if isinstance(cols_to_update, str):
113
+ cols_to_update = cols_to_update + '=%s'
114
+ else:
115
+ cols_to_update = '=%s, '.join(cols_to_update)
116
+ if isinstance(new_values, str):
117
+ new_values = [new_values]
118
+ QUERY = 'UPDATE {table_name} SET {cols}'.format(table_name=table_name, cols=cols_to_update)
119
+ if where_clause:
120
+ QUERY = QUERY + ' WHERE ' + where_clause
121
+ cursor.execute(QUERY, new_values)
122
+ con.commit()
123
+ return True
testing/pack/functools.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import requests
3
+ BASE_URL = 'https://caffeinecrew-techdocs.hf.space'
4
+
5
+ def get_access_token(data, return_refresh_token=False):
6
+ """
7
+ This function sends a POST request to the specified URL to get an access token.
8
+
9
+ Arguments:
10
+ data (dict): A dictionary containing the credentials required for authentication.
11
+ return_refresh_token (bool, optional): A flag to indicate if the refresh token should be returned. Defaults to False.
12
+
13
+ Returns:
14
+ 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.
15
+
16
+ Raises:
17
+ Exception: If an error occurs during the execution of the function, an Exception is raised.
18
+ """
19
+ '\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 '
20
+ '\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 '
21
+ try:
22
+ url = BASE_URL + '/auth/login'
23
+ headers = {'accept': 'application/json'}
24
+ data = json.dumps(data)
25
+ response = requests.post(url, data=data, headers=headers)
26
+ access_token = response.json()['access_token']
27
+ if return_refresh_token:
28
+ refresh_token = response.json()['refresh_token']
29
+ return (access_token, refresh_token)
30
+ return access_token
31
+ except Exception as e:
32
+ print('Invlaid Credentials')
33
+ return None
34
+
35
+ def request_inference(config, code_block, max_retries=1):
36
+ """
37
+ Usage: request_inference(config, code_block, max_retries=1)
38
+
39
+ Purpose:
40
+ This function sends a POST request to the API server to perform code inference.
41
+
42
+ Arguments:
43
+ - config (dict): A dictionary containing the necessary authentication details like 'access_token', 'api_key' and 'username'.
44
+ - code_block (str): The code block that needs to be inferenced.
45
+ - max_retries (int, optional): The maximum number of times the function should retry in case of an error. Defaults to 1.
46
+
47
+ Returns:
48
+ - str: The docstring of the inferenced code block.
49
+
50
+ Raises:
51
+ - Exception: If the maximum number of retries (specified by max_retries) is reached and the API server still returns an error.
52
+ """
53
+ "\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"
54
+ "\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"
55
+ if max_retries == 0:
56
+ return None
57
+ url = BASE_URL + '/api/inference'
58
+ headers = {'accept': 'application/json', 'Authorization': f"Bearer {config['access_token']}"}
59
+ code_input = code_block
60
+ response = requests.post(url=url, headers=headers, data=json.dumps({'code_block': code_input, 'api_key': config['api_key']}))
61
+ if response.status_code == 200:
62
+ return response.json()['docstr']
63
+ else:
64
+ data = {'username': config['username'], 'password': config['password']}
65
+ print('Encountered error retrying...')
66
+ config.update({'access_token': get_access_token(data)})
67
+ return request_inference(config, code_block, max_retries=max_retries - 1)
68
+
69
+ def update_file(file_path, docstr_code):
70
+ """
71
+ This function updates the docstring of a Python file.
72
+
73
+ Arguments:
74
+ file_path (str): The path of the Python file to be updated.
75
+ docstr_code (str): The new docstring to be written to the file.
76
+
77
+ Returns:
78
+ None
79
+
80
+ Raises:
81
+ FileNotFoundError: If the specified file does not exist.
82
+ IOError: If there is an error while writing to the file.
83
+ """
84
+ '\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 '
85
+ '\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 '
86
+ with open(file_path, 'w', errors='ignore') as file:
87
+ file.write(docstr_code)
88
+
89
+ def issue_api_key(config):
90
+ """
91
+ This function generates a new API key for the given user.
92
+
93
+ Arguments:
94
+ config: dict, A dictionary containing the user's configuration details.
95
+ - access_token: str, The user's access token.
96
+ - username: str, The user's username.
97
+
98
+ Returns:
99
+ None, Prints the new API key to the console.
100
+
101
+ Raises:
102
+ Exception, If the API key generation fails. The error message will be printed to the console.
103
+
104
+ """
105
+ "\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 "
106
+ "\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 "
107
+ try:
108
+ headers = {'accept': 'application/json', 'Authorization': f"Bearer {config['access_token']}"}
109
+ response = requests.put(url=BASE_URL + '/auth/regenerate_api_key', headers=headers, data=json.dumps({'username': config['username']}))
110
+ if response.status_code != 200:
111
+ raise Exception('API Key Generation Failed')
112
+ print(f"$ API_KEY:{response.json()['api_key']}")
113
+ except Exception as e:
114
+ print(f'$ {e}')
115
+
116
+ def signup(config):
117
+ """
118
+ This function is used to sign up a user with the provided configuration.
119
+
120
+ Arguments:
121
+ config: dict
122
+ A dictionary containing the user's signup information.
123
+
124
+ Returns:
125
+ None
126
+
127
+ Raises:
128
+ Exception
129
+ If the username or email already exists.
130
+ If there's a general error during the sign up process.
131
+ """
132
+ "\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 "
133
+ '\ndef signup(config: dict) -> None:\n '
134
+ try:
135
+ headers = {'accept': 'application/json'}
136
+ response = requests.post(url=BASE_URL + '/auth/signup', headers=headers, data=json.dumps(config))
137
+ if response.status_code == 226:
138
+ raise Exception('username or email already exists')
139
+ elif response.status_code != 200:
140
+ raise Exception('Something went wrong, please try again later')
141
+ print('Signed up successfully, please issue a new `API_KEY` to continue')
142
+ except Exception as e:
143
+ print(e)
testing/test.py CHANGED
@@ -1,18 +1,33 @@
1
  def add(a, b):
2
- return a + b
 
3
 
4
- def multiply(a, b):
5
- return a * b
 
6
 
7
- def subtract(a, b):
8
- return a - b
9
-
10
- def divide(a, b):
11
- if b == 0:
12
- raise ValueError('Cannot divide by zero')
13
- return a / b
14
-
15
- def func(*args, **kwargs):
16
- def wrapper(*args, **kwargs):
17
- return func(*args, **kwargs)
18
- return wrapper
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  def add(a, b):
2
+ """
3
+ This function adds two integers.
4
 
5
+ Arguments:
6
+ a (int): The first integer to be added.
7
+ b (int): The second integer to be added.
8
 
9
+ Returns:
10
+ int: The sum of the two integers.
11
+ """
12
+ '\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 '
13
+ '\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 '
14
+ '\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 '
15
+ '\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 '
16
+ '\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 '
17
+ '\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 '
18
+ '\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 '
19
+ '\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 '
20
+ '\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 '
21
+ '\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 '
22
+ '\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 '
23
+ '\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 '
24
+ '\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 '
25
+ '\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 '
26
+ '\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 '
27
+ '\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 '
28
+ '\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 '
29
+ '\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 '
30
+ '\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 '
31
+ '\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 '
32
+ '\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 '
33
+ return a + b