Python scraper based on AI
Python ai-crawlerai-scrapingai-searchcrawlerdata-extractionfirecrawl-alternativelarge-language-modelllmmarkdownragscrapingscraping-pythonweb-crawlerweb-crawlersweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
refactoring for pylint
VinciGit0065fcd0b9e528
diff --git a/.github/workflows/pylint.yml b/.github/workflows/pylint.ymlindex 1bbe3f26..1bf48b67 100644--- a/.github/workflows/pylint.yml+++ b/.github/workflows/pylint.yml@@ -18,6 +18,7 @@ jobs:run: |python -m pip install --upgrade pippip install pylint+ pip install -r requirements.txt- name: Analysing the code with pylintrun: |- pylint yosoai/*.py+ pylint yosoai/*.py\ No newline at end of filediff --git a/yosoai/__init__.py b/yosoai/__init__.pyindex d8356992..e5cf2eb4 100644--- a/yosoai/__init__.py+++ b/yosoai/__init__.py@@ -1,3 +1,6 @@+"""+init file+"""from .class_creator import create_classfrom .class_generator import Generatorfrom .getter import _get_functiondiff --git a/yosoai/class_creator.py b/yosoai/class_creator.pyindex 9cc41dc3..1760b7c9 100644--- a/yosoai/class_creator.py+++ b/yosoai/class_creator.py@@ -1,3 +1,8 @@+"""+Module for creating a class+"""++def create_class(data_dict: dict):"""This function creates a class at runtime using the values from the list.@@ -20,8 +25,8 @@ class _Response(BaseModel):"""for elem in data_dict:- base_script = base_script + f" {elem['title']}: {elem['type']} = Field(description='{elem['description']}')\n"+ base_script = base_script + \+ f" {elem['title']}: {elem['type']} = Field(description='{elem['description']}')\n"- with open("./yosoai/pydantic_class.py", "w") as f:+ with open("./yosoai/pydantic_class.py", "w", encoding="utf-8") as f:f.write(base_script)-\ No newline at end of filediff --git a/yosoai/class_generator.py b/yosoai/class_generator.pyindex af02b963..24ea61a2 100644--- a/yosoai/class_generator.py+++ b/yosoai/class_generator.py@@ -1,35 +1,37 @@"""Module for generating responses using language model"""-from dotenv import load_dotenvfrom langchain_openai import ChatOpenAIfrom langchain.prompts import PromptTemplate-from langchain_core.pydantic_v1 import Fieldfrom langchain.output_parsers import PydanticOutputParserfrom .pydantic_class import _Response+class Generator:"""Class to generate responses using language model"""+def __init__(self,api_key: str,temperature_param: float = 0.0,model_name: str = "gpt-3.5-turbo") -> None:-"""Initializes the Generator object.Args:api_key (str): The API key for accessing the language model.- temperature_param (float): A parameter controlling the randomness of the language model's output.- model_name (str): The name of the language model to be used (default: "gpt-3.5-turbo"). All- the possible models are available at the following link: https://platform.openai.com/docs/models+ temperature_param (float): A parameter controlling the randomness of the language+ model's output.+ model_name (str): The name of the language model to be used (default: "gpt-3.5-turbo").+ All the possible models are available at the+ following link: https://platform.openai.com/docs/modelsReturns:- result_dict (dict): The result of the language model invocation, converted to a dictionary.+ result_dict (dict): The result of the language model invocation, converted+ to a dictionary."""self.parser = PydanticOutputParser(pydantic_object=_Response)@@ -37,10 +39,11 @@ class Generator:self.prompt = PromptTemplate(template="Answer the user query.\n{format_instructions}\n{query}\n",input_variables=["query"],- partial_variables={"format_instructions": self.parser.get_format_instructions()},+ partial_variables={+ "format_instructions": self.parser.get_format_instructions()},)- self.model = ChatOpenAI(openai_api_key=api_key, temperature=temperature_param,+ self.model = ChatOpenAI(openai_api_key=api_key, temperature=temperature_param,model=model_name)self.chain = self.prompt | self.model | self.parser@@ -51,8 +54,7 @@ class Generator:"""try:result = self.chain.invoke({"query": query_info})- result_dict = result.dict()-+ result_dict = result.dict()return result_dictexcept Exception as e:print(f"Error: {e}")diff --git a/yosoai/json_getter.py b/yosoai/json_getter.pyindex f0dd678b..cd8714a6 100644--- a/yosoai/json_getter.py+++ b/yosoai/json_getter.py@@ -1,21 +1,27 @@+"""+Module for creating the json schema+"""from tqdm import tqdm-from .getter import _get_functionfrom langchain_openai import ChatOpenAI-from .dictionaries import schema_examplefrom langchain.prompts import PromptTemplate-from .token_calculator import truncate_text_tokensfrom langchain_core.output_parsers import JsonOutputParser+from .getter import _get_function+from .dictionaries import schema_example+from .token_calculator import truncate_text_tokensEMBEDDING_ENCODING = 'cl100k_base'-def get_json(key: str, link: str, model_name: str, encoding_name_chunk: str = EMBEDDING_ENCODING) -> str:++def get_json(key: str, link: str, model_name: str,+ encoding_name_chunk: str = EMBEDDING_ENCODING) -> str:"""Function that creates a JSON schema given a linkArgs:key (str): openai keylink (str): link to analyzemodel_name (str): The name of the openai language model to be used.- encoding_name_chunk (str): The name of the encoding to be used (default: EMBEDDING_ENCODING).+ encoding_name_chunk (str): The name of the encoding+ to be used (default: EMBEDDING_ENCODING).Returns:str: the HTML schema of the website"""@@ -24,7 +30,8 @@ def get_json(key: str, link: str, model_name: str, encoding_name_chunk: str = EMhtml = _get_function(link)- chunks = truncate_text_tokens(html, model=model_name, encoding_name=encoding_name_chunk)+ chunks = truncate_text_tokens(+ html, model=model_name, encoding_name=encoding_name_chunk)progress_bar = tqdm(total=len(chunks), desc="Sending chunks")@@ -32,7 +39,10 @@ def get_json(key: str, link: str, model_name: str, encoding_name_chunk: str = EMfor chunk in chunks:prompt = PromptTemplate(- template="You are a website scraper and you want to extract information in a schema like the example provided. Write a dictionary where the key is the section and the value is the type.\n{format_instructions}\n{query}\n. Example: {example}",+ template=("You are a website scraper and you want to extract information "+ "in a schema like the example provided. Write a dictionary where "+ "the key is the section and the value is the type.\n{format_instructions}\n{query}\n"+ ". Example: {example}"),input_variables=["query"],partial_variables={"format_instructions": parser.get_format_instructions(),@@ -50,12 +60,14 @@ def get_json(key: str, link: str, model_name: str, encoding_name_chunk: str = EMif len(result) > 1:prompt = PromptTemplate(- template="You are a website scraper and you have to merge the given schemas without repetitions.\n{format_instructions}}\n. Example: {to_merge}",+ template=("You are a website scraper and you have to merge the given "+ "schemas without repetitions.\n{format_instructions}}\n"+ ". Example: {to_merge}"),input_variables=["to_merge"],partial_variables={"format_instructions": parser.get_format_instructions()- },+ },)-+chain = prompt | model | parserresult = chain.invoke({"query": str(result)})diff --git a/yosoai/pydantic_class.py b/yosoai/pydantic_class.pyindex 6a6d72a1..795786ff 100644--- a/yosoai/pydantic_class.py+++ b/yosoai/pydantic_class.py@@ -1,5 +1,8 @@-+"""+Pydantic module to send+"""from langchain_core.pydantic_v1 import BaseModel, Field+class _Response(BaseModel):- title_news: str = Field(description='Give me the name of the news')+ title_news: str = Field(description='Give me the name of the news')diff --git a/yosoai/remover.py b/yosoai/remover.pyindex 001c9986..add1a973 100644--- a/yosoai/remover.py+++ b/yosoai/remover.py@@ -1,7 +1,12 @@-def remover(file:str, only_body:bool = False) -> str:+"""+Module for removing the unused html tags+"""+++def remover(file: str, only_body: bool = False) -> str:"""This function elaborates the HTML file and remove all the not necessary tag-+Parameters:file (str): the file to parse@@ -11,17 +16,17 @@ def remover(file:str, only_body:bool = False) -> str:res = ""- if only_body == True:- isBody = True+ if only_body:+ is_body = Trueelse:- isBody = False+ is_body = Falsefor elem in file.splitlines():if "<title>" in elem:res = res + elem- if "<body>" in elem:- isBody = True+ if "<body>" in elem:+ is_body = Trueif "</body>" in elem:break@@ -29,7 +34,7 @@ def remover(file:str, only_body:bool = False) -> str:if "<script>" in elem:continue- if isBody == True:+ if is_body:res = res + elemreturn res.replace("\\n", "")diff --git a/yosoai/request.py b/yosoai/request.pyindex 886f2204..246d2bf4 100644--- a/yosoai/request.py+++ b/yosoai/request.py@@ -1,6 +1,9 @@+"""+Module for sending the request+"""import time-from tqdm import tqdmfrom typing import List+from tqdm import tqdmfrom .remover import removerfrom .class_generator import Generatorfrom .class_creator import create_class@@ -9,9 +12,12 @@ from .token_calculator import truncate_text_tokensEMBEDDING_ENCODING = 'cl100k_base'LAST_REQUEST_TIME = 0-REQUEST_INTERVAL = 20+REQUEST_INTERVAL = 20-def send_request(key: str, text: str, values: List[dict], model: str, temperature: float = 0.0, encoding_name: str = EMBEDDING_ENCODING) -> List[dict]:++def send_request(key: str, text: str, values: List[dict],+ model: str, temperature: float = 0.0,+ encoding_name: str = EMBEDDING_ENCODING) -> List[dict]:"""Send a request to openai.Args:@@ -23,7 +29,8 @@ def send_request(key: str, text: str, values: List[dict], model: str, temperatur- "type" (str): The type of the field.- "description" (str): The description of the field.model (str): The name of the openai language model to be used.- temperature (float): A parameter controlling the randomness of the language model's output (default: 0).+ temperature (float): A parameter controlling the randomness of the language+ model's output (default: 0).encoding_name (str): The name of the encoding to be used (default: EMBEDDING_ENCODING).Returns:List[dict]: The result of the request to openai.@@ -36,7 +43,6 @@ def send_request(key: str, text: str, values: List[dict], model: str, temperaturtime.sleep(2) # TODO: implement asynchronous waitingmessages = truncate_text_tokens(remover(text), model, encoding_name)-processed_messages = 0with tqdm(total=len(messages)) as pbar:@@ -45,13 +51,11 @@ def send_request(key: str, text: str, values: List[dict], model: str, temperaturtime_since_last_request = current_time - LAST_REQUEST_TIMEif time_since_last_request < REQUEST_INTERVAL:time.sleep(REQUEST_INTERVAL - time_since_last_request)-generator_instance = Generator(key, temperature, model)res.append(generator_instance.invocation(message))processed_messages += 1- pbar.update(1)-- LAST_REQUEST_TIME = time.time()+ pbar.update(1)+ LAST_REQUEST_TIME = time.time()return resdiff --git a/yosoai/token_calculator.py b/yosoai/token_calculator.pyindex 2b15adb0..c0a4127b 100644--- a/yosoai/token_calculator.py+++ b/yosoai/token_calculator.py@@ -2,7 +2,8 @@Module for calculating token truncation for text"""from typing import List-from .tiktoken import tokenizer+from tiktoken import tokenizer+def truncate_text_tokens(text: str, model: str, encoding_name: str) -> List[str]:"""@@ -16,7 +17,6 @@ def truncate_text_tokens(text: str, model: str, encoding_name: str) -> List[str]"""# Calculate the token limit for the given model and encodingtoken_limit = tokenizer.token_limit(model, encoding_name)-# Truncate the text into smaller chunks based on the token limitchunks = []start = 0@@ -24,5 +24,4 @@ def truncate_text_tokens(text: str, model: str, encoding_name: str) -> List[str]chunk = text[start:start+token_limit]chunks.append(chunk)start += token_limit-return chunks