instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Write docstrings describing functionality
# -*- coding: utf-8 -*- # !/usr/bin/env python __author__ = 'JHao' import os import sys from util.six import urlparse, withMetaclass from util.singleton import Singleton sys.path.append(os.path.dirname(os.path.abspath(__file__))) class DbClient(withMetaclass(Singleton)): def __init__(self, db_conn): s...
--- +++ @@ -1,5 +1,17 @@ # -*- coding: utf-8 -*- # !/usr/bin/env python +""" +------------------------------------------------- + File Name: DbClient.py + Description : DB工厂类 + Author : JHao + date: 2016/12/2 +------------------------------------------------- + Change Activity: + ...
https://raw.githubusercontent.com/jhao104/proxy_pool/HEAD/db/dbClient.py
Fill in missing docstrings in my code
# -*- coding: utf-8 -*- __author__ = 'JHao' from util.six import Empty from threading import Thread from datetime import datetime from util.webRequest import WebRequest from handler.logHandler import LogHandler from helper.validator import ProxyValidator from handler.proxyHandler import ProxyHandler from handler.confi...
--- +++ @@ -1,4 +1,17 @@ # -*- coding: utf-8 -*- +""" +------------------------------------------------- + File Name: check + Description : 执行代理校验 + Author : JHao + date: 2019/8/6 +------------------------------------------------- + Change Activity: + 2019/08/06: 执行代理校验...
https://raw.githubusercontent.com/jhao104/proxy_pool/HEAD/helper/check.py
Add documentation for all methods
# -*- coding: utf-8 -*- __author__ = 'JHao' from threading import Thread from helper.proxy import Proxy from helper.check import DoValidator from handler.logHandler import LogHandler from handler.proxyHandler import ProxyHandler from fetcher.proxyFetcher import ProxyFetcher from handler.configHandler import ConfigHand...
--- +++ @@ -1,4 +1,15 @@ # -*- coding: utf-8 -*- +""" +------------------------------------------------- + File Name: fetchScheduler + Description : + Author : JHao + date: 2019/8/6 +------------------------------------------------- + Change Activity: + 2021/11/18: 多线程采集 ...
https://raw.githubusercontent.com/jhao104/proxy_pool/HEAD/helper/fetch.py
Add documentation for all methods
# -*- coding: utf-8 -*- __author__ = 'JHao' import re from requests import head from util.six import withMetaclass from util.singleton import Singleton from handler.configHandler import ConfigHandler conf = ConfigHandler() HEADER = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/3...
--- +++ @@ -1,4 +1,15 @@ # -*- coding: utf-8 -*- +""" +------------------------------------------------- + File Name: _validators + Description : 定义proxy验证方法 + Author : JHao + date: 2021/5/25 +------------------------------------------------- + Change Activity: + 2023/0...
https://raw.githubusercontent.com/jhao104/proxy_pool/HEAD/helper/validator.py
Document all endpoints with docstrings
# -*- coding: utf-8 -*- __author__ = 'JHao' import os import logging import platform from logging.handlers import TimedRotatingFileHandler # 日志级别 CRITICAL = 50 FATAL = CRITICAL ERROR = 40 WARNING = 30 WARN = WARNING INFO = 20 DEBUG = 10 NOTSET = 0 CURRENT_PATH = os.path.dirname(os.path.abspath(__file__)) ROOT_PATH ...
--- +++ @@ -1,4 +1,17 @@ # -*- coding: utf-8 -*- +""" +------------------------------------------------- + File Name: LogHandler.py + Description : 日志操作模块 + Author : JHao + date: 2017/3/6 +------------------------------------------------- + Change Activity: + 2017/03/06: ...
https://raw.githubusercontent.com/jhao104/proxy_pool/HEAD/handler/logHandler.py
Add docstrings to make code maintainable
# -*- coding: utf-8 -*- __author__ = 'JHao' import json class Proxy(object): def __init__(self, proxy, fail_count=0, region="", anonymous="", source="", check_count=0, last_status="", last_time="", https=False): self._proxy = proxy self._fail_count = fail_count self._reg...
--- +++ @@ -1,4 +1,15 @@ # -*- coding: utf-8 -*- +""" +------------------------------------------------- + File Name: Proxy + Description : 代理对象类型封装 + Author : JHao + date: 2019/7/11 +------------------------------------------------- + Change Activity: + 2019/7/11: 代理对象...
https://raw.githubusercontent.com/jhao104/proxy_pool/HEAD/helper/proxy.py
Write docstrings for data processing functions
# -*- coding: utf-8 -*- __author__ = 'JHao' class LazyProperty(object): def __init__(self, func): self.func = func def __get__(self, instance, owner): if instance is None: return self else: value = self.func(instance) setattr(instance, self.func.__...
--- +++ @@ -1,8 +1,23 @@ # -*- coding: utf-8 -*- +""" +------------------------------------------------- + File Name: lazyProperty + Description : + Author : JHao + date: 2016/12/3 +------------------------------------------------- + Change Activity: + 2016/12/3: +-------...
https://raw.githubusercontent.com/jhao104/proxy_pool/HEAD/util/lazyProperty.py
Provide clean and structured docstrings
# -*- coding: utf-8 -*- __author__ = 'JHao' import sys PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY3: def iteritems(d, **kw): return iter(d.items(**kw)) else: def iteritems(d, **kw): return d.iteritems(**kw) if PY3: from urllib.parse import urlparse else: from ...
--- +++ @@ -1,4 +1,15 @@ # -*- coding: utf-8 -*- +""" +------------------------------------------------- + File Name: six + Description : + Author : JHao + date: 2020/6/22 +------------------------------------------------- + Change Activity: + 2020/6/22: +----------------...
https://raw.githubusercontent.com/jhao104/proxy_pool/HEAD/util/six.py
Expand my code with proper documentation strings
from typing import Optional class Node: def __init__(self, data: int, next=None): self._data = data self._next = next class LinkedStack: def __init__(self): self._top: Node = None def push(self, value: int): new_top = Node(value) new_top._next = self...
--- +++ @@ -1,3 +1,9 @@+""" + Stack based upon linked list + 基于链表实现的栈 + + Author: Wenru +""" from typing import Optional @@ -9,6 +15,8 @@ class LinkedStack: + """A stack based upon singly-linked list. + """ def __init__(self): self._top: Node = None
https://raw.githubusercontent.com/wangzheng0822/algo/HEAD/python/08_stack/linked_stack.py
Annotate my code with docstrings
# 1.单链表的插入、删除、查找操作; # 2.链表中存储的数据类型是Int # # Author:Lee class Node(object): def __init__(self, data, next_node=None): self.__data = data self.__next = next_node @property def data(self): return self.__data @data.setter def data(self, data): self.__data = data ...
--- +++ @@ -5,40 +5,76 @@ class Node(object): + """链表结构的Node节点""" def __init__(self, data, next_node=None): + """Node节点的初始化方法. + 参数: + data:存储的数据 + next:下一个Node节点的引用地址 + """ self.__data = data self.__next = next_node @property def da...
https://raw.githubusercontent.com/wangzheng0822/algo/HEAD/python/06_linkedlist/singlyLinkedList.py
Write clean docstrings for readability
# -*- coding: utf-8 -*- __author__ = 'J_hao' from requests.models import Response from lxml import etree import requests import random import time from handler.logHandler import LogHandler requests.packages.urllib3.disable_warnings() class WebRequest(object): name = "web_request" def __init__(self, *args,...
--- +++ @@ -1,4 +1,15 @@ # -*- coding: utf-8 -*- +""" +------------------------------------------------- + File Name: WebRequest + Description : Network Requests Class + Author : J_hao + date: 2017/7/31 +------------------------------------------------- + Change Activity: + ...
https://raw.githubusercontent.com/jhao104/proxy_pool/HEAD/util/webRequest.py
Generate docstrings for this script
from typing import List def bsearch_left(nums: List[int], target: int) -> int: low, high = 0, len(nums) - 1 while low <= high: mid = low + (high - low) // 2 if nums[mid] < target: low = mid + 1 else: high = mid - 1 if low < len(nums) and nums[low] == target:...
--- +++ @@ -1,7 +1,15 @@+""" + Author: Wenru + Fix: nzjia +""" from typing import List def bsearch_left(nums: List[int], target: int) -> int: + """Binary search of the index of the first element + equal to a given target in the ascending sorted array. + If not found, return -1. + """ low, h...
https://raw.githubusercontent.com/wangzheng0822/algo/HEAD/python/16_bsearch/bsearch_variants.py
Provide docstrings following PEP 257
#!/usr/bin/python # -*- coding: UTF-8 -*- from queue import Queue import pygraphviz as pgv import random OUTPUT_PATH = 'E:/' class TreeNode: def __init__(self, val=None, color=None): self.val = val assert color in ['r', 'b'] self.color = 'red' if color == 'r' else 'black' self.l...
--- +++ @@ -30,6 +30,17 @@ class RedBlackTree: + """ + 红黑树实现 + 参考资料: + 1. 《算法导论》 + 第13章 红黑树 + 13.3 插入 p178 + 13.4 删除 p183 + + 2. 红黑树(二):删除 + https://zhuanlan.zhihu.com/p/25402654 + """ def __init__(self, val_list=None): self.root = None self.black_leaf = TreeNode...
https://raw.githubusercontent.com/wangzheng0822/algo/HEAD/python/26_red_black_tree/red_black_tree.py
Can you add docstrings to this Python file?
#!/usr/bin/python # -*- coding: UTF-8 -*- import math import random class BinaryHeap: def __init__(self, data=None, capacity=100): self._data = [] self._capacity = capacity if type(data) is list: if len(data) > self._capacity: raise Exception('Heap oversize, ca...
--- +++ @@ -6,6 +6,9 @@ class BinaryHeap: + """ + 大顶堆 + """ def __init__(self, data=None, capacity=100): self._data = [] self._capacity = capacity @@ -18,9 +21,19 @@ self._length = len(self._data) def heapify(self): + """ + 堆化 + :return: + "...
https://raw.githubusercontent.com/wangzheng0822/algo/HEAD/python/28_binary_heap/binary_heap.py
Write documentation strings for class attributes
import random class SkipListNode(object): def __init__(self, val, high=1): # 节点存储的值 self.data = val # 节点对应索引层的深度 self.deeps = [None] * high class SkipList(object): def __init__(self): # 索引层的最大深度 self.__MAX_LEVEL = 16 # 跳表的高度 self._high = 1 ...
--- +++ @@ -10,6 +10,13 @@ class SkipList(object): + """ + An implementation of skip list. + The list stores positive integers without duplicates. + 跳表的一种实现方法。 + 跳表中储存的是正整数,并且储存的是不重复的。 + Author: Ben + """ def __init__(self): # 索引层的最大深度 @@ -33,6 +40,10 @@ ...
https://raw.githubusercontent.com/wangzheng0822/algo/HEAD/python/17_skiplist/skip_list_comments.py
Add clean documentation to messy code
class Heap(object): def __init__(self, nums): self._heap = nums def _siftup(self, pos): start = pos startval = self._heap[pos] n = len(self._heap) # 完全二叉树特性 child = pos * 2 + 1 # 比较叶子节点 while child < n: right = child + 1 #...
--- +++ @@ -1,9 +1,19 @@ class Heap(object): + ''' + 索引从0开始的小顶堆 + 参考: https://github.com/python/cpython/blob/master/Lib/heapq.py + + author: Ben + ''' def __init__(self, nums): self._heap = nums def _siftup(self, pos): + ''' + 从上向下的堆化 + 将pos节点的子节点中的最值提升到pos位置 +...
https://raw.githubusercontent.com/wangzheng0822/algo/HEAD/python/28_heap/min_heap.py
Add docstrings following best practices
from typing import List, Optional, Generator, IO from collections import deque class Graph: def __init__(self, num_vertices: int): self._num_vertices = num_vertices self._adjacency = [[] for _ in range(num_vertices)] def add_edge(self, s: int, t: int) -> None: self._adjacency[s].appen...
--- +++ @@ -1,8 +1,14 @@+""" + Breadth-first search and depth-first search. + + Author: Wenru Dong +""" from typing import List, Optional, Generator, IO from collections import deque class Graph: + """Undirected graph.""" def __init__(self, num_vertices: int): self._num_vertices = num_vert...
https://raw.githubusercontent.com/wangzheng0822/algo/HEAD/python/31_bfs_dfs/bfs_dfs.py
Write reusable docstrings
#!/usr/bin/python # -*- coding: UTF-8 -*- from time import time def bf(main, pattern): n = len(main) m = len(pattern) if n <= m: return 0 if pattern == main else -1 for i in range(n-m+1): for j in range(m): if main[i+j] == pattern[j]: if j == m-1: ...
--- +++ @@ -5,6 +5,12 @@ def bf(main, pattern): + """ + 字符串匹配,bf暴搜 + :param main: 主串 + :param pattern: 模式串 + :return: + """ n = len(main) m = len(pattern) @@ -24,6 +30,14 @@ def simple_hash(s, start, end): + """ + 计算子串的哈希值 + 每个字符取acs-ii码后求和 + :param s: + :param start...
https://raw.githubusercontent.com/wangzheng0822/algo/HEAD/python/32_bf_rk/bf_rk.py
Generate NumPy-style docstrings
from typing import Optional, List class Heap: def __init__(self, capacity: int): self._data = [0] * (capacity + 1) self._capacity = capacity self._count = 0 @classmethod def _parent(cls, child_index: int) -> int: return child_index // 2 @classmethod def _l...
--- +++ @@ -1,3 +1,8 @@+""" + Max-heap + + Author: Wenru Dong +""" from typing import Optional, List @@ -9,14 +14,17 @@ @classmethod def _parent(cls, child_index: int) -> int: + """The parent index.""" return child_index // 2 @classmethod def _left(cls, parent_i...
https://raw.githubusercontent.com/wangzheng0822/algo/HEAD/python/28_heap/heap.py
Create Google-style docstrings for my code
#!/usr/bin/python # -*- coding: UTF-8 -*- SIZE = 256 def bm(main, pattern): assert type(main) is str and type(pattern) is str n, m = len(main), len(pattern) if n <= m: return 0 if main == pattern else -1 # bc bc = [-1] * SIZE generate_bc(pattern, m, bc) # gs suffix = [-1] *...
--- +++ @@ -5,6 +5,15 @@ def bm(main, pattern): + """ + BM算法 + 匹配规则: + 1. 坏字符规则 + 2. 好字符规则 + :param main: + :param pattern: + :return: + """ assert type(main) is str and type(pattern) is str n, m = len(main), len(pattern) @@ -47,11 +56,26 @@ def generate_bc(pattern, m, bc)...
https://raw.githubusercontent.com/wangzheng0822/algo/HEAD/python/33_bm/bm_.py
Add professional docstrings to my codebase
#!/usr/bin/python # -*- coding: UTF-8 -*- from queue import Queue import pygraphviz as pgv OUTPUT_PATH = 'E:/' class Node: def __init__(self, c): self.data = c self.is_ending_char = False # 使用有序数组,降低空间消耗,支持更多字符 self.children = [] def insert_child(self, c): self._inse...
--- +++ @@ -18,6 +18,11 @@ self._insert_child(Node(c)) def _insert_child(self, node): + """ + 插入一个子节点 + :param c: + :return: + """ v = ord(node.data) idx = self._find_insert_idx(v) length = len(self.children) @@ -34,6 +39,11 @@ return ...
https://raw.githubusercontent.com/wangzheng0822/algo/HEAD/python/35_trie/trie_.py
Generate consistent documentation across files
#!/usr/bin/python # -*- coding: UTF-8 -*- def kmp(main, pattern): assert type(main) is str and type(pattern) is str n, m = len(main), len(pattern) if m == 0: return 0 if n <= m: return 0 if main == pattern else -1 # 求解next数组 next = get_next(pattern) j = 0 for i in r...
--- +++ @@ -3,6 +3,12 @@ def kmp(main, pattern): + """ + kmp字符串匹配 + :param main: + :param pattern: + :return: + """ assert type(main) is str and type(pattern) is str n, m = len(main), len(pattern) @@ -30,6 +36,24 @@ def get_next(pattern): + """ + next数组生成 + + 注意: + 理解的难...
https://raw.githubusercontent.com/wangzheng0822/algo/HEAD/python/34_kmp/kmp_.py
Document this script properly
#!/usr/bin/python # -*- coding: UTF-8 -*- # 棋盘尺寸 BOARD_SIZE = 8 solution_count = 0 queen_list = [0] * BOARD_SIZE def eight_queens(cur_column: int): if cur_column >= BOARD_SIZE: global solution_count solution_count += 1 # 解 print(queen_list) else: for i in range(BOARD_...
--- +++ @@ -9,6 +9,11 @@ def eight_queens(cur_column: int): + """ + 输出所有符合要求的八皇后序列 + 用一个长度为8的数组代表棋盘的列,数组的数字则为当前列上皇后所在的行数 + :return: + """ if cur_column >= BOARD_SIZE: global solution_count solution_count += 1 @@ -22,6 +27,16 @@ def is_valid_pos(cur_column: int, pos: int) ->...
https://raw.githubusercontent.com/wangzheng0822/algo/HEAD/python/39_back_track/eight_queens.py
Help me write clear docstrings
#!/usr/bin/python # -*- coding: UTF-8 -*- from typing import List, Tuple def bag(items_info: List[int], capacity: int) -> int: n = len(items_info) memo = [[-1]*(capacity+1) for i in range(n)] memo[0][0] = 1 if items_info[0] <= capacity: memo[0][items_info[0]] = 1 for i in range(1, n): ...
--- +++ @@ -5,6 +5,13 @@ def bag(items_info: List[int], capacity: int) -> int: + """ + 固定容量的背包,计算能装进背包的物品组合的最大重量 + + :param items_info: 每个物品的重量 + :param capacity: 背包容量 + :return: 最大装载重量 + """ n = len(items_info) memo = [[-1]*(capacity+1) for i in range(n)] memo[0][0] = 1 @@ -24,6 +3...
https://raw.githubusercontent.com/wangzheng0822/algo/HEAD/python/40_dynamic_programming/01_bag.py
Turn comments into proper docstrings
# 1.数组的插入、删除、按照下标随机访问操作; # 2.数组中的数据类型是Int # # Author:Lee class Array(): def __init__(self): self.__data = [] # 数据存储List def find(self, index): if index > len(self.__data) or index < 0: return False else: return self.__data[index] def delete(self, index): ...
--- +++ @@ -1,35 +1,70 @@-# 1.数组的插入、删除、按照下标随机访问操作; -# 2.数组中的数据类型是Int -# -# Author:Lee - -class Array(): - - def __init__(self): - self.__data = [] # 数据存储List - - def find(self, index): - if index > len(self.__data) or index < 0: - return False - else: - return self.__da...
https://raw.githubusercontent.com/wangzheng0822/algo/HEAD/python/array.py
Write beginner-friendly docstrings
from langchain_classic.chains import create_extraction_chain from langchain_community.chat_models import ErnieBotChat from langchain_core.prompts import ChatPromptTemplate from langchain_openai import ChatOpenAI from ..helpers import graph_schema, nodes_metadata class GraphBuilder: def __init__(self, prompt: s...
--- +++ @@ -1,3 +1,6 @@+""" +GraphBuilder Module +""" from langchain_classic.chains import create_extraction_chain from langchain_community.chat_models import ErnieBotChat @@ -8,8 +11,40 @@ class GraphBuilder: + """ + GraphBuilder is a dynamic tool for constructing web scraping graphs based on user prompt...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/builders/graph_builder.py
Document helper functions with docstrings
from typing import Optional, Type from pydantic import BaseModel from ..nodes import FetchNode, GenerateAnswerCSVNode from .abstract_graph import AbstractGraph from .base_graph import BaseGraph class CSVScraperGraph(AbstractGraph): def __init__( self, prompt: str, source: str, ...
--- +++ @@ -1,3 +1,6 @@+""" +Module for creating the smart scraper +""" from typing import Optional, Type @@ -9,6 +12,41 @@ class CSVScraperGraph(AbstractGraph): + """ + A class representing a graph for extracting information from CSV files. + + Attributes: + prompt (str): The prompt used to ge...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/csv_scraper_graph.py
Generate docstrings for each module
from typing import Optional, Type from pydantic import BaseModel from ..nodes import ( FetchNode, GenerateAnswerNode, GenerateCodeNode, HtmlAnalyzerNode, ParseNode, PromptRefinerNode, ) from ..utils.save_code_to_file import save_code_to_file from .abstract_graph import AbstractGraph from .bas...
--- +++ @@ -1,3 +1,6 @@+""" +SmartScraperGraph Module +""" from typing import Optional, Type @@ -17,6 +20,40 @@ class CodeGeneratorGraph(AbstractGraph): + """ + CodeGeneratorGraph is a script generator pipeline that generates + the function extract_data(html: str) -> dict() for + extracting the wan...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/code_generator_graph.py
Add docstrings to clarify complex logic
from typing import Optional, Type from pydantic import BaseModel from ..nodes import ( DescriptionNode, FetchNodeLevelK, GenerateAnswerNodeKLevel, ParseNodeDepthK, RAGNode, ) from .abstract_graph import AbstractGraph from .base_graph import BaseGraph class DepthSearchGraph(AbstractGraph): ...
--- +++ @@ -1,3 +1,6 @@+""" +depth search graph Module +""" from typing import Optional, Type @@ -15,6 +18,40 @@ class DepthSearchGraph(AbstractGraph): + """ + CodeGeneratorGraph is a script generator pipeline that generates + the function extract_data(html: str) -> dict() for + extracting the want...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/depth_search_graph.py
Add docstrings to clarify complex logic
import asyncio from typing import Any, AsyncIterator, Iterator, List, Optional, Union import aiohttp import async_timeout from langchain_community.document_loaders.base import BaseLoader from langchain_core.documents import Document from ..utils import Proxy, dynamic_import, get_logger, parse_or_search_proxy logger ...
--- +++ @@ -12,6 +12,17 @@ class ChromiumLoader(BaseLoader): + """Scrapes HTML pages from URLs using a (headless) instance of the + Chromium web driver with proxy protection. + + Attributes: + backend: The web driver backend library; defaults to 'playwright'. + browser_config: A dictionary co...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/docloaders/chromium.py
Generate docstrings for this script
import asyncio import uuid import warnings from abc import ABC, abstractmethod from typing import Optional, Type from langchain.chat_models import init_chat_model from langchain_core.rate_limiters import InMemoryRateLimiter from pydantic import BaseModel from ..helpers import models_tokens from ..models import XAI, ...
--- +++ @@ -1,3 +1,6 @@+""" +AbstractGraph Module +""" import asyncio import uuid @@ -22,6 +25,33 @@ class AbstractGraph(ABC): + """ + Scaffolding class for creating a graph representation and executing it. + + prompt (str): The prompt for the graph. + source (str): The source of the graph. ...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/abstract_graph.py
Create documentation for each function signature
from typing import Dict, List, Optional, Tuple from ..nodes import ( FetchNode, MarkdownifyNode, ) from .base_graph import BaseGraph class MarkdownifyGraph(BaseGraph): def __init__( self, llm_model, embedder_model=None, node_config: Optional[Dict] = None, ): ...
--- +++ @@ -1,3 +1,6 @@+""" +markdownify_graph module +""" from typing import Dict, List, Optional, Tuple @@ -9,6 +12,27 @@ class MarkdownifyGraph(BaseGraph): + """ + A graph that converts HTML content to Markdown format. + + This graph takes a URL or HTML content as input and converts it to clean, re...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/markdownify_graph.py
Add standardized docstrings across the file
from typing import Optional, Type from pydantic import BaseModel from ..nodes import FetchNode, GenerateAnswerNode from .abstract_graph import AbstractGraph from .base_graph import BaseGraph class JSONScraperGraph(AbstractGraph): def __init__( self, prompt: str, source: str, co...
--- +++ @@ -1,3 +1,6 @@+""" +JSONScraperGraph Module +""" from typing import Optional, Type @@ -9,6 +12,34 @@ class JSONScraperGraph(AbstractGraph): + """ + JSONScraperGraph defines a scraping pipeline for JSON files. + + Attributes: + prompt (str): The prompt for the graph. + source (st...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/json_scraper_graph.py
Annotate my code with docstrings
from typing import Optional import torch from torch import Tensor from torch_geometric.typing import TensorFrame def mask_select(src: Tensor, dim: int, mask: Tensor) -> Tensor: assert mask.dim() == 1 if not torch.jit.is_scripting(): if isinstance(src, TensorFrame): assert dim == 0 and s...
--- +++ @@ -7,6 +7,15 @@ def mask_select(src: Tensor, dim: int, mask: Tensor) -> Tensor: + r"""Returns a new tensor which masks the :obj:`src` tensor along the + dimension :obj:`dim` according to the boolean mask :obj:`mask`. + + Args: + src (torch.Tensor): The input tensor. + dim (int): The ...
https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/mask.py
Add inline docstrings for readability
from typing import Optional, Type from pydantic import BaseModel from ..nodes import FetchNode, GenerateAnswerNode, ParseNode from .abstract_graph import AbstractGraph from .base_graph import BaseGraph class DocumentScraperGraph(AbstractGraph): def __init__( self, prompt: str, source: ...
--- +++ @@ -1,3 +1,6 @@+""" +This module implements the Document Scraper Graph for the ScrapeGraphAI application. +""" from typing import Optional, Type @@ -9,6 +12,36 @@ class DocumentScraperGraph(AbstractGraph): + """ + DocumentScraperGraph is a scraping pipeline that automates the process of + extr...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/document_scraper_graph.py
Add return value explanations in docstrings
from typing import Optional, Tuple, Union import torch from torch import Tensor from torch_geometric.utils import cumsum, negative_sampling, scatter def shuffle_node( x: Tensor, batch: Optional[Tensor] = None, training: bool = True, ) -> Tuple[Tensor, Tensor]: if not training: perm = torch.a...
--- +++ @@ -11,6 +11,48 @@ batch: Optional[Tensor] = None, training: bool = True, ) -> Tuple[Tensor, Tensor]: + r"""Randomly shuffle the feature matrix :obj:`x` along the + first dimension. + + The method returns (1) the shuffled :obj:`x`, (2) the permutation + indicating the orders of original no...
https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/augmentation.py
Write proper docstrings for these functions
from copy import deepcopy from typing import List, Optional, Type from pydantic import BaseModel from ..nodes import GraphIteratorNode, MergeAnswersNode from ..utils.copy import safe_deepcopy from .abstract_graph import AbstractGraph from .base_graph import BaseGraph from .document_scraper_graph import DocumentScrap...
--- +++ @@ -1,3 +1,6 @@+""" +DocumentScraperMultiGraph Module +""" from copy import deepcopy from typing import List, Optional, Type @@ -12,6 +15,32 @@ class DocumentScraperMultiGraph(AbstractGraph): + """ + DocumentScraperMultiGraph is a scraping pipeline that scrapes a list of URLs and + generates an...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/document_scraper_multi_graph.py
Generate docstrings for each module
from copy import deepcopy from typing import Optional, Type from pydantic import BaseModel from ..nodes import GraphIteratorNode, MergeAnswersNode, SearchInternetNode from ..utils.copy import safe_deepcopy from .abstract_graph import AbstractGraph from .base_graph import BaseGraph from .omni_scraper_graph import Omn...
--- +++ @@ -1,3 +1,6 @@+""" +OmniSearchGraph Module +""" from copy import deepcopy from typing import Optional, Type @@ -12,6 +15,31 @@ class OmniSearchGraph(AbstractGraph): + """ + OmniSearchGraph is a scraping pipeline that searches the internet for answers to a given prompt. + It only requires a use...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/omni_search_graph.py
Document functions with clear intent
import typing from typing import Optional, Tuple, Union import torch from torch import Tensor from torch_geometric import EdgeIndex from torch_geometric.utils import scatter from torch_geometric.utils.num_nodes import maybe_num_nodes from torch_geometric.utils.sparse import ( is_torch_sparse_tensor, to_edge_i...
--- +++ @@ -21,6 +21,25 @@ def contains_self_loops(edge_index: Tensor) -> bool: + r"""Returns :obj:`True` if the graph given by :attr:`edge_index` contains + self-loops. + + Args: + edge_index (LongTensor): The edge indices. + + :rtype: bool + + Examples: + >>> edge_index = torch.tensor...
https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/loop.py
Add docstrings following best practices
from copy import deepcopy from typing import List, Optional, Type from pydantic import BaseModel from ..nodes import ( ConcatAnswersNode, ConditionalNode, GraphIteratorNode, MergeAnswersNode, ) from ..utils.copy import safe_deepcopy from .abstract_graph import AbstractGraph from .base_graph import Ba...
--- +++ @@ -1,3 +1,6 @@+""" +SmartScraperMultiCondGraph Module with ConditionalNode +""" from copy import deepcopy from typing import List, Optional, Type @@ -17,6 +20,31 @@ class SmartScraperMultiConcatGraph(AbstractGraph): + """ + SmartScraperMultiConditionalGraph is a scraping pipeline that scrapes a +...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/smart_scraper_multi_concat_graph.py
Add docstrings that explain purpose and usage
from typing import Optional, Type from pydantic import BaseModel from ..nodes import FetchNode, ParseNode from .abstract_graph import AbstractGraph from .base_graph import BaseGraph class SmartScraperLiteGraph(AbstractGraph): def __init__( self, source: str, config: dict, promp...
--- +++ @@ -1,3 +1,6 @@+""" +SmartScraperGraph Module +""" from typing import Optional, Type @@ -9,6 +12,32 @@ class SmartScraperLiteGraph(AbstractGraph): + """ + SmartScraperLiteGraph is a scraping pipeline that automates the process of + extracting information from web pages. + + Attributes: + ...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/smart_scraper_lite_graph.py
Add detailed documentation for each class
import math from typing import Literal, Optional import torch from torch import Tensor def get_smld_sigma_schedule( sigma_min: float, sigma_max: float, num_scales: int, dtype: Optional[torch.dtype] = None, device: Optional[torch.device] = None, ) -> Tensor: return torch.linspace( math...
--- +++ @@ -12,6 +12,28 @@ dtype: Optional[torch.dtype] = None, device: Optional[torch.device] = None, ) -> Tensor: + r"""Generates a set of noise values on a logarithmic scale for "Score + Matching with Langevin Dynamics" from the `"Generative Modeling by + Estimating Gradients of the Data Distribut...
https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/noise_scheduler.py
Improve documentation using docstrings
from typing import Optional, Type from pydantic import BaseModel from ..models import OpenAIImageToText from ..nodes import FetchNode, GenerateAnswerOmniNode, ImageToTextNode, ParseNode from .abstract_graph import AbstractGraph from .base_graph import BaseGraph class OmniScraperGraph(AbstractGraph): def __ini...
--- +++ @@ -1,3 +1,6 @@+""" +This module implements the Omni Scraper Graph for the ScrapeGraphAI application. +""" from typing import Optional, Type @@ -10,6 +13,38 @@ class OmniScraperGraph(AbstractGraph): + """ + OmniScraper is a scraping pipeline that automates the process of + extracting informati...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/omni_scraper_graph.py
Add docstrings to make code maintainable
from copy import deepcopy from typing import List, Optional, Type from pydantic import BaseModel from ..nodes import GraphIteratorNode, MergeAnswersNode from ..utils.copy import safe_deepcopy from .abstract_graph import AbstractGraph from .base_graph import BaseGraph from .smart_scraper_graph import SmartScraperGrap...
--- +++ @@ -1,3 +1,6 @@+""" +SmartScraperMultiGraph Module +""" from copy import deepcopy from typing import List, Optional, Type @@ -12,6 +15,38 @@ class SmartScraperMultiGraph(AbstractGraph): + """ + SmartScraperMultiGraph is a scraping pipeline that scrapes a + list of URLs and generates answers to ...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/smart_scraper_multi_graph.py
Add concise docstrings to each method
from copy import deepcopy from typing import List, Optional, Type from pydantic import BaseModel from ..nodes import GraphIteratorNode, MergeAnswersNode from ..utils.copy import safe_deepcopy from .abstract_graph import AbstractGraph from .base_graph import BaseGraph from .json_scraper_graph import JSONScraperGraph ...
--- +++ @@ -1,3 +1,6 @@+""" +JSONScraperMultiGraph Module +""" from copy import deepcopy from typing import List, Optional, Type @@ -12,6 +15,32 @@ class JSONScraperMultiGraph(AbstractGraph): + """ + JSONScraperMultiGraph is a scraping pipeline that scrapes a + list of URLs and generates answers to a g...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/json_scraper_multi_graph.py
Create simple docstrings for beginners
from copy import deepcopy from typing import List, Optional, Type from pydantic import BaseModel from ..nodes import GraphIteratorNode, MergeAnswersNode from ..utils.copy import safe_deepcopy from .abstract_graph import AbstractGraph from .base_graph import BaseGraph from .smart_scraper_lite_graph import SmartScrape...
--- +++ @@ -1,3 +1,6 @@+""" +SmartScraperMultiGraph Module +""" from copy import deepcopy from typing import List, Optional, Type @@ -12,6 +15,38 @@ class SmartScraperMultiLiteGraph(AbstractGraph): + """ + SmartScraperMultiLiteGraph is a scraping pipeline that scrapes a + list of URLs and merge the con...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/smart_scraper_multi_lite_graph.py
Document my Python code with docstrings
from typing import Optional, Type from pydantic import BaseModel from ..models import OpenAITextToSpeech from ..nodes import FetchNode, GenerateAnswerNode, ParseNode, TextToSpeechNode from ..utils.save_audio_from_bytes import save_audio_from_bytes from .abstract_graph import AbstractGraph from .base_graph import Bas...
--- +++ @@ -1,3 +1,6 @@+""" +SpeechGraph Module +""" from typing import Optional, Type @@ -11,6 +14,34 @@ class SpeechGraph(AbstractGraph): + """ + SpeechyGraph is a scraping pipeline that scrapes the web, provide an answer + to a given prompt, and generate an audio file. + + Attributes: + p...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/speech_graph.py
Add docstrings following best practices
from copy import deepcopy from typing import List, Optional, Type from pydantic import BaseModel from ..nodes import GraphIteratorNode, MergeAnswersNode from ..utils.copy import safe_deepcopy from .abstract_graph import AbstractGraph from .base_graph import BaseGraph from .xml_scraper_graph import XMLScraperGraph ...
--- +++ @@ -1,3 +1,6 @@+""" +XMLScraperMultiGraph Module +""" from copy import deepcopy from typing import List, Optional, Type @@ -12,6 +15,32 @@ class XMLScraperMultiGraph(AbstractGraph): + """ + XMLScraperMultiGraph is a scraping pipeline that scrapes a list of URLs and + generates answers to a give...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/xml_scraper_multi_graph.py
Add docstrings following best practices
from openai import OpenAI class OpenAITextToSpeech: def __init__(self, tts_config: dict): self.client = OpenAI( api_key=tts_config.get("api_key"), base_url=tts_config.get("base_url", None) ) self.model = tts_config.get("model", "tts-1") self.voice = tts_config.get("vo...
--- +++ @@ -1,8 +1,22 @@+""" +OpenAITextToSpeech Module +""" from openai import OpenAI class OpenAITextToSpeech: + """ + Implements a text-to-speech model using the OpenAI API. + + Attributes: + client (OpenAI): The OpenAI client used to interact with the API. + model (str): The model to ...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/models/openai_tts.py
Add docstrings with type hints explained
# -*- coding: utf-8 -*- __author__ = 'JHao' from redis.exceptions import TimeoutError, ConnectionError, ResponseError from redis.connection import BlockingConnectionPool from handler.logHandler import LogHandler from random import choice from redis import Redis import json class RedisClient(object): def __init_...
--- +++ @@ -1,4 +1,17 @@ # -*- coding: utf-8 -*- +""" +----------------------------------------------------- + File Name: redisClient.py + Description : 封装Redis相关操作 + Author : JHao + date: 2019/8/9 +------------------------------------------------------ + Change Activity: + ...
https://raw.githubusercontent.com/jhao104/proxy_pool/HEAD/db/redisClient.py
Generate docstrings for each module
import inspect import re import uuid from typing import Any, Dict, List, Tuple try: from burr import tracking from burr.core import ( Action, Application, ApplicationBuilder, ApplicationContext, State, default, ) from burr.lifecycle import PostRunStepHoo...
--- +++ @@ -1,3 +1,7 @@+""" +Bridge class to integrate Burr into ScrapeGraphAI graphs +[Burr](https://github.com/DAGWorks-Inc/burr) +""" import inspect import re @@ -23,6 +27,9 @@ class PrintLnHook(PostRunStepHook, PreRunStepHook): + """ + Hook to print the action name before and after it is executed. + ...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/integrations/burr_bridge.py
Generate docstrings for exported functions
from typing import List, Optional from ..nodes.base_node import BaseNode class IndexifyNode(BaseNode): def __init__( self, input: str, output: List[str], node_config: Optional[dict] = None, node_name: str = "Indexify", ): super().__init__(node_name, "node", i...
--- +++ @@ -1,3 +1,6 @@+""" +IndexifyNode Module +""" from typing import List, Optional @@ -5,6 +8,18 @@ class IndexifyNode(BaseNode): + """ + A node responsible for indexing the content present in the state. + + Attributes: + verbose (bool): A flag indicating whether to show print statements d...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/integrations/indexify_node.py
Add docstrings to meet PEP guidelines
from typing import Optional, Type from pydantic import BaseModel from ..nodes import FetchNode, GenerateAnswerNode from .abstract_graph import AbstractGraph from .base_graph import BaseGraph class XMLScraperGraph(AbstractGraph): def __init__( self, prompt: str, source: str, con...
--- +++ @@ -1,3 +1,6 @@+""" +XMLScraperGraph Module +""" from typing import Optional, Type @@ -9,6 +12,36 @@ class XMLScraperGraph(AbstractGraph): + """ + XMLScraperGraph is a scraping pipeline that extracts information from XML files using a natural + language model to interpret and answer prompts. +...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/xml_scraper_graph.py
Annotate my code with docstrings
from langchain_core.messages import HumanMessage from langchain_openai import ChatOpenAI class OpenAIImageToText(ChatOpenAI): def __init__(self, llm_config: dict): super().__init__(**llm_config, max_tokens=256) def run(self, image_url: str) -> str: message = HumanMessage( conten...
--- +++ @@ -1,14 +1,35 @@+""" +OpenAIImageToText Module +""" from langchain_core.messages import HumanMessage from langchain_openai import ChatOpenAI class OpenAIImageToText(ChatOpenAI): + """ + A wrapper for the OpenAIImageToText class that provides default configuration + and could be extended with ...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/models/openai_itt.py
Fully document this Python code with docstrings
from typing import List, Optional from simpleeval import EvalWithCompoundTypes, simple_eval from .base_node import BaseNode class ConditionalNode(BaseNode): def __init__( self, input: str, output: List[str], node_config: Optional[dict] = None, node_name: str = "Cond", ...
--- +++ @@ -1,3 +1,6 @@+""" +Module for implementing the conditional node +""" from typing import List, Optional @@ -7,6 +10,28 @@ class ConditionalNode(BaseNode): + """ + A node that determines the next step in the graph's execution flow based on + the presence and content of a specified key in the g...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/conditional_node.py
Document this code for team use
import asyncio import base64 from typing import List, Optional import aiohttp from .base_node import BaseNode class GenerateAnswerFromImageNode(BaseNode): def __init__( self, input: str, output: List[str], node_config: Optional[dict] = None, node_name: str = "GenerateAn...
--- +++ @@ -1,3 +1,6 @@+""" +GenerateAnswerFromImageNode Module +""" import asyncio import base64 @@ -9,6 +12,10 @@ class GenerateAnswerFromImageNode(BaseNode): + """ + GenerateAnswerFromImageNode analyzes images from the state dictionary using the OpenAI API + and updates the state with the consolidat...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/generate_answer_from_image_node.py
Write docstrings for data processing functions
import json import time from typing import List, Optional from langchain_core.prompts import PromptTemplate from langchain_aws import ChatBedrock from langchain_community.chat_models import ChatOllama from langchain_core.output_parsers import JsonOutputParser from langchain_core.runnables import RunnableParallel from...
--- +++ @@ -1,3 +1,6 @@+""" +GenerateAnswerNode Module +""" import json import time @@ -25,6 +28,26 @@ class GenerateAnswerNode(BaseNode): + """ + Initializes the GenerateAnswerNode class. + + Args: + input (str): The input data type for the node. + output (List[str]): The output data typ...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/generate_answer_node.py
Add docstrings for production code
import ast import json import re import sys from io import StringIO from typing import Any, Dict, List, Optional from bs4 import BeautifulSoup from jsonschema import ValidationError as JSONSchemaValidationError from jsonschema import validate from langchain_classic.output_parsers import ResponseSchema, StructuredOutp...
--- +++ @@ -1,3 +1,6 @@+""" +GenerateCodeNode Module +""" import ast import json @@ -32,6 +35,20 @@ class GenerateCodeNode(BaseNode): + """ + A node that generates Python code for a function that extracts data + from HTML based on a output schema. + + Attributes: + llm_model: An instance of a...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/generate_code_node.py
Add docstrings to improve readability
import re from abc import ABC, abstractmethod from typing import List, Optional from ..utils import get_logger class BaseNode(ABC): def __init__( self, node_name: str, node_type: str, input: str, output: List[str], min_input_len: int = 1, node_config: Opt...
--- +++ @@ -1,3 +1,6 @@+""" +This module defines the base node class for the ScrapeGraphAI application. +""" import re from abc import ABC, abstractmethod @@ -7,6 +10,40 @@ class BaseNode(ABC): + """ + An abstract base class for nodes in a graph-based workflow, + designed to perform specific actions wh...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/base_node.py
Write docstrings for utility functions
from typing import List, Optional from langchain_aws import ChatBedrock from langchain_community.chat_models import ChatOllama from langchain_core.output_parsers import JsonOutputParser from langchain_core.prompts import PromptTemplate from langchain_core.runnables import RunnableParallel from langchain_mistralai imp...
--- +++ @@ -1,3 +1,6 @@+""" +GenerateAnswerNodeKLevel Module +""" from typing import List, Optional @@ -26,6 +29,22 @@ class GenerateAnswerNodeKLevel(BaseNode): + """ + A node responsible for compressing the input tokens and storing the document + in a vector database for retrieval. Relevant chunks ar...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/generate_answer_node_k_level.py
Add missing documentation to my Python functions
from typing import List, Optional from .base_node import BaseNode class ConcatAnswersNode(BaseNode): def __init__( self, input: str, output: List[str], node_config: Optional[dict] = None, node_name: str = "ConcatAnswers", ): super().__init__(node_name, "node"...
--- +++ @@ -1,3 +1,6 @@+""" +ConcatAnswersNode Module +""" from typing import List, Optional @@ -5,6 +8,19 @@ class ConcatAnswersNode(BaseNode): + """ + A node responsible for concatenating the answers from multiple + graph instances into a single answer. + + Attributes: + verbose (bool): A ...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/concat_answers_node.py
Please document this code using docstrings
from typing import List, Optional from langchain_core.prompts import PromptTemplate from langchain_community.chat_models import ChatOllama from langchain_core.output_parsers import JsonOutputParser from langchain_core.runnables import RunnableParallel from langchain_mistralai import ChatMistralAI from langchain_opena...
--- +++ @@ -1,3 +1,6 @@+""" +GenerateAnswerNode Module +""" from typing import List, Optional @@ -22,6 +25,22 @@ class GenerateAnswerOmniNode(BaseNode): + """ + A node that generates an answer using a large language model (LLM) based on the user's input + and the content extracted from a webpage. It c...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/generate_answer_omni_node.py
Improve my code by adding docstrings
from typing import List, Optional from langchain_core.prompts import PromptTemplate from langchain_core.output_parsers import JsonOutputParser from langchain_core.runnables import RunnableParallel from langchain_mistralai import ChatMistralAI from langchain_openai import ChatOpenAI from tqdm import tqdm from ..promp...
--- +++ @@ -1,3 +1,6 @@+""" +Module for generating the answer node +""" from typing import List, Optional @@ -17,6 +20,29 @@ class GenerateAnswerCSVNode(BaseNode): + """ + A node that generates an answer using a language model (LLM) based on the user's input + and the content extracted from a webpage....
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/generate_answer_csv_node.py
Create documentation strings for testing functions
from typing import List, Optional from langchain_core.prompts import PromptTemplate from langchain_core.output_parsers import JsonOutputParser, StrOutputParser from .base_node import BaseNode class GenerateScraperNode(BaseNode): def __init__( self, input: str, output: List[str], ...
--- +++ @@ -1,3 +1,6 @@+""" +GenerateScraperNode Module +""" from typing import List, Optional @@ -8,6 +11,25 @@ class GenerateScraperNode(BaseNode): + """ + Generates a python script for scraping a website using the specified library. + It takes the user's prompt and the scraped content as input and ...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/generate_scraper_node.py
Generate docstrings for this script
import warnings from typing import Any, List, Optional, Tuple, Union import torch from torch import Tensor import torch_geometric.typing from torch_geometric.index import index2ptr, ptr2index from torch_geometric.typing import SparseTensor from torch_geometric.utils import coalesce, cumsum def dense_to_sparse( ...
--- +++ @@ -14,6 +14,57 @@ adj: Tensor, mask: Optional[Tensor] = None, ) -> Tuple[Tensor, Tensor]: + r"""Converts a dense adjacency matrix to a sparse adjacency matrix defined + by edge indices and edge attributes. + + Args: + adj (torch.Tensor): The dense adjacency matrix of shape + ...
https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/sparse.py
Add docstrings that explain logic
import asyncio from typing import List, Optional, Type from pydantic import BaseModel from tqdm.asyncio import tqdm from .base_node import BaseNode DEFAULT_BATCHSIZE = 16 class GraphIteratorNode(BaseNode): def __init__( self, input: str, output: List[str], node_config: Optiona...
--- +++ @@ -1,3 +1,6 @@+""" +GraphIterator Module +""" import asyncio from typing import List, Optional, Type @@ -11,6 +14,19 @@ class GraphIteratorNode(BaseNode): + """ + A node responsible for instantiating and running multiple graph instances in parallel. + It creates as many graph instances as the ...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/graph_iterator_node.py
Create Google-style docstrings for my code
import json from typing import List, Optional import concurrent.futures import requests from langchain_community.document_loaders import PyPDFLoader from langchain_core.documents import Document from langchain_openai import AzureChatOpenAI, ChatOpenAI from ..docloaders import ChromiumLoader from ..utils.cleanup_html...
--- +++ @@ -1,3 +1,6 @@+""" +FetchNode Module +""" import json from typing import List, Optional @@ -15,6 +18,24 @@ class FetchNode(BaseNode): + """ + A node responsible for fetching the HTML content of a specified URL and updating + the graph's state with this content. It uses ChromiumLoader to fetch ...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/fetch_node.py
Provide docstrings following PEP 257
from typing import List from langchain_core.output_parsers import CommaSeparatedListOutputParser from langchain_core.prompts import PromptTemplate from ..prompts import TEMPLATE_GET_PROBABLE_TAGS from .base_node import BaseNode class GetProbableTagsNode(BaseNode): def __init__( self, input: st...
--- +++ @@ -1,3 +1,6 @@+""" +GetProbableTagsNode Module +""" from typing import List @@ -9,6 +12,21 @@ class GetProbableTagsNode(BaseNode): + """ + A node that utilizes a language model to identify probable HTML tags within a document that + are likely to contain the information relevant to a user's q...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/get_probable_tags_node.py
Add missing documentation to my Python functions
from typing import List, Optional from langchain_core.messages import HumanMessage from .base_node import BaseNode class ImageToTextNode(BaseNode): def __init__( self, input: str, output: List[str], node_config: Optional[dict] = None, node_name: str = "ImageToText", ...
--- +++ @@ -1,3 +1,6 @@+""" +ImageToTextNode Module +""" from typing import List, Optional @@ -7,6 +10,20 @@ class ImageToTextNode(BaseNode): + """ + Retrieve images from a list of URLs and return a description of + the images using an image-to-text model. + + Attributes: + llm_model: An ins...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/image_to_text_node.py
Generate docstrings with parameter types
from typing import List, Optional from langchain_core.prompts import PromptTemplate from langchain_community.chat_models import ChatOllama from langchain_core.output_parsers import JsonOutputParser from langchain_mistralai import ChatMistralAI from langchain_openai import ChatOpenAI from ..prompts import TEMPLATE_CO...
--- +++ @@ -1,3 +1,6 @@+""" +MergeAnswersNode Module +""" from typing import List, Optional @@ -16,6 +19,19 @@ class MergeAnswersNode(BaseNode): + """ + A node responsible for merging the answers from multiple graph instances into a single answer. + + Attributes: + llm_model: An instance of a l...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/merge_answers_node.py
Fill in missing docstrings in my code
from typing import List, Optional from langchain_core.prompts import PromptTemplate from langchain_community.chat_models import ChatOllama from langchain_core.output_parsers import StrOutputParser from ..prompts import TEMPLATE_HTML_ANALYSIS, TEMPLATE_HTML_ANALYSIS_WITH_CONTEXT from ..utils import reduce_html from ....
--- +++ @@ -1,3 +1,6 @@+""" +HtmlAnalyzerNode Module +""" from typing import List, Optional @@ -11,6 +14,19 @@ class HtmlAnalyzerNode(BaseNode): + """ + A node that generates an analysis of the provided HTML code based on the wanted infromations to be extracted. + + Attributes: + llm_model: An ...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/html_analyzer_node.py
Document helper functions with docstrings
from typing import List, Optional from ..utils.convert_to_md import convert_to_md from .base_node import BaseNode class MarkdownifyNode(BaseNode): def __init__( self, input: str, output: List[str], node_config: Optional[dict] = None, node_name: str = "Markdownify", )...
--- +++ @@ -1,3 +1,6 @@+""" +MarkdownifyNode Module +""" from typing import List, Optional @@ -6,6 +9,21 @@ class MarkdownifyNode(BaseNode): + """ + A node responsible for converting HTML content to Markdown format. + + This node takes HTML content from the state and converts it to clean, readable Mar...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/markdownify_node.py
Add docstrings explaining edge cases
from typing import List, Optional from langchain_core.prompts import PromptTemplate from langchain_core.output_parsers import StrOutputParser from ..prompts import TEMPLATE_MERGE_SCRIPTS_PROMPT from .base_node import BaseNode class MergeGeneratedScriptsNode(BaseNode): def __init__( self, input...
--- +++ @@ -1,3 +1,6 @@+""" +MergeAnswersNode Module +""" from typing import List, Optional @@ -9,6 +12,17 @@ class MergeGeneratedScriptsNode(BaseNode): + """ + A node responsible for merging scripts generated. + Attributes: + llm_model: An instance of a language model client, configured for ge...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/merge_generated_scripts_node.py
Provide docstrings following PEP 257
from typing import List, Optional from langchain_core.output_parsers import CommaSeparatedListOutputParser from langchain_core.prompts import PromptTemplate from langchain_community.chat_models import ChatOllama from ..prompts import TEMPLATE_SEARCH_INTERNET from ..utils.research_web import search_on_web from .base_...
--- +++ @@ -1,3 +1,6 @@+""" +SearchInternetNode Module +""" from typing import List, Optional @@ -11,6 +14,22 @@ class SearchInternetNode(BaseNode): + """ + A node that generates a search query based on the user's input and searches the internet + for relevant information. The node constructs a prompt...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/search_internet_node.py
Add inline docstrings for readability
from typing import List, Optional from langchain_core.prompts import PromptTemplate from langchain_community.chat_models import ChatOllama from langchain_core.output_parsers import StrOutputParser from ..prompts import TEMPLATE_REASONING, TEMPLATE_REASONING_WITH_CONTEXT from ..utils import transform_schema from .bas...
--- +++ @@ -1,3 +1,6 @@+""" +PromptRefinerNode Module +""" from typing import List, Optional @@ -11,6 +14,21 @@ class ReasoningNode(BaseNode): + """ + A node that refine the user prompt with the use of the schema and additional context and + create a precise prompt in subsequent steps that explicitly ...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/reasoning_node.py
Generate documentation strings for clarity
from typing import List, Optional from langchain_community.document_transformers import Html2TextTransformer from .base_node import BaseNode class ParseNodeDepthK(BaseNode): def __init__( self, input: str, output: List[str], node_config: Optional[dict] = None, node_name...
--- +++ @@ -1,3 +1,6 @@+""" +ParseNodeDepthK Module +""" from typing import List, Optional @@ -7,6 +10,21 @@ class ParseNodeDepthK(BaseNode): + """ + A node responsible for parsing HTML content from a series of documents. + + This node enhances the scraping workflow by allowing for targeted extraction...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/parse_node_depth_k_node.py
Help me document legacy Python code
import re from typing import List, Optional, Tuple from urllib.parse import urljoin from langchain_community.document_transformers import Html2TextTransformer from langchain_core.documents import Document from ..helpers import default_filters from ..utils.split_text_into_chunks import split_text_into_chunks from .ba...
--- +++ @@ -1,3 +1,6 @@+""" +ParseNode Module +""" import re from typing import List, Optional, Tuple @@ -12,6 +15,22 @@ class ParseNode(BaseNode): + """ + A node responsible for parsing HTML content from a document. + The parsed content is split into chunks for further processing. + + This node enh...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/parse_node.py
Create documentation strings for testing functions
from typing import List, Optional from urllib.parse import urlparse from langchain_core.output_parsers import CommaSeparatedListOutputParser from langchain_core.prompts import PromptTemplate from langchain_community.document_loaders import AsyncChromiumLoader from ..helpers import robots_dictionary from ..prompts im...
--- +++ @@ -1,3 +1,6 @@+""" +RobotsNode Module +""" from typing import List, Optional from urllib.parse import urlparse @@ -12,6 +15,27 @@ class RobotsNode(BaseNode): + """ + A node responsible for checking if a website is scrapeable or not based on the robots.txt file. + It uses a language model to de...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/robots_node.py
Document functions with detailed explanations
from typing import List, Optional from .base_node import BaseNode class TextToSpeechNode(BaseNode): def __init__( self, input: str, output: List[str], node_config: Optional[dict] = None, node_name: str = "TextToSpeech", ): super().__init__(node_name, "node", ...
--- +++ @@ -1,3 +1,6 @@+""" +TextToSpeechNode Module +""" from typing import List, Optional @@ -5,6 +8,19 @@ class TextToSpeechNode(BaseNode): + """ + Converts text to speech using the specified text-to-speech model. + + Attributes: + tts_model: An instance of the text-to-speech model client. +...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/text_to_speech_node.py
Add docstrings for production code
import re from typing import List, Optional from urllib.parse import parse_qs, urlparse from langchain_core.prompts import PromptTemplate from langchain_core.output_parsers import JsonOutputParser from tqdm import tqdm from ..helpers import default_filters from ..prompts import TEMPLATE_RELEVANT_LINKS from .base_nod...
--- +++ @@ -1,3 +1,6 @@+""" +SearchLinkNode Module +""" import re from typing import List, Optional @@ -13,6 +16,21 @@ class SearchLinkNode(BaseNode): + """ + A node that can filter out the relevant links in the webpage content for the user prompt. + Node expects the already scrapped links on the webpa...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/search_link_node.py
Create docstrings for API functions
from typing import List, Optional from langchain_core.prompts import PromptTemplate from langchain_community.chat_models import ChatOllama from langchain_core.output_parsers import StrOutputParser from ..prompts import TEMPLATE_REFINER, TEMPLATE_REFINER_WITH_CONTEXT from ..utils import transform_schema from .base_no...
--- +++ @@ -1,3 +1,6 @@+""" +PromptRefinerNode Module +""" from typing import List, Optional @@ -11,6 +14,21 @@ class PromptRefinerNode(BaseNode): + """ + A node that refine the user prompt with the use of the schema and additional context and + create a precise prompt in subsequent steps that explici...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/prompt_refiner_node.py
Add docstrings that explain inputs and outputs
from typing import List, Optional from langchain_core.output_parsers import CommaSeparatedListOutputParser from langchain_core.prompts import PromptTemplate from tqdm import tqdm from ..prompts import ( TEMPLATE_SEARCH_WITH_CONTEXT_CHUNKS, TEMPLATE_SEARCH_WITH_CONTEXT_NO_CHUNKS, ) from .base_node import Base...
--- +++ @@ -1,3 +1,6 @@+""" +SearchInternetNode Module +""" from typing import List, Optional @@ -13,6 +16,23 @@ class SearchLinksWithContext(BaseNode): + """ + A node that generates a search query based on the user's input and searches the internet + for relevant information. The node constructs a pr...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/search_node_with_context.py
Add docstrings to make code maintainable
import copy from typing import Any class DeepCopyError(Exception): pass def is_boto3_client(obj): import sys boto3_module = sys.modules.get("boto3") if boto3_module: try: from botocore.client import BaseClient return isinstance(obj, BaseClient) except (At...
--- +++ @@ -1,14 +1,23 @@+""" +copy module +""" import copy from typing import Any class DeepCopyError(Exception): + """ + Custom exception raised when an object cannot be deep-copied. + """ pass def is_boto3_client(obj): + """ + Function for understanding if the script is using boto...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/utils/copy.py
Add docstrings to improve collaboration
import json from typing import Any, Dict, Optional from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import PromptTemplate from pydantic import BaseModel, Field, validator from ..prompts import ( TEMPLATE_EXECUTION_ANALYSIS, TEMPLATE_SEMANTIC_ANALYSIS, TEMPLATE_SYNTAX_...
--- +++ @@ -1,3 +1,15 @@+""" +This module contains the functions that generate prompts for various types of code error analysis. + +Functions: +- syntax_focused_analysis: Focuses on syntax-related errors in the generated code. +- execution_focused_analysis: Focuses on execution-related errors, +including generated code...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/utils/code_error_analysis.py
Generate descriptive docstrings automatically
import json import re from urllib.parse import urljoin from bs4 import BeautifulSoup, Comment from minify_html import minify def extract_from_script_tags(soup): script_content = [] for script in soup.find_all("script"): content = script.string if content: try: js...
--- +++ @@ -1,3 +1,6 @@+""" +Module for minimizing the code +""" import json import re @@ -43,6 +46,25 @@ def cleanup_html(html_content: str, base_url: str) -> str: + """ + Processes HTML content by removing unnecessary tags, + minifying the HTML, and extracting the title and body content. + + Args:...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/utils/cleanup_html.py
Generate consistent documentation across files
import json from functools import lru_cache from typing import Any, Dict from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import PromptTemplate from pydantic import BaseModel, Field from ..prompts import ( TEMPLATE_EXECUTION_CODE_GENERATION, TEMPLATE_SEMANTIC_CODE_GENERAT...
--- +++ @@ -1,3 +1,14 @@+""" +This module contains the functions for code generation to correct different types of errors. + +Functions: +- syntax_focused_code_generation: Generates corrected code based on syntax error analysis. +- execution_focused_code_generation: Generates corrected code based on execution error ana...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/utils/code_error_correction.py
Add docstrings to clarify complex logic
import threading from contextlib import contextmanager from langchain_aws import ChatBedrock from langchain_community.callbacks.manager import ( get_bedrock_anthropic_callback, get_openai_callback, ) from langchain_openai import AzureChatOpenAI, ChatOpenAI from .custom_callback import get_custom_callback c...
--- +++ @@ -1,3 +1,9 @@+""" +This module provides a custom callback manager for LLM models. + +Classes: +- CustomLLMCallbackManager: Manages exclusive access to callbacks for different types of LLM models. +""" import threading from contextlib import contextmanager @@ -13,11 +19,32 @@ class CustomLLMCallbackMan...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/utils/llm_callback_manager.py
Add clean documentation to messy code
import configparser import functools import importlib.metadata import json import logging import os import threading import uuid from typing import Callable, Dict from urllib import request VERSION = importlib.metadata.version("scrapegraphai") TRACK_URL = "https://sgai-oss-tracing.onrender.com/v1/telemetry" TIMEOUT = 2...
--- +++ @@ -85,6 +85,7 @@ llm_model: str | None, source: list[str] | None, ) -> dict | None: + """Build telemetry payload dict. Returns None if required fields are missing.""" url = source[0] if isinstance(source, list) and source else None if isinstance(content, list): @@ -122,6 +123,7 @@ ...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/telemetry/telemetry.py
Generate NumPy-style docstrings
from typing import Any, Dict, List def normalize_dict(d: Dict[str, Any]) -> Dict[str, Any]: normalized = {} for key, value in d.items(): if isinstance(value, str): normalized[key] = value.lower().strip() elif isinstance(value, dict): normalized[key] = normalize_dict(va...
--- +++ @@ -1,8 +1,28 @@+""" +This module contains utility functions for comparing the content of two dictionaries. + +Functions: +- normalize_dict: Recursively normalizes the values in a dictionary, +converting strings to lowercase and stripping whitespace. +- normalize_list: Recursively normalizes the values in a lis...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/utils/dict_content_compare.py
Document functions with detailed explanations
import csv import json import xml.etree.ElementTree as ET from typing import Any, Dict, List def export_to_json(data: List[Dict[str, Any]], filename: str) -> None: with open(filename, "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=4) print(f"Data exported to {filename}") ...
--- +++ @@ -1,3 +1,7 @@+""" +data_export module +This module provides functions to export data to various file formats. +""" import csv import json @@ -6,12 +10,24 @@ def export_to_json(data: List[Dict[str, Any]], filename: str) -> None: + """ + Export data to a JSON file. + + :param data: List of dict...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/utils/data_export.py
Create documentation for each function signature
from typing import Union def prettify_exec_info( complete_result: list[dict], as_string: bool = True ) -> Union[str, list[dict]]: if not as_string: return complete_result if not complete_result: return "Empty result" # Format the table lines = [] lines.append("Node Statistic...
--- +++ @@ -1,3 +1,6 @@+""" +Prettify the execution information of the graph. +""" from typing import Union @@ -5,6 +8,18 @@ def prettify_exec_info( complete_result: list[dict], as_string: bool = True ) -> Union[str, list[dict]]: + """ + Formats the execution information of a graph showing node statist...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/utils/prettify_exec_info.py
Add clean documentation to messy code
from pathlib import Path from typing import Union def save_audio_from_bytes(byte_response: bytes, output_path: Union[str, Path]) -> None: if not isinstance(output_path, Path): output_path = Path(output_path) with open(output_path, "wb") as audio_file: audio_file.write(byte_response)
--- +++ @@ -1,12 +1,28 @@+""" +This utility function saves the byte response as an audio file. +""" from pathlib import Path from typing import Union def save_audio_from_bytes(byte_response: bytes, output_path: Union[str, Path]) -> None: + """ + Saves the byte response as an audio file to the specified p...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/utils/save_audio_from_bytes.py
Write clean docstrings for readability
import ipaddress import random import re from typing import List, Optional, Set, TypedDict from urllib.parse import urlparse import requests from fp.errors import FreeProxyException from fp.fp import FreeProxy class ProxyBrokerCriteria(TypedDict, total=False): anonymous: bool countryset: Set[str] secur...
--- +++ @@ -1,3 +1,6 @@+""" +Module for rotating proxies +""" import ipaddress import random @@ -11,6 +14,9 @@ class ProxyBrokerCriteria(TypedDict, total=False): + """ + proxy broker criteria + """ anonymous: bool countryset: Set[str] @@ -20,6 +26,9 @@ class ProxySettings(TypedDict, tot...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/utils/proxy_rotation.py
Generate docstrings for exported functions
from typing import Any, Dict, List import torch import torch_geometric x_map: Dict[str, List[Any]] = { 'atomic_num': list(range(0, 119)), 'chirality': [ 'CHI_UNSPECIFIED', 'CHI_TETRAHEDRAL_CW', 'CHI_TETRAHEDRAL_CCW', 'CHI_OTHER', 'CHI_TETRAHEDRAL', 'CHI_ALL...
--- +++ @@ -78,6 +78,12 @@ def from_rdmol(mol: Any) -> 'torch_geometric.data.Data': + r"""Converts a :class:`rdkit.Chem.Mol` instance to a + :class:`torch_geometric.data.Data` instance. + + Args: + mol (rdkit.Chem.Mol): The :class:`rdkit` molecule. + """ from rdkit import Chem from to...
https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/smiles.py
Write docstrings describing each step
from typing import Any, Callable, Dict, Type, Union from langchain_core.output_parsers import JsonOutputParser from pydantic import BaseModel as BaseModelV2 from pydantic.v1 import BaseModel as BaseModelV1 def get_structured_output_parser( schema: Union[Dict[str, Any], Type[BaseModelV1 | BaseModelV2], Type], ) ...
--- +++ @@ -1,3 +1,6 @@+""" +Functions to retrieve the correct output parser and format instructions for the LLM model. +""" from typing import Any, Callable, Dict, Type, Union @@ -9,6 +12,12 @@ def get_structured_output_parser( schema: Union[Dict[str, Any], Type[BaseModelV1 | BaseModelV2], Type], ) -> Calla...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/utils/output_parser.py
Provide clean and structured docstrings
import random import re import time from functools import wraps from typing import Dict, List, Optional, Union import requests from bs4 import BeautifulSoup from langchain_community.tools import DuckDuckGoSearchResults from pydantic import BaseModel, Field, validator class ResearchWebError(Exception): pass c...
--- +++ @@ -1,3 +1,7 @@+""" +research_web module for web searching across different search engines with improved +error handling, validation, and security features. +""" import random import re @@ -12,21 +16,25 @@ class ResearchWebError(Exception): + """Base exception for research web errors.""" pass ...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/utils/research_web.py
Write proper docstrings for these functions
import threading from contextlib import contextmanager from contextvars import ContextVar from typing import Any, Dict, List, Optional from langchain_core.callbacks import BaseCallbackHandler from langchain_core.messages import AIMessage from langchain_core.outputs import ChatGeneration, LLMResult from langchain_core...
--- +++ @@ -1,3 +1,9 @@+""" +Custom callback for LLM token usage statistics. + +This module has been taken and modified from the OpenAI callback manager in langchian-community. +https://github.com/langchain-ai/langchain/blob/master/libs/community/langchain_community/callbacks/openai_info.py +""" import threading fr...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/utils/custom_callback.py
Add docstrings to improve readability
from io import BytesIO import numpy as np from playwright.async_api import async_playwright async def take_screenshot(url: str, save_path: str = None, quality: int = 100): try: from PIL import Image except ImportError as e: raise ImportError( "The dependencies for screenshot scra...
--- +++ @@ -1,3 +1,6 @@+""" +screenshot_preparation module +""" from io import BytesIO @@ -6,6 +9,15 @@ async def take_screenshot(url: str, save_path: str = None, quality: int = 100): + """ + Takes a screenshot of a webpage at the specified URL and saves it if the save_path is specified. + Parameters:...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/utils/screenshot_scraping/screenshot_preparation.py
Document functions with clear intent
import tiktoken from ..logging import get_logger def num_tokens_openai(text: str) -> int: logger = get_logger() logger.debug(f"Counting tokens for text of {len(text)} characters") encoding = tiktoken.encoding_for_model("gpt-4o") num_tokens = len(encoding.encode(text)) return num_tokens
--- +++ @@ -1,3 +1,6 @@+""" +Tokenization utilities for OpenAI models +""" import tiktoken @@ -5,6 +8,16 @@ def num_tokens_openai(text: str) -> int: + """ + Estimate the number of tokens in a given text using OpenAI's tokenization method, + adjusted for different OpenAI models. + + Args: + t...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/utils/tokenizers/tokenizer_openai.py
Annotate my code with docstrings
import importlib.util import sys import typing if typing.TYPE_CHECKING: import types def srcfile_import(modpath: str, modname: str) -> "types.ModuleType": spec = importlib.util.spec_from_file_location(modname, modpath) if spec is None: message = f"missing spec for module at {modpath}" r...
--- +++ @@ -1,3 +1,8 @@+""" +high-level module for dynamic importing of python modules at runtime + +source code inspired by https://gist.github.com/DiTo97/46f4b733396b8d7a8f1d4d22db902cfc +""" import importlib.util import sys @@ -8,6 +13,19 @@ def srcfile_import(modpath: str, modname: str) -> "types.ModuleType...
https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/utils/sys_dynamic_import.py