Python scraper based on AI
Python ai-crawlerai-scrapingai-searchcrawlerdata-extractionfirecrawl-alternativelarge-language-modelllmmarkdownragscrapingscraping-pythonweb-crawlerweb-crawlersweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
merge: temp branch
PeriniM134b96449551
diff --git a/examples/html_scraping.py b/examples/html_scraping.pyindex bb326687..c19ba9cb 100644--- a/examples/html_scraping.py+++ b/examples/html_scraping.py@@ -1,20 +1,9 @@import osfrom dotenv import load_dotenv-from yosoai.class_generator import Generator+from yosoai.request import send_requestload_dotenv()-MY_ENV_VAR = os.getenv('API_KEY')--values = [- {- "title": "description",- "type": "str",- "description": "The description of the news"- }-]--# Example using a HTML codequery_info = '''Given this code extract all the information in a json format about the news.<article class="c-card__wrapper aem_card_check_wrapper" data-cardindex="0">@@ -52,9 +41,31 @@ query_info = '''</article>'''-if __name__ == "__main__":+def main():+ # Get OpenAI API key from environment variables+ openai_key = os.getenv("API_KEY")+ if not openai_key:+ print("Error: OpenAI API key not found in environment variables.")+ return++ # Example values for the request+ request_settings = [+ {+ "title": "title",+ "type": "str",+ "description": "Title of the news"+ }+ ]- generator_instance = Generator(values, MY_ENV_VAR, 0, "gpt-3.5-turbo")+ # Choose the desired model and other parameters+ selected_model = "gpt-3.5-turbo"+ temperature_value = 0.7- res = generator_instance.invocation(query_info)- print(res)\ No newline at end of file+ # Invoke send_request function+ result = send_request(openai_key, query_info, request_settings, selected_model, temperature_value, 'cl100k_base')++ # Print or process the result as needed+ print("Result:", result)++if __name__ == "__main__":+ main()\ No newline at end of filediff --git a/examples/value_scraping.py b/examples/value_scraping.pyindex 9d5a5296..6c55cb84 100644--- a/examples/value_scraping.py+++ b/examples/value_scraping.py@@ -1,24 +1,38 @@import osfrom dotenv import load_dotenv-from yosoai.getter import remover-from yosoai.class_generator import Generator+from yosoai.getter import get_function+from yosoai.request import send_requestload_dotenv()-MY_ENV_VAR = os.getenv('API_KEY')+def main():+ # Get OpenAI API key from environment variables+ openai_key = os.getenv("API_KEY")+ if not openai_key:+ print("Error: OpenAI API key not found in environment variables.")+ return-values = [- {- "title": "title_website",+ # Example values for the request+ request_settings = [+ {+ "title": "title_news","type": "str",- "description": "Find the main header title of the website"- }-]+ "description": "Give me the name of the news"+ }+ ]-if __name__ == "__main__":+ # Choose the desired model and other parameters+ selected_model = "gpt-3.5-turbo"+ temperature_value = 0.7++ # Mockup World URL+ mockup_world_url = "https://sport.sky.it/nba?gr=www"- generator_instance = Generator(values, MY_ENV_VAR, 0, "gpt-3.5-turbo")+ # Invoke send_request function+ result = send_request(openai_key, get_function(mockup_world_url), request_settings, selected_model, temperature_value, 'cl100k_base')- res = generator_instance.invocation(remover("https://www.mockupworld.co"))-- print(res)\ No newline at end of file+ # Print or process the result as needed+ print("Result:", result)++if __name__ == "__main__":+ main()\ No newline at end of filediff --git a/setup.py b/setup.pyindex ebf98490..e8c3f177 100644--- a/setup.py+++ b/setup.py@@ -32,7 +32,7 @@ setup('Operating System :: OS Independent',],packages = ['yosoai'],- python_requires='>=3.9 , !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, !=3.6.*, !=3.7.*, !=3.8.*',+ python_requires='>=3.9, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, !=3.6.*, !=3.7.*, !=3.8.*',include_package_data=True,# https://packaging.python.org/en/latest/discussions/install-requires-vs-requirements/install_requires=prod_requirements,diff --git a/yosoai/class_creator.py b/yosoai/class_creator.pyindex 43d64224..34146044 100644--- a/yosoai/class_creator.py+++ b/yosoai/class_creator.py@@ -1,5 +1,3 @@-import time-def create_class(data_dict: dict):"""This function creates a class at runtime using the values from the list.diff --git a/yosoai/class_generator.py b/yosoai/class_generator.pyindex 136a0724..c3a7835a 100644--- a/yosoai/class_generator.py+++ b/yosoai/class_generator.py@@ -1,13 +1,12 @@from dotenv import load_dotenvfrom .pydantic_class import _Response-from .class_creator import create_class #in future to removefrom langchain_openai import ChatOpenAIfrom langchain.prompts import PromptTemplatefrom langchain_core.pydantic_v1 import Fieldfrom langchain.output_parsers import PydanticOutputParserclass Generator:- def __init__(self, values: list[dict], api_key: str, temperature_param: float = 0, model_name: str = "gpt-3.5-turbo") -> dict:+ def __init__(self, values: list[dict], api_key: str, temperature_param: float = 0.0, model_name: str = "gpt-3.5-turbo") -> dict:"""Initializes the Generator object.@@ -21,8 +20,6 @@ class Generator:Returns:result_dict (dict): The result of the language model invocation, converted to a dictionary."""-- create_class(values) # in future to removeself.parser = PydanticOutputParser(pydantic_object=_Response)diff --git a/yosoai/getter.py b/yosoai/getter.pyindex ac4852c9..a90632cd 100644--- a/yosoai/getter.py+++ b/yosoai/getter.py@@ -1,54 +1,8 @@import requests-import tiktoken-from typing import ListHEADERS = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36','Accept-Language': 'en-US'}-models_tokens = {- "gpt-3.5-turbo-0125": 16385,- "gpt-3.5-turbo": 4096,- "gpt-3.5-turbo-1106": 16385,- "gpt-3.5-turbo-instruct": 4096,- "gpt-4-0125-preview": 128000,- "gpt-4-turbo-preview": 128000,- "gpt-4-1106-preview": 128000,- "gpt-4-vision-preview": 128000,- "gpt-4": 8192,- "gpt-4-0613": 8192,- "gpt-4-32k": 32768,- "gpt-4-32k-0613": 32768,-}--EMBEDDING_ENCODING = 'cl100k_base'--DEFAULT_MESSAGE_LENGTH = 100---def truncate_text_tokens(text: str, model: str, encoding_name: str = EMBEDDING_ENCODING) -> List[str]:- """- It creates a list of strings to create max dimension tokenizable elements-- Args:- text (str): The input text to be truncated into tokenizable elements.- model (str): The name of the language model to be used.- encoding_name (str): The name of the encoding to be used (default: EMBEDDING_ENCODING).-- Returns:- List[str]: A list of tokenizable elements created from the input text.- """-- encoding = tiktoken.get_encoding(encoding_name)- max_tokens = models_tokens[model]- encoded_text = encoding.encode(text)-- chunks = [encoded_text[i:i + max_tokens] for i in range(0, len(encoded_text), max_tokens)]-- result = [encoding.decode(chunk) for chunk in chunks]-- return result--def get_function(link:str, param = HEADERS) -> str:"""It sends a GET request to the specified link with optional headers.@@ -94,4 +48,4 @@ def remover(file:str) -> str:if isBody == True:res = res + elem- return res.replace("\n", "")+ return res.replace("\n", "")\ No newline at end of filediff --git a/yosoai/request.py b/yosoai/request.pyindex 1ec658c7..537b3018 100644--- a/yosoai/request.py+++ b/yosoai/request.py@@ -1,23 +1,50 @@+import time+from typing import Listfrom .getter import removerfrom .class_creator import create_classfrom .class_generator import Generator+from .token_calculator import truncate_text_tokens-def send_request(values: list[dict]) -> dict:+EMBEDDING_ENCODING = 'cl100k_base'++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:+ key (str): The API key for accessing the language model.+ text (str): The input text to be processed.values (list[dict]): Settings of the request.Each element of the list should have the following keys:- "title" (str): The title of the field.- "type" (str): The type of the field.- "description" (str): The description of the field.+ model (str): The name of the language model to be used.+ 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:- dict: The result of the request to openai.+ List[dict]: The result of the request to openai."""- res = {}- create_class("TOADD")+ res = []+ create_class(values)+ time.sleep(2) # TODO: implement an asynchrous waiting++ text = remover(text)++ messages = truncate_text_tokens(text, model, encoding_name)++ count = 0++ for message in messages:+ generator_instance = Generator(key, temperature, model)++ res.append(generator_instance.invocation(message))++ print(res)+ print(f"Percentage: {round(count/len(messages),2)*100}%")+ count +=1return res\ No newline at end of filediff --git a/yosoai/token_calculator.py b/yosoai/token_calculator.pynew file mode 100644index 00000000..47f6f292--- /dev/null+++ b/yosoai/token_calculator.py@@ -0,0 +1,40 @@+import tiktoken+from typing import List++models_tokens = {+ "gpt-3.5-turbo-0125": 16385,+ "gpt-3.5-turbo": 4096,+ "gpt-3.5-turbo-1106": 16385,+ "gpt-3.5-turbo-instruct": 4096,+ "gpt-4-0125-preview": 128000,+ "gpt-4-turbo-preview": 128000,+ "gpt-4-1106-preview": 128000,+ "gpt-4-vision-preview": 128000,+ "gpt-4": 8192,+ "gpt-4-0613": 8192,+ "gpt-4-32k": 32768,+ "gpt-4-32k-0613": 32768,+}++def truncate_text_tokens(text: str, model: str, encoding_name: str) -> List[str]:+ """+ It creates a list of strings to create max dimension tokenizable elements++ Args:+ text (str): The input text to be truncated into tokenizable elements.+ model (str): The name of the language model to be used.+ encoding_name (str): The name of the encoding to be used (default: EMBEDDING_ENCODING).++ Returns:+ List[str]: A list of tokenizable elements created from the input text.+ """++ encoding = tiktoken.get_encoding(encoding_name)+ max_tokens = models_tokens[model]+ encoded_text = encoding.encode(text)++ chunks = [encoded_text[i:i + max_tokens] for i in range(0, len(encoded_text), max_tokens)]++ result = [encoding.decode(chunk) for chunk in chunks]++ return result\ No newline at end of file