instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Add structured docstrings to improve clarity | import copy
import functools
import json
import time
from collections import deque
from pathlib import Path
import tiktoken
import yaml
from pydantic import ValidationError
from extensions.openai.errors import InvalidRequestError
from extensions.openai.typing import ToolDefinition
from extensions.openai.utils import ... | --- +++ @@ -29,6 +29,7 @@
@functools.cache
def load_chat_template_file(filepath):
+ """Load a chat template from a file path (.jinja, .jinja2, or .yaml/.yml)."""
filepath = Path(filepath)
ext = filepath.suffix.lower()
text = filepath.read_text(encoding='utf-8')
@@ -39,6 +40,10 @@
def _get_raw_l... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/extensions/openai/completions.py |
Document this script properly | import os
import gradio as gr
# get the current directory of the script
current_dir = os.path.dirname(os.path.abspath(__file__))
# check if the bias_options.txt file exists, if not, create it
bias_file = os.path.join(current_dir, "bias_options.txt")
if not os.path.isfile(bias_file):
with open(bias_file, "w") as ... | --- +++ @@ -23,14 +23,26 @@
def input_modifier(string):
+ """
+ This function is applied to your text inputs before
+ they are fed into the model.
+ """
return string
def output_modifier(string):
+ """
+ This function is applied to the model outputs.
+ """
return string
def ... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/extensions/character_bias/script.py |
Provide clean and structured docstrings | import functools
import pprint
from pathlib import Path
import yaml
from modules import shared
from modules.loaders import loaders_samplers
from modules.logging_colors import logger
default_preset_values = {
'temperature': 1,
'dynatemp_low': 1,
'dynatemp_high': 1,
'dynatemp_exponent': 1,
'smooth... | --- +++ @@ -98,12 +98,14 @@
def reset_preset_for_ui(name, state):
+ """Reset current preset to its saved values from file"""
generate_params = load_preset(name, verbose=True)
state.update(generate_params)
return state, *[generate_params[k] for k in presets_params()]
def neutralize_samplers_fo... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/presets.py |
Add docstrings following best practices | import math
import re
import string
import nltk
import spacy
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from num2words import num2words
class TextPreprocessorBuilder:
# Define class variables as None initially
_stop_words = set(stopwords.words('english'))
_lemmatizer = Word... | --- +++ @@ -1,3 +1,16 @@+"""
+This module contains utils for preprocessing the text before converting it to embeddings.
+
+- TextPreprocessorBuilder preprocesses individual strings.
+ * lowering cases
+ * converting numbers to words or characters
+ * merging and stripping spaces
+ * removing punctuation
+ ... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/extensions/superboogav2/data_preprocessor.py |
Create simple docstrings for beginners | import json
import random
import re
def get_tool_call_id() -> str:
letter_bytes = "abcdefghijklmnopqrstuvwxyz0123456789"
b = [random.choice(letter_bytes) for _ in range(8)]
return "call_" + "".join(b).lower()
# All known opening markers for tool calls across model formats.
TOOL_CALL_OPENING_MARKERS = [
... | --- +++ @@ -25,6 +25,18 @@
def streaming_tool_buffer_check(text, markers=None, tool_names=None, check_bare_names=False):
+ '''
+ Check whether streaming output should be withheld because it may
+ contain tool-call markup.
+
+ Args:
+ text: Full accumulated internal text.
+ markers: Templat... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/tool_parsing.py |
Add docstrings to make code maintainable | import functools
import json
import re
from math import floor
from pathlib import Path
import yaml
from modules import loaders, metadata_gguf, shared
from modules.logging_colors import logger
from modules.utils import resolve_model_path
def get_fallback_settings():
return {
'bf16': False,
'ctx_s... | --- +++ @@ -202,6 +202,9 @@
def update_model_parameters(state, initial=False):
+ '''
+ UI: update the command-line arguments based on the interface values
+ '''
elements = loaders.list_model_elements() # the names of the parameters
for i, element in enumerate(elements):
@@ -219,6 +222,9 @@
... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/models_settings.py |
Document functions with clear intent |
import math
import torch
from transformers.generation.logits_process import LogitsProcessor
from transformers.utils import add_start_docstrings
LOGITS_PROCESSOR_INPUTS_DOCSTRING = r"""
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tok... | --- +++ @@ -1,3 +1,12 @@+'''
+This file has been 100% copied from this PR to the Transformers library:
+https://github.com/huggingface/transformers/pull/27557
+
+Author: Saibo-creator
+Author GitHub: https://github.com/Saibo-creator
+
+All credits go to the author.
+'''
import math
@@ -36,6 +45,12 @@
# TODO:... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/grammar/logits_process.py |
Generate consistent documentation across files | import time
import html
import functools
import re
import gradio
import numpy as np
import torch
from transformers import LogitsProcessor
import colorsys
from modules import html_generator, shared
params = {
'active': True,
'color_by_perplexity': False,
'color_by_probability': False,
'ppl_scale': 15... | --- +++ @@ -198,6 +198,9 @@
def probability_color_scale(prob):
+ '''
+ Green-yellow-red color scale
+ '''
# hue (0.0 = red, 0.33 = green)
# saturation (0.0 = gray / white, 1.0 = normal, just leave at 1.0)
# brightness (0.0 = black, 1.0 = brightest, use something in between for better readabi... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/extensions/perplexity_colors/script.py |
Provide clean and structured docstrings | import argparse
import glob
import hashlib
import json
import os
import platform
import re
import signal
import site
import subprocess
import sys
# Define the required versions
TORCH_VERSION = "2.9.1"
PYTHON_VERSION = "3.13"
LIBSTDCXX_VERSION_LINUX = "12.1.0"
# Environment
script_dir = os.getcwd()
conda_env_path = os... | --- +++ @@ -61,6 +61,7 @@
def load_state():
+ """Load installer state from JSON file"""
if os.path.exists(state_file):
try:
with open(state_file, 'r') as f:
@@ -71,11 +72,13 @@
def save_state(state):
+ """Save installer state to JSON file"""
with open(state_file, 'w') as f:... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/one_click.py |
Add docstrings explaining edge cases | import base64
import copy
import functools
import html
import json
import pprint
import re
import shutil
import threading
import time
from datetime import datetime
from functools import partial
from pathlib import Path
import markupsafe
import yaml
from jinja2.ext import loopcontrols
from jinja2.sandbox import Immutab... | --- +++ @@ -52,10 +52,20 @@
def get_current_timestamp():
+ """Returns the current time in 24-hour format"""
return datetime.now().strftime('%b %d, %Y %H:%M')
def update_message_metadata(metadata_dict, role, index, **fields):
+ """
+ Updates or adds metadata fields for a specific message.
+
+ A... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/chat.py |
Add missing documentation to my Python functions |
import logging
import re
import time
from abc import ABC
from functools import lru_cache
from typing import Dict, List
import torch
from modules import shared
logger = logging.getLogger(__name__)
########################
# EBNF Grammar Parsing #
########################
END_OF_ALTERNATE_MARKER = 0
END_OF_RULE_MA... | --- +++ @@ -1,3 +1,12 @@+'''
+This file has been 100% copied from this PR to the Transformers library:
+https://github.com/huggingface/transformers/pull/27557
+
+Author: Saibo-creator
+Author GitHub: https://github.com/Saibo-creator
+
+All credits go to the author.
+'''
import logging
import re
@@ -55,6 +64,21 @@
... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/grammar/grammar_utils.py |
Add structured docstrings to improve clarity | import torch
from modules import chat, shared
from modules.text_generation import (
decode,
encode,
generate_reply,
)
from transformers import LogitsProcessor
import gradio as gr
params = {
"display_name": "Long replies",
"is_tab": False,
"min_length": 120,
}
initial_size = 0
class MyLogits(L... | --- +++ @@ -17,6 +17,10 @@ initial_size = 0
class MyLogits(LogitsProcessor):
+ """
+ Manipulates the probabilities for the next token before it gets sampled.
+ Used in the logits_processor_modifier function below.
+ """
def __init__(self):
self.newline_id = shared.tokenizer.encode('\n')[-1]... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/extensions/long_replies/script.py |
Add docstrings to incomplete code | import asyncio
import json
import logging
import os
import socket
import threading
import traceback
from collections import deque
from threading import Thread
import uvicorn
from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.requests import Reque... | --- +++ @@ -61,6 +61,7 @@
async def _wait_for_disconnect(request: Request, stop_event: threading.Event):
+ """Block until the client disconnects, then signal the stop_event."""
while True:
message = await request.receive()
if message["type"] == "http.disconnect":
@@ -234,6 +235,9 @@
@app... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/extensions/openai/script.py |
Write docstrings for backend logic | import threading
import time
from pathlib import Path
import gradio as gr
from modules import logits, shared, ui, utils
from modules.prompts import count_tokens, load_prompt
from modules.text_generation import (
generate_reply_wrapper,
get_token_ids,
stop_everything_event
)
from modules.utils import gradi... | --- +++ @@ -169,6 +169,7 @@
def generate_and_save_wrapper_notebook(textbox_content, interface_state, prompt_name):
+ """Generate reply and automatically save the result for notebook mode with periodic saves"""
last_save_time = time.monotonic()
save_interval = 8
output = textbox_content
@@ -247,6 +... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/ui_notebook.py |
Write proper docstrings for these functions | import json
import math
import pprint
import random
import torch
import transformers
from transformers.generation.logits_process import (
LogitNormalization,
LogitsProcessor,
LogitsProcessorList
)
from modules import shared
from modules.logging_colors import logger
from modules.torch_utils import get_devi... | --- +++ @@ -22,6 +22,9 @@
class TemperatureLogitsWarperCustom(LogitsProcessor):
+ '''
+ A copy of the original Transformers temperature logits warper.
+ '''
def __init__(self, temperature: float):
if not isinstance(temperature, float) or not (temperature > 0):
@@ -42,6 +45,9 @@
class Dy... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/sampler_hijack.py |
Write docstrings describing each step | import datetime
import functools
import html
import os
import re
import time
from pathlib import Path
import markdown
from PIL import Image, ImageOps
from modules import shared
from modules.reasoning import extract_reasoning
from modules.sane_markdown_lists import SaneListExtension
from modules.utils import get_avail... | --- +++ @@ -110,11 +110,13 @@
def extract_thinking_block(string):
+ """Extract thinking blocks from the beginning of an HTML-escaped string."""
return extract_reasoning(string, html_escaped=True)
def build_tool_call_block(header, body, message_id, index):
+ """Build HTML for a tool call accordion ... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/html_generator.py |
Generate consistent docstrings | import importlib.util
import json
from modules import shared
from modules.logging_colors import logger
from modules.utils import natural_keys, sanitize_filename
def get_available_tools():
tools_dir = shared.user_data_dir / 'tools'
tools_dir.mkdir(parents=True, exist_ok=True)
return sorted((p.stem for p i... | --- +++ @@ -7,12 +7,19 @@
def get_available_tools():
+ """Return sorted list of tool script names from user_data/tools/*.py."""
tools_dir = shared.user_data_dir / 'tools'
tools_dir.mkdir(parents=True, exist_ok=True)
return sorted((p.stem for p in tools_dir.glob('*.py')), key=natural_keys)
def... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/tool_use.py |
Write clean docstrings for readability | import os
import re
from datetime import datetime
from pathlib import Path
from modules import shared
from modules.logging_colors import logger
# Helper function to get multiple values from shared.gradio
def gradio(*keys):
if len(keys) == 1 and type(keys[0]) in [list, tuple]:
keys = keys[0]
return [... | --- +++ @@ -16,12 +16,18 @@
def sanitize_filename(name):
+ """Strip path traversal components from a filename.
+
+ Returns only the final path component with leading dots removed,
+ preventing directory traversal via '../' or absolute paths.
+ """
name = Path(name).name # drop all directory compon... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/utils.py |
Add return value explanations in docstrings |
import base64
import io
import time
from extensions.openai.errors import ServiceUnavailableError
from modules import shared
def generations(request):
from modules.ui_image_generation import generate
if shared.image_model is None:
raise ServiceUnavailableError("No image model loaded. Load a model vi... | --- +++ @@ -1,3 +1,6 @@+"""
+OpenAI-compatible image generation using local diffusion models.
+"""
import base64
import io
@@ -8,6 +11,10 @@
def generations(request):
+ """
+ Generate images using the loaded diffusion model.
+ Returns dict with 'created' timestamp and 'data' list of images.
+ """
... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/extensions/openai/images.py |
Include argument descriptions in docstrings | import json
import os
import random
import time
import traceback
from datetime import datetime
from pathlib import Path
import gradio as gr
from PIL.PngImagePlugin import PngInfo
from modules import shared, ui, utils
from modules.image_models import (
get_pipeline_type,
load_image_model,
unload_image_mode... | --- +++ @@ -118,6 +118,7 @@
def build_generation_metadata(state, actual_seed):
+ """Build metadata dict from generation settings."""
metadata = {}
for key in METADATA_SETTINGS_KEYS:
if key in state:
@@ -132,6 +133,7 @@
def save_generated_images(images, state, actual_seed):
+ """Save ima... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/ui_image_generation.py |
Insert docstrings into my code | import argparse
import copy
import os
import shlex
import sys
from collections import OrderedDict
from pathlib import Path
import yaml
from modules.logging_colors import logger
from modules.paths import resolve_user_data_dir
from modules.presets import default_preset, default_preset_values
# Resolve user_data direct... | --- +++ @@ -403,6 +403,7 @@
def apply_image_model_cli_overrides():
+ """Apply command-line overrides for image model settings."""
if args.image_model is not None:
settings['image_model_menu'] = args.image_model
if args.image_dtype is not None:
@@ -449,6 +450,9 @@
def load_user_config():
+ ... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/shared.py |
Document this script properly | import concurrent.futures
import html
import ipaddress
import random
import re
import socket
from concurrent.futures import as_completed
from datetime import datetime
from urllib.parse import parse_qs, quote_plus, urljoin, urlparse
import requests
from modules import shared
from modules.logging_colors import logger
... | --- +++ @@ -15,6 +15,7 @@
def _validate_url(url):
+ """Validate that a URL is safe to fetch (not targeting private/internal networks)."""
parsed = urlparse(url)
if parsed.scheme not in ('http', 'https'):
raise ValueError(f"Unsupported URL scheme: {parsed.scheme}")
@@ -34,10 +35,14 @@
def g... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/web_search.py |
Create documentation for each function signature | import os
os.environ["WANDB_MODE"] = "offline"
# os.environ["WANDB_DISABLED"] = "true"
import json
import math
import random
import shutil
import sys
import threading
import time
import traceback
from datetime import datetime
from pathlib import Path
import yaml
import gradio as gr
from modules import shared, ui, u... | --- +++ @@ -215,6 +215,7 @@
def clean_path(base_path: str, path: str):
+ """Strips unusual symbols and forcibly builds a path as relative to the intended directory."""
path = path.replace('\\', '/').replace('..', '_')
if base_path is None:
return path
@@ -232,6 +233,7 @@
def load_template(... | https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/training.py |
Include argument descriptions in docstrings | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/api/main.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用者应遵守以下原则:
# 1... | --- +++ @@ -16,6 +16,11 @@ # 详细许可条款请参阅项目根目录下的LICENSE文件。
# 使用本代码即表示您同意遵守上述原则和LICENSE中的所有条款。
+"""
+MediaCrawler WebUI API Server
+Start command: uvicorn api.main:app --port 8080 --reload
+Or: python -m api.main
+"""
import asyncio
import os
import subprocess
@@ -58,6 +63,7 @@
@app.get("/")
async def serve_fronte... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/api/main.py |
Add docstrings for production code | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/database/db.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用者应遵守以下原则:
... | --- +++ @@ -33,6 +33,12 @@ from database.db_session import create_tables
async def init_table_schema(db_type: str):
+ """
+ Initializes the database table schema.
+ This will create tables based on the ORM models.
+ Args:
+ db_type: The type of database, 'sqlite' or 'mysql'.
+ """
utils.lo... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/database/db.py |
Add docstrings including usage examples | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/xhs/xhs_sign.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目... | --- +++ @@ -77,12 +77,14 @@
def _right_shift_unsigned(num: int, bit: int = 0) -> int:
+ """Python implementation of JavaScript unsigned right shift (>>>)"""
val = ctypes.c_uint32(num).value >> bit
MAX32INT = 4294967295
return (val + (MAX32INT + 1)) % (2 * (MAX32INT + 1)) - MAX32INT - 1
def mr... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/xhs/xhs_sign.py |
Add verbose docstrings with examples | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/api/services/crawler_manager.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究... | --- +++ @@ -28,6 +28,7 @@
class CrawlerManager:
+ """Crawler process manager"""
def __init__(self):
self._lock = asyncio.Lock()
@@ -48,11 +49,13 @@ return self._logs
def get_log_queue(self) -> asyncio.Queue:
+ """Get or create log queue"""
if self._log_queue is None... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/api/services/crawler_manager.py |
Generate docstrings with examples | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/base/base_crawler.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用者应遵... | --- +++ @@ -27,17 +27,39 @@
@abstractmethod
async def start(self):
+ """
+ start crawler
+ """
pass
@abstractmethod
async def search(self):
+ """
+ search
+ """
pass
@abstractmethod
async def launch_browser(self, chromium: Br... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/base/base_crawler.py |
Add docstrings to my Python code | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/tieba/client.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究... | --- +++ @@ -59,6 +59,17 @@ self.playwright_page = playwright_page # Playwright page object
def _sync_request(self, method, url, proxy=None, **kwargs):
+ """
+ Synchronous requests method
+ Args:
+ method: Request method
+ url: Request URL
+ proxy: Pr... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/tieba/client.py |
Add docstrings to my Python code | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/douyin/login.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究... | --- +++ @@ -51,6 +51,10 @@ self.cookie_str = cookie_str
async def begin(self):
+ """
+ Start login douyin website
+ The verification accuracy of the slider verification is not very good... If there are no special requirements, it is recommended not to use Douyin login, or use... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/douyin/login.py |
Write reusable docstrings | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/xhs/core.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用... | --- +++ @@ -123,6 +123,7 @@ utils.logger.info("[XiaoHongShuCrawler.start] Xhs Crawler finished ...")
async def search(self) -> None:
+ """Search for notes and retrieve their comment information."""
utils.logger.info("[XiaoHongShuCrawler.search] Begin search Xiaohongshu keywords")
... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/xhs/core.py |
Add detailed docstrings explaining each function | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/weibo/core.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的... | --- +++ @@ -134,6 +134,10 @@ utils.logger.info("[WeiboCrawler.start] Weibo Crawler finished ...")
async def search(self):
+ """
+ search weibo note with keywords
+ :return:
+ """
utils.logger.info("[WeiboCrawler.search] Begin search weibo keywords")
weibo... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/weibo/core.py |
Create documentation strings for testing functions | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/douyin/client.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研... | --- +++ @@ -127,6 +127,9 @@ raise DataFetchError(f"{e}, {response.text}")
async def get(self, uri: str, params: Optional[Dict] = None, headers: Optional[Dict] = None):
+ """
+ GET请求
+ """
await self.__process_req_params(uri, params, headers)
headers = headers or... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/douyin/client.py |
Add docstrings that explain inputs and outputs | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/kuaishou/help.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研... | --- +++ @@ -25,6 +25,17 @@
def parse_video_info_from_url(url: str) -> VideoUrlInfo:
+ """
+ Parse video ID from Kuaishou video URL
+ Supports the following formats:
+ 1. Full video URL: "https://www.kuaishou.com/short-video/3x3zxz4mjrsc8ke?authorId=3x84qugg4ch9zhs&streamSource=search"
+ 2. Pure video... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/kuaishou/help.py |
Add docstrings to meet PEP guidelines | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/bilibili/core.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研... | --- +++ @@ -130,6 +130,9 @@ utils.logger.info("[BilibiliCrawler.start] Bilibili Crawler finished ...")
async def search(self):
+ """
+ search bilibili video
+ """
# Search for video and retrieve their comment information.
if config.BILI_SEARCH_MODE == "normal":
... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/bilibili/core.py |
Please document this code using docstrings | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/tieba/core.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的... | --- +++ @@ -59,6 +59,11 @@ self.cdp_manager = None
async def start(self) -> None:
+ """
+ Start the crawler
+ Returns:
+
+ """
playwright_proxy_format, httpx_proxy_format = None, None
if config.ENABLE_IP_PROXY:
utils.logger.info(
@@ -137,6 +142,1... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/tieba/core.py |
Add missing documentation to my Python functions | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/database/mongodb_store_base.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目... | --- +++ @@ -16,6 +16,7 @@ # 详细许可条款请参阅项目根目录下的LICENSE文件。
# 使用本代码即表示您同意遵守上述原则和LICENSE中的所有条款。
+"""MongoDB storage base class: Provides connection management and common storage methods"""
import asyncio
from typing import Dict, List, Optional
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase, As... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/database/mongodb_store_base.py |
Write docstrings for backend logic | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/bilibili/client.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习... | --- +++ @@ -81,12 +81,23 @@ return data.get("data", {})
async def pre_request_data(self, req_data: Dict) -> Dict:
+ """
+ Send request to sign request parameters
+ Need to get wbi_img_urls parameter from localStorage, value as follows:
+ https://i0.hdslb.com/bfs/wbi/7cd084... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/bilibili/client.py |
Create docstrings for reusable components | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/zhihu/core.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的... | --- +++ @@ -64,6 +64,11 @@ self.ip_proxy_pool = None # Proxy IP pool for automatic proxy refresh
async def start(self) -> None:
+ """
+ Start the crawler
+ Returns:
+
+ """
playwright_proxy_format, httpx_proxy_format = None, None
if config.ENABLE_IP_PROXY:
... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/zhihu/core.py |
Add concise docstrings to each method | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/kuaishou/client.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习... | --- +++ @@ -88,6 +88,12 @@ )
async def request_rest_v2(self, uri: str, data: dict) -> Dict:
+ """
+ Make REST API V2 request (for comment endpoints)
+ :param uri: API endpoint path
+ :param data: request body
+ :return: response data
+ """
await self._re... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/kuaishou/client.py |
Add professional docstrings to my codebase | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/bilibili/help.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研... | --- +++ @@ -44,6 +44,10 @@ ]
def get_salt(self) -> str:
+ """
+ Get the salted key
+ :return:
+ """
salt = ""
mixin_key = self.img_key + self.sub_key
for mt in self.map_table:
@@ -51,6 +55,12 @@ return salt[:32]
def sign(self, req_data... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/bilibili/help.py |
Add detailed documentation for each class | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/xhs/exception.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研... | --- +++ @@ -22,9 +22,12 @@
class DataFetchError(RequestError):
+ """something error when fetch"""
class IPBlockError(RequestError):
+ """fetch so fast that the server block us ip"""
-class NoteNotFoundError(RequestError):+class NoteNotFoundError(RequestError):
+ """Note does not exist or is abnorm... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/xhs/exception.py |
Create documentation for each function signature | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/weibo/login.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目... | --- +++ @@ -53,6 +53,7 @@ self.weibo_sso_login_url = "https://passport.weibo.com/sso/signin?entry=miniblog&source=miniblog"
async def begin(self):
+ """Start login weibo"""
utils.logger.info("[WeiboLogin.begin] Begin login weibo ...")
if config.LOGIN_TYPE == "qrcode":
... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/weibo/login.py |
Add professional docstrings to my codebase | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/xhs/playwright_sign.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅... | --- +++ @@ -30,6 +30,16 @@
def _build_sign_string(uri: str, data: Optional[Union[Dict, str]] = None, method: str = "POST") -> str:
+ """Build string to be signed
+
+ Args:
+ uri: API path
+ data: Request data
+ method: Request method (GET or POST)
+
+ Returns:
+ String to be sig... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/xhs/playwright_sign.py |
Document classes and their methods | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/zhihu/client.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究... | --- +++ @@ -64,6 +64,13 @@ self.init_proxy_pool(proxy_ip_pool)
async def _pre_headers(self, url: str) -> Dict:
+ """
+ Sign request headers
+ Args:
+ url: Request URL with query parameters
+ Returns:
+
+ """
d_c0 = self.cookie_dict.get("d_c0")
... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/zhihu/client.py |
Document all endpoints with docstrings | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/cache/abs_cache.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用者应遵守以... | --- +++ @@ -32,12 +32,31 @@
@abstractmethod
def get(self, key: str) -> Optional[Any]:
+ """
+ Get the value of a key from the cache.
+ This is an abstract method. Subclasses must implement this method.
+ :param key: The key
+ :return:
+ """
raise NotImplemen... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/cache/abs_cache.py |
Write docstrings that follow conventions | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/kuaishou/core.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研... | --- +++ @@ -181,6 +181,7 @@ await self.batch_get_video_comments(video_id_list)
async def get_specified_videos(self):
+ """Get the information and comments of the specified post"""
utils.logger.info("[KuaishouCrawler.get_specified_videos] Parsing video URLs...")
video_ids ... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/kuaishou/core.py |
Add docstrings for production code | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/cache/local_cache.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用者应遵... | --- +++ @@ -34,6 +34,11 @@ class ExpiringLocalCache(AbstractCache):
def __init__(self, cron_interval: int = 10):
+ """
+ Initialize local cache
+ :param cron_interval: Time interval for scheduled cache cleanup
+ :return:
+ """
self._cron_interval = cron_interval
... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/cache/local_cache.py |
Add docstrings to incomplete code | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/tieba/login.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目... | --- +++ @@ -49,6 +49,12 @@
@retry(stop=stop_after_attempt(600), wait=wait_fixed(1), retry=retry_if_result(lambda value: value is False))
async def check_login_state(self) -> bool:
+ """
+ Poll to check if login status is successful, return True if successful, otherwise return False
+
+ R... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/tieba/login.py |
Document all endpoints with docstrings | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/douyin/help.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目... | --- +++ @@ -37,6 +37,11 @@ douyin_sign_obj = execjs.compile(open('libs/douyin.js', encoding='utf-8-sig').read())
def get_web_id():
+ """
+ Generate random webid
+ Returns:
+
+ """
def e(t):
if t is not None:
@@ -54,9 +59,22 @@
async def get_a_bogus(url: str, params: str, post_data: di... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/douyin/help.py |
Add docstrings for internal functions | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/tieba/help.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的... | --- +++ @@ -41,6 +41,14 @@
@staticmethod
def extract_search_note_list(page_content: str) -> List[TiebaNote]:
+ """
+ Extract Tieba post list from keyword search result pages, still missing reply count and reply page data
+ Args:
+ page_content: HTML string of page content
+
+ ... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/tieba/help.py |
Improve my code by adding docstrings | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/xhs/help.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用... | --- +++ @@ -29,6 +29,9 @@
def sign(a1="", b1="", x_s="", x_t=""):
+ """
+ takes in a URI (uniform resource identifier), an optional data dictionary, and an optional ctime parameter. It returns a dictionary containing two keys: "x-s" and "x-t".
+ """
common = {
"s0": 3, # getPlatformCode
... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/xhs/help.py |
Add inline docstrings for readability | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/xhs/login.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使... | --- +++ @@ -50,6 +50,9 @@
@retry(stop=stop_after_attempt(600), wait=wait_fixed(1), retry=retry_if_result(lambda value: value is False))
async def check_login_state(self, no_logged_in_session: str) -> bool:
+ """
+ Verify login status using dual-check: UI elements and Cookies.
+ """
... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/xhs/login.py |
Add docstrings to clarify complex logic | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/bilibili/login.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和... | --- +++ @@ -52,6 +52,7 @@ self.cookie_str = cookie_str
async def begin(self):
+ """Start login bilibili"""
utils.logger.info("[BilibiliLogin.begin] Begin login Bilibili ...")
if config.LOGIN_TYPE == "qrcode":
await self.login_by_qrcode()
@@ -65,6 +66,11 @@
@ret... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/bilibili/login.py |
Document all public functions with docstrings | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/xhs/client.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的... | --- +++ @@ -70,6 +70,16 @@ self.init_proxy_pool(proxy_ip_pool)
async def _pre_headers(self, url: str, params: Optional[Dict] = None, payload: Optional[Dict] = None) -> Dict:
+ """Request header parameter signing (using playwright injection method)
+
+ Args:
+ url: Request URL
+ ... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/xhs/client.py |
Create simple docstrings for beginners | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/zhihu/help.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的... | --- +++ @@ -35,6 +35,15 @@
def sign(url: str, cookies: str) -> Dict:
+ """
+ zhihu sign algorithm
+ Args:
+ url: request url with query string
+ cookies: request cookies with d_c0 key
+
+ Returns:
+
+ """
global ZHIHU_SGIN_JS
if not ZHIHU_SGIN_JS:
with open("libs/zhih... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/zhihu/help.py |
Generate helpful docstrings for debugging | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/api/routers/websocket.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用... | --- +++ @@ -27,6 +27,7 @@
class ConnectionManager:
+ """WebSocket connection manager"""
def __init__(self):
self.active_connections: Set[WebSocket] = set()
@@ -39,6 +40,7 @@ self.active_connections.discard(websocket)
async def broadcast(self, message: dict):
+ """Broadcast m... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/api/routers/websocket.py |
Write docstrings that follow conventions | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/zhihu/login.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目... | --- +++ @@ -50,6 +50,11 @@
@retry(stop=stop_after_attempt(600), wait=wait_fixed(1), retry=retry_if_result(lambda value: value is False))
async def check_login_state(self) -> bool:
+ """
+ Check if the current login status is successful and return True otherwise return False
+ Returns:
+
... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/zhihu/login.py |
Write reusable docstrings | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/kuaishou/login.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和... | --- +++ @@ -47,6 +47,7 @@ self.cookie_str = cookie_str
async def begin(self):
+ """Start login xiaohongshu"""
utils.logger.info("[KuaishouLogin.begin] Begin login kuaishou ...")
if config.LOGIN_TYPE == "qrcode":
await self.login_by_qrcode()
@@ -59,6 +60,11 @@
@... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/kuaishou/login.py |
Provide docstrings following PEP 257 | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/cmd_arg/arg.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用者应遵守以下原则:... | --- +++ @@ -37,6 +37,7 @@
class PlatformEnum(str, Enum):
+ """Supported media platform enumeration"""
XHS = "xhs"
DOUYIN = "dy"
@@ -48,6 +49,7 @@
class LoginTypeEnum(str, Enum):
+ """Login type enumeration"""
QRCODE = "qrcode"
PHONE = "phone"
@@ -55,6 +57,7 @@
class CrawlerType... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/cmd_arg/arg.py |
Add docstrings that explain inputs and outputs | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/douyin/core.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目... | --- +++ @@ -171,6 +171,7 @@ utils.logger.info(f"[DouYinCrawler.search] keyword:{keyword}, aweme_list:{aweme_list}")
async def get_specified_awemes(self):
+ """Get the information and comments of the specified post from URLs or IDs"""
utils.logger.info("[DouYinCrawler.get_specified_awe... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/douyin/core.py |
Add concise docstrings to each method | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/cache/redis_cache.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用者应遵... | --- +++ @@ -42,6 +42,10 @@
@staticmethod
def _connet_redis() -> Redis:
+ """
+ Connect to redis, return redis client, configure redis connection information as needed
+ :return:
+ """
return Redis(
host=db_config.REDIS_DB_HOST,
port=db_config.RED... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/cache/redis_cache.py |
Add docstrings for better understanding | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/xhs/extractor.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研... | --- +++ @@ -29,6 +29,14 @@ pass
def extract_note_detail_from_html(self, note_id: str, html: str) -> Optional[Dict]:
+ """Extract note details from HTML
+
+ Args:
+ html (str): HTML string
+
+ Returns:
+ Dict: Note details dictionary
+ """
if "not... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/xhs/extractor.py |
Add docstrings to incomplete code | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/media_platform/weibo/client.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究... | --- +++ @@ -114,6 +114,7 @@ return await self.request(method="POST", url=f"{self._host}{uri}", data=json_str, headers=self.headers)
async def pong(self) -> bool:
+ """get a note to check if login state is ok"""
utils.logger.info("[WeiboClient.pong] Begin pong weibo...")
ping_flag... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/media_platform/weibo/client.py |
Generate documentation strings for clarity | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/store/xhs/xhs_store_media.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的... | --- +++ @@ -39,12 +39,42 @@ self.image_store_path = "data/xhs/images"
async def store_image(self, image_content_item: Dict):
+ """
+ store content
+
+ Args:
+ image_content_item:
+
+ Returns:
+
+ """
await self.save_image(image_content_item.get("... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/store/xhs/xhs_store_media.py |
Turn comments into proper docstrings | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/store/zhihu/_store_impl.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用... | --- +++ @@ -43,6 +43,12 @@ from database.mongodb_store_base import MongoDBStoreBase
def calculate_number_of_files(file_store_path: str) -> int:
+ """Calculate the prefix sorting number for data save files, supporting writing to different files for each run
+ Args:
+ file_store_path;
+ Returns:
+ ... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/store/zhihu/_store_impl.py |
Add docstrings to improve readability | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/store/xhs/__init__.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用者应... | --- +++ @@ -51,6 +51,14 @@
def get_video_url_arr(note_item: Dict) -> List:
+ """
+ Get video url array
+ Args:
+ note_item:
+
+ Returns:
+
+ """
if note_item.get('type') != 'video':
return []
@@ -77,6 +85,14 @@
async def update_xhs_note(note_item: Dict):
+ """
+ Updat... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/store/xhs/__init__.py |
Add docstrings to improve readability | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/store/xhs/_store_impl.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用... | --- +++ @@ -45,9 +45,19 @@ self.writer = AsyncFileWriter(platform="xhs", crawler_type=crawler_type_var.get())
async def store_content(self, content_item: Dict):
+ """
+ store content data to csv file
+ :param content_item:
+ :return:
+ """
await self.writer.wri... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/store/xhs/_store_impl.py |
Add docstrings to incomplete code | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/store/tieba/_store_impl.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用... | --- +++ @@ -44,6 +44,12 @@
def calculate_number_of_files(file_store_path: str) -> int:
+ """Calculate the prefix sorting number for data save files, supporting writing to different files for each run
+ Args:
+ file_store_path;
+ Returns:
+ file nums
+ """
if not os.path.exists(file_st... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/store/tieba/_store_impl.py |
Add well-formatted docstrings | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/store/weibo/__init__.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用... | --- +++ @@ -52,6 +52,14 @@
async def batch_update_weibo_notes(note_list: List[Dict]):
+ """
+ Batch update weibo notes
+ Args:
+ note_list:
+
+ Returns:
+
+ """
if not note_list:
return
for note_item in note_list:
@@ -59,6 +67,14 @@
async def update_weibo_note(note_item:... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/store/weibo/__init__.py |
Write beginner-friendly docstrings | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/store/weibo/_store_impl.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用... | --- +++ @@ -44,6 +44,12 @@
def calculate_number_of_files(file_store_path: str) -> int:
+ """Calculate the prefix sorting number for data save files, supporting writing to different files for each run
+ Args:
+ file_store_path;
+ Returns:
+ file nums
+ """
if not os.path.exists(file_st... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/store/weibo/_store_impl.py |
Write docstrings for backend logic | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/proxy/providers/wandou_http_proxy.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅... | --- +++ @@ -35,6 +35,11 @@ class WanDouHttpProxy(ProxyProvider):
def __init__(self, app_key: str, num: int = 100):
+ """
+ WanDou HTTP proxy IP implementation
+ :param app_key: Open app_key, can be obtained through user center
+ :param num: Number of IPs extracted at once, maximum 100... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/proxy/providers/wandou_http_proxy.py |
Add minimal docstrings for each function | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/store/weibo/weibo_store_media.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和... | --- +++ @@ -39,14 +39,44 @@ self.image_store_path = "data/weibo/images"
async def store_image(self, image_content_item: Dict):
+ """
+ store content
+
+ Args:
+ image_content_item:
+
+ Returns:
+
+ """
await self.save_image(image_content_item.get... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/store/weibo/weibo_store_media.py |
Add concise docstrings to each method | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/proxy/providers/kuaidl_proxy.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研... | --- +++ @@ -44,6 +44,14 @@
def parse_kuaidaili_proxy(proxy_info: str) -> KuaidailiProxyModel:
+ """
+ Parse KuaiDaili IP information
+ Args:
+ proxy_info:
+
+ Returns:
+
+ """
proxies: List[str] = proxy_info.split(":")
if len(proxies) != 2:
raise Exception("not invalid kuaid... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/proxy/providers/kuaidl_proxy.py |
Improve documentation using docstrings | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/store/zhihu/__init__.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用... | --- +++ @@ -55,6 +55,14 @@ return store_class()
async def batch_update_zhihu_contents(contents: List[ZhihuContent]):
+ """
+ Batch update Zhihu contents
+ Args:
+ contents:
+
+ Returns:
+
+ """
if not contents:
return
@@ -62,6 +70,14 @@ await update_zhihu_content... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/store/zhihu/__init__.py |
Write docstrings describing each step | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用者应遵守以下原则:
# 1. 不得用于任何商业用途。
# 2. 使用... | --- +++ @@ -32,13 +32,33 @@
class ProxyRefreshMixin:
+ """
+ Auto-refresh proxy Mixin class
+
+ Usage:
+ 1. Let client class inherit this Mixin
+ 2. Call init_proxy_pool(proxy_ip_pool) in client's __init__
+ 3. Call await _refresh_proxy_if_expired() before each request method call
+
+ Requireme... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/proxy/proxy_mixin.py |
Generate docstrings for exported functions | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/proxy/providers/jishu_http_proxy.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供... | --- +++ @@ -35,6 +35,11 @@ class JiSuHttpProxy(ProxyProvider):
def __init__(self, key: str, crypto: str, time_validity_period: int):
+ """
+ JiSu HTTP proxy IP implementation
+ :param key: Extraction key value (obtain after registering on the official website)
+ :param crypto: Encrypt... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/proxy/providers/jishu_http_proxy.py |
Help me add docstrings to my project | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/proxy/base_proxy.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用者应遵守... | --- +++ @@ -36,11 +36,17 @@
class IpGetError(Exception):
+ """ ip get error"""
class ProxyProvider(ABC):
@abstractmethod
async def get_proxy(self, num: int) -> List[IpInfoModel]:
+ """
+ Abstract method to get IP, different HTTP proxy providers need to implement this method
+ ... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/proxy/base_proxy.py |
Generate consistent docstrings | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/proxy/proxy_ip_pool.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用者... | --- +++ @@ -43,6 +43,13 @@ def __init__(
self, ip_pool_count: int, enable_validate_ip: bool, ip_provider: ProxyProvider
) -> None:
+ """
+
+ Args:
+ ip_pool_count:
+ enable_validate_ip:
+ ip_provider:
+ """
self.valid_ip_url = "https://ech... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/proxy/proxy_ip_pool.py |
Document functions with clear intent | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/tools/file_header_manager.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使... | --- +++ @@ -16,6 +16,15 @@ # 详细许可条款请参阅项目根目录下的LICENSE文件。
# 使用本代码即表示您同意遵守上述原则和LICENSE中的所有条款。
+"""
+File header copyright declaration management tool
+
+Features:
+- Automatically add standardized copyright declaration and disclaimer to Python files
+- Intelligently detect existing file headers (encoding declaration, a... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/tools/file_header_manager.py |
Generate NumPy-style docstrings | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/tools/time_util.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用者应遵守以... | --- +++ @@ -28,32 +28,63 @@
def get_current_timestamp() -> int:
+ """
+ Get current timestamp (13 digits): 1701493264496
+ :return:
+ """
return int(time.time() * 1000)
def get_current_time() -> str:
+ """
+ Get current time: '2023-12-02 13:01:23'
+ :return:
+ """
return time.... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/tools/time_util.py |
Generate NumPy-style docstrings | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/store/kuaishou/_store_impl.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目... | --- +++ @@ -43,6 +43,12 @@
def calculate_number_of_files(file_store_path: str) -> int:
+ """Calculate the prefix sorting number for data save files, supporting writing to different files for each run
+ Args:
+ file_store_path;
+ Returns:
+ file nums
+ """
if not os.path.exists(file_st... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/store/kuaishou/_store_impl.py |
Help me write clear docstrings | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/store/douyin/_store_impl.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使... | --- +++ @@ -48,18 +48,42 @@ )
async def store_content(self, content_item: Dict):
+ """
+ Douyin content CSV storage implementation
+ Args:
+ content_item: note item dict
+
+ Returns:
+
+ """
await self.file_writer.write_to_csv(
item=cont... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/store/douyin/_store_impl.py |
Add docstrings that explain inputs and outputs | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/store/tieba/__init__.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用... | --- +++ @@ -49,6 +49,14 @@
async def batch_update_tieba_notes(note_list: List[TiebaNote]):
+ """
+ Batch update tieba notes
+ Args:
+ note_list:
+
+ Returns:
+
+ """
if not note_list:
return
for note_item in note_list:
@@ -56,6 +64,14 @@
async def update_tieba_note(note_... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/store/tieba/__init__.py |
Help me write clear docstrings | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/tools/browser_launcher.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。... | --- +++ @@ -32,6 +32,10 @@
class BrowserLauncher:
+ """
+ Browser launcher for detecting and launching user's Chrome/Edge browser
+ Supports Windows and macOS systems
+ """
def __init__(self):
self.system = platform.system()
@@ -39,6 +43,10 @@ self.debug_port = None
def de... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/tools/browser_launcher.py |
Create docstrings for API functions | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/store/bilibili/bilibilli_store_media.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本... | --- +++ @@ -39,14 +39,44 @@ self.video_store_path = "data/bili/videos"
async def store_video(self, video_content_item: Dict):
+ """
+ store content
+
+ Args:
+ video_content_item:
+
+ Returns:
+
+ """
await self.save_video(video_content_item.get(... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/store/bilibili/bilibilli_store_media.py |
Add well-formatted docstrings | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/tools/crawler_util.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用者应... | --- +++ @@ -40,6 +40,7 @@
async def find_login_qrcode(page: Page, selector: str) -> str:
+ """find login qrcode image from target selector"""
try:
elements = await page.wait_for_selector(
selector=selector,
@@ -62,6 +63,15 @@
async def find_qrcode_img_from_canvas(page: Page, canvas... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/tools/crawler_util.py |
Add docstrings to improve code quality | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/tools/cdp_browser.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用者应遵... | --- +++ @@ -33,6 +33,9 @@
class CDPBrowserManager:
+ """
+ CDP browser manager, responsible for launching and managing browsers connected via CDP
+ """
def __init__(self):
self.launcher = BrowserLauncher()
@@ -42,10 +45,14 @@ self._cleanup_registered = False
def _register_cle... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/tools/cdp_browser.py |
Document functions with clear intent | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/store/douyin/__init__.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使... | --- +++ @@ -51,6 +51,15 @@
def _extract_note_image_list(aweme_detail: Dict) -> List[str]:
+ """
+ Extract note image list
+
+ Args:
+ aweme_detail (Dict): Douyin content details
+
+ Returns:
+ List[str]: Note image list
+ """
images_res: List[str] = []
images: List[Dict] = awe... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/store/douyin/__init__.py |
Generate consistent docstrings | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/store/bilibili/_store_impl.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目... | --- +++ @@ -51,30 +51,70 @@ )
async def store_content(self, content_item: Dict):
+ """
+ content CSV storage implementation
+ Args:
+ content_item:
+
+ Returns:
+
+ """
await self.file_writer.write_to_csv(
item=content_item,
... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/store/bilibili/_store_impl.py |
Add docstrings to existing functions | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/store/excel_store_base.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使... | --- +++ @@ -26,6 +26,10 @@ # 详细许可条款请参阅项目根目录下的LICENSE文件。
# 使用本代码即表示您同意遵守上述原则和LICENSE中的所有条款。
+"""
+Excel Store Base Implementation
+Provides Excel export functionality for crawled data with formatted sheets
+"""
import threading
from datetime import datetime
@@ -46,6 +50,11 @@
class ExcelStoreBase(AbstractStor... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/store/excel_store_base.py |
Add docstrings to existing functions | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/store/douyin/douyin_store_media.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学... | --- +++ @@ -35,12 +35,42 @@ self.image_store_path = "data/douyin/images"
async def store_image(self, image_content_item: Dict):
+ """
+ store content
+
+ Args:
+ image_content_item:
+
+ Returns:
+
+ """
await self.save_image(image_content_item.ge... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/store/douyin/douyin_store_media.py |
Can you add docstrings to this Python file? | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/tools/slider_util.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用者应遵... | --- +++ @@ -32,7 +32,15 @@
class Slide:
+ """
+ copy from https://blog.csdn.net/weixin_43582101 thanks for author
+ update: relakkes
+ """
def __init__(self, gap, bg, gap_size=None, bg_size=None, out=None):
+ """
+ :param gap: Gap image path or url
+ :param bg: Background image... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/tools/slider_util.py |
Add docstrings to existing functions | # -*- coding: utf-8 -*-
# Copyright (c) 2025 relakkes@gmail.com
#
# This file is part of MediaCrawler project.
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/recv_sms.py
# GitHub: https://github.com/NanmiCoder
# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1
#
# 声明:本代码仅供学习和研究目的使用。使用者应遵守以下原则:
# ... | --- +++ @@ -44,6 +44,9 @@
def extract_verification_code(message: str) -> str:
+ """
+ Extract verification code of 6 digits from the SMS.
+ """
pattern = re.compile(r'\b[0-9]{6}\b')
codes: List[str] = pattern.findall(message)
return codes[0] if codes else ""
@@ -51,6 +54,21 @@
@app.post("/... | https://raw.githubusercontent.com/NanmiCoder/MediaCrawler/HEAD/recv_sms.py |
Can you add docstrings to this Python file? |
import re
import tempfile
import zipfile
import lxml.etree
from .base import BaseSchemaValidator
class DOCXSchemaValidator(BaseSchemaValidator):
# Word-specific namespace
WORD_2006_NAMESPACE = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
# Word-specific element to relationship type ... | --- +++ @@ -1,3 +1,6 @@+"""
+Validator for Word document XML files against XSD schemas.
+"""
import re
import tempfile
@@ -9,6 +12,7 @@
class DOCXSchemaValidator(BaseSchemaValidator):
+ """Validator for Word document XML files against XSD schemas."""
# Word-specific namespace
WORD_2006_NAMESPACE ... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/pptx/ooxml/scripts/validation/docx.py |
Can you add docstrings to this Python file? | #!/usr/bin/env python3
from PIL import Image, ImageDraw, ImageFont
import numpy as np
from typing import Optional
def create_blank_frame(width: int, height: int, color: tuple[int, int, int] = (255, 255, 255)) -> Image.Image:
return Image.new('RGB', (width, height), color)
def draw_circle(frame: Image.Image, ce... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""
+Frame Composer - Utilities for composing visual elements into frames.
+
+Provides functions for drawing shapes, text, emojis, and compositing elements
+together to create animation frames.
+"""
from PIL import Image, ImageDraw, ImageFont
import numpy as np
@@ -6... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/core/frame_composer.py |
Add docstrings that explain inputs and outputs | #!/usr/bin/env python3
import sys
import math
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from core.gif_builder import GIFBuilder
from core.frame_composer import create_blank_frame, draw_circle, draw_emoji, draw_text
from core.easing import ease_out_quad
def create_shake_animation(
... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""
+Shake Animation Template - Creates shaking/vibrating motion.
+
+Use this for impact effects, emphasis, or nervous/excited reactions.
+"""
import sys
import math
@@ -23,6 +28,24 @@ frame_height: int = 480,
bg_color: tuple[int, int, int] = (255, 255, 255)
... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/shake.py |
Add docstrings to improve code quality | #!/usr/bin/env python3
import json
import sys
from pathlib import Path
from typing import Any, Dict, List
from inventory import InventoryData, extract_text_inventory
from pptx import Presentation
from pptx.dml.color import RGBColor
from pptx.enum.dml import MSO_THEME_COLOR
from pptx.enum.text import PP_ALIGN
from ppt... | --- +++ @@ -1,4 +1,13 @@ #!/usr/bin/env python3
+"""Apply text replacements to PowerPoint presentation.
+
+Usage:
+ python replace.py <input.pptx> <replacements.json> <output.pptx>
+
+The replacements JSON should have the structure output by inventory.py.
+ALL text shapes identified by inventory.py will have their t... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/pptx/scripts/replace.py |
Add docstrings to improve readability |
import subprocess
import tempfile
import zipfile
from pathlib import Path
class RedliningValidator:
def __init__(self, unpacked_dir, original_docx, verbose=False):
self.unpacked_dir = Path(unpacked_dir)
self.original_docx = Path(original_docx)
self.verbose = verbose
self.namespac... | --- +++ @@ -1,3 +1,6 @@+"""
+Validator for tracked changes in Word documents.
+"""
import subprocess
import tempfile
@@ -6,6 +9,7 @@
class RedliningValidator:
+ """Validator for tracked changes in Word documents."""
def __init__(self, unpacked_dir, original_docx, verbose=False):
self.unpacked... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/document-skills/pptx/ooxml/scripts/validation/redlining.py |
Generate consistent documentation across files | #!/usr/bin/env python3
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from PIL import Image, ImageDraw
import numpy as np
from core.gif_builder import GIFBuilder
from core.frame_composer import create_blank_frame, draw_emoji_enhanced
from core.easing import interpolate
def c... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""
+Fade Animation - Fade in, fade out, and crossfade effects.
+
+Creates smooth opacity transitions for appearing, disappearing, and transitioning.
+"""
import sys
from pathlib import Path
@@ -23,6 +28,23 @@ frame_height: int = 480,
bg_color: tuple[int, int... | https://raw.githubusercontent.com/ComposioHQ/awesome-claude-skills/HEAD/slack-gif-creator/templates/fade.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.