instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Help me add docstrings to my project
from fastapi import APIRouter, HTTPException from fastapi.responses import StreamingResponse from pydantic import BaseModel from typing import List, Dict, Any import logging from app.backend.models.schemas import ErrorResponse from app.backend.services.ollama_service import ollama_service logger = logging.getLogger(_...
--- +++ @@ -46,6 +46,7 @@ }, ) async def get_ollama_status(): + """Get Ollama installation and server status.""" try: status = await ollama_service.check_ollama_status() return OllamaStatusResponse(**status) @@ -62,6 +63,7 @@ }, ) async def start_ollama_server(): + """Start the ...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/app/backend/routes/ollama.py
Generate documentation strings for clarity
import json from pydantic import BaseModel from src.llm.models import get_model, get_model_info from src.utils.progress import progress from src.graph.state import AgentState def call_llm( prompt: any, pydantic_model: type[BaseModel], agent_name: str | None = None, state: AgentState | None = None, ...
--- +++ @@ -1,3 +1,4 @@+"""Helper functions for LLM""" import json from pydantic import BaseModel @@ -14,6 +15,20 @@ max_retries: int = 3, default_factory=None, ) -> BaseModel: + """ + Makes an LLM call with retry logic, handling both JSON supported and non-JSON supported models. + + Args: + ...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/utils/llm.py
Add docstrings to incomplete code
import re from datetime import datetime, timedelta from typing import Tuple, Dict, Optional from .errors import InvalidParameterError class DateParser: # 中文日期映射 CN_DATE_MAPPING = { "今天": 0, "昨天": 1, "前天": 2, "大前天": 3, } # 英文日期映射 EN_DATE_MAPPING = { "toda...
--- +++ @@ -1,3 +1,8 @@+""" +日期解析工具 + +支持多种自然语言日期格式解析,包括相对日期和绝对日期。 +""" import re from datetime import datetime, timedelta @@ -7,6 +12,7 @@ class DateParser: + """日期解析器类""" # 中文日期映射 CN_DATE_MAPPING = { @@ -84,6 +90,35 @@ @staticmethod def parse_date_query(date_query: str) -> datetime: ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/mcp_server/utils/date_parser.py
Add docstrings explaining edge cases
import re from collections import Counter from datetime import datetime, timedelta from difflib import SequenceMatcher from typing import Dict, List, Optional, Tuple, Union from ..services.data_service import DataService from ..utils.validators import validate_keyword, validate_limit, validate_threshold, normalize_da...
--- +++ @@ -1,3 +1,8 @@+""" +智能新闻检索工具 + +提供模糊搜索、链接查询、历史相关新闻检索等高级搜索功能。 +""" import re from collections import Counter @@ -11,8 +16,15 @@ class SearchTools: + """智能新闻检索工具类""" def __init__(self, project_root: str = None): + """ + 初始化智能检索工具 + + Args: + project_root: 项目根目录 +...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/mcp_server/tools/search_tools.py
Help me add docstrings to my project
# coding=utf-8 import re import html import json from dataclasses import dataclass from datetime import datetime from typing import List, Optional, Dict, Any from email.utils import parsedate_to_datetime try: import feedparser HAS_FEEDPARSER = True except ImportError: HAS_FEEDPARSER = False feedparser...
--- +++ @@ -1,4 +1,9 @@ # coding=utf-8 +""" +RSS 解析器 + +支持 RSS 2.0、Atom 和 JSON Feed 1.1 格式的解析 +""" import re import html @@ -18,6 +23,7 @@ @dataclass class ParsedRSSItem: + """解析后的 RSS 条目""" title: str url: str published_at: Optional[str] = None @@ -27,14 +33,31 @@ class RSSParser: + """...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/crawler/rss/parser.py
Generate docstrings for exported functions
from pathlib import Path from typing import Dict, List, Optional from ..services.data_service import DataService from ..utils.validators import validate_platforms from ..utils.errors import MCPError, CrawlTaskError class SystemManagementTools: def __init__(self, project_root: str = None): self.data_ser...
--- +++ @@ -1,3 +1,8 @@+""" +系统管理工具 + +实现系统状态查询和爬虫触发功能。 +""" from pathlib import Path from typing import Dict, List, Optional @@ -8,8 +13,15 @@ class SystemManagementTools: + """系统管理工具类""" def __init__(self, project_root: str = None): + """ + 初始化系统管理工具 + + Args: + proje...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/mcp_server/tools/system.py
Write clean docstrings for readability
# coding=utf-8 import time import random from dataclasses import dataclass from typing import List, Dict, Optional, Tuple import requests from .parser import RSSParser from trendradar.storage.base import RSSItem, RSSData from trendradar.utils.time import get_configured_time, is_within_days, DEFAULT_TIMEZONE @datac...
--- +++ @@ -1,4 +1,9 @@ # coding=utf-8 +""" +RSS 抓取器 + +负责从配置的 RSS 源抓取数据并转换为标准格式 +""" import time import random @@ -14,6 +19,7 @@ @dataclass class RSSFeedConfig: + """RSS 源配置""" id: str # 源 ID name: str # 显示名称 url: str # RSS URL @@ -23,6 ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/crawler/rss/fetcher.py
Add professional docstrings to my codebase
from datetime import datetime from typing import List, Optional, Union import os import json import yaml import ast from .errors import InvalidParameterError from .date_parser import DateParser # ==================== 辅助函数:处理字符串序列化 ==================== def _parse_string_to_list(value: str) -> List[str]: value =...
--- +++ @@ -1,3 +1,9 @@+""" +参数验证工具 + +提供统一的参数验证功能。 +支持 MCP 客户端将参数序列化为字符串的情况。 +""" from datetime import datetime from typing import List, Optional, Union @@ -13,6 +19,23 @@ # ==================== 辅助函数:处理字符串序列化 ==================== def _parse_string_to_list(value: str) -> List[str]: + """ + 将字符串解析为列表 + + ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/mcp_server/utils/validators.py
Help me comply with documentation standards
# coding=utf-8 import os import re from pathlib import Path from datetime import datetime, timedelta from typing import Dict, List, Optional import yaml from ..utils.errors import MCPError class StorageSyncTools: def __init__(self, project_root: str = None): if project_root: self.project_r...
--- +++ @@ -1,4 +1,9 @@ # coding=utf-8 +""" +存储同步工具 + +实现从远程存储拉取数据到本地、获取存储状态、列出可用日期等功能。 +""" import os import re @@ -12,8 +17,15 @@ class StorageSyncTools: + """存储同步工具类""" def __init__(self, project_root: str = None): + """ + 初始化存储同步工具 + + Args: + project_root: 项目根目录 + ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/mcp_server/tools/storage_sync.py
Generate descriptive docstrings automatically
# coding=utf-8 import os from pathlib import Path from typing import Dict, Any, Optional import yaml from .config import parse_multi_account_config, validate_paired_configs from trendradar.utils.time import DEFAULT_TIMEZONE def _get_env_bool(key: str) -> Optional[bool]: value = os.environ.get(key, "").strip()....
--- +++ @@ -1,4 +1,9 @@ # coding=utf-8 +""" +配置加载模块 + +负责从 YAML 配置文件和环境变量加载配置。 +""" import os from pathlib import Path @@ -11,6 +16,7 @@ def _get_env_bool(key: str) -> Optional[bool]: + """从环境变量获取布尔值,如果未设置返回 None""" value = os.environ.get(key, "").strip().lower() if not value: return None ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/core/loader.py
Add well-formatted docstrings
# coding=utf-8 import argparse import copy import json import os import re import sys import webbrowser from datetime import datetime, timezone from pathlib import Path from typing import Dict, List, Tuple, Optional import requests from trendradar.context import AppContext from trendradar import __version__ from tre...
--- +++ @@ -1,4 +1,10 @@ # coding=utf-8 +""" +TrendRadar 主程序 + +热点新闻聚合与分析工具 +支持: python -m trendradar +""" import argparse import copy @@ -25,6 +31,7 @@ def _parse_version(version_str: str) -> Tuple[int, int, int]: + """解析版本号字符串为元组""" try: parts = version_str.strip().split(".") if len(...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/__main__.py
Provide clean and structured docstrings
from colorama import Fore, Style from tabulate import tabulate from .analysts import ANALYST_ORDER import os import json def sort_agent_signals(signals): # Create order mapping from ANALYST_ORDER analyst_order = {display: idx for idx, (display, _) in enumerate(ANALYST_ORDER)} analyst_order["Risk Managemen...
--- +++ @@ -6,6 +6,7 @@ def sort_agent_signals(signals): + """Sort agent signals in a consistent order.""" # Create order mapping from ANALYST_ORDER analyst_order = {display: idx for idx, (display, _) in enumerate(ANALYST_ORDER)} analyst_order["Risk Management"] = len(ANALYST_ORDER) # Add Risk Ma...
https://raw.githubusercontent.com/virattt/ai-hedge-fund/HEAD/src/utils/display.py
Add docstrings to make code maintainable
# coding=utf-8 from typing import Dict, List, Optional, Tuple def parse_multi_account_config(config_value: str, separator: str = ";") -> List[str]: if not config_value: return [] # 保留空字符串用于占位(如 ";token2" 表示第一个账号无token) accounts = [acc.strip() for acc in config_value.split(separator)] # 过滤掉全部为...
--- +++ @@ -1,9 +1,32 @@ # coding=utf-8 +""" +配置工具模块 - 多账号配置解析和验证 + +提供多账号推送配置的解析、验证和限制功能 +""" from typing import Dict, List, Optional, Tuple def parse_multi_account_config(config_value: str, separator: str = ";") -> List[str]: + """ + 解析多账号配置,返回账号列表 + + Args: + config_value: 配置值字符串,多个账号用分隔符分隔 +...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/core/config.py
Annotate my code with docstrings
# coding=utf-8 from datetime import datetime from typing import Dict, List, Optional, Callable from trendradar.report.helpers import html_escape def render_rss_html_content( rss_items: List[Dict], total_count: int, feeds_info: Optional[Dict[str, str]] = None, *, get_time_func: Optional[Callable[...
--- +++ @@ -1,4 +1,9 @@ # coding=utf-8 +""" +RSS HTML 报告渲染模块 + +提供 RSS 订阅内容的 HTML 格式报告生成功能 +""" from datetime import datetime from typing import Dict, List, Optional, Callable @@ -13,6 +18,24 @@ *, get_time_func: Optional[Callable[[], datetime]] = None, ) -> str: + """渲染 RSS HTML 内容 + + Args: + ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/report/rss_html.py
Can you add docstrings to this Python file?
# coding=utf-8 import json import random import time from typing import Dict, List, Tuple, Optional, Union import requests class DataFetcher: # 默认 API 地址 DEFAULT_API_URL = "https://newsnow.busiyi.world/api/s" # 默认请求头 DEFAULT_HEADERS = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x...
--- +++ @@ -1,4 +1,13 @@ # coding=utf-8 +""" +数据获取器模块 + +负责从 NewsNow API 抓取新闻数据,支持: +- 单个平台数据获取 +- 批量平台数据爬取 +- 自动重试机制 +- 代理支持 +""" import json import random @@ -9,6 +18,7 @@ class DataFetcher: + """数据获取器""" # 默认 API 地址 DEFAULT_API_URL = "https://newsnow.busiyi.world/api/s" @@ -27,6 +37,13 @@ ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/crawler/fetcher.py
Write Python docstrings for this snippet
# coding=utf-8 from typing import List def get_batch_header(format_type: str, batch_num: int, total_batches: int) -> str: if format_type == "telegram": return f"<b>[第 {batch_num}/{total_batches} 批次]</b>\n\n" elif format_type == "slack": return f"*[第 {batch_num}/{total_batches} 批次]*\n\n" e...
--- +++ @@ -1,9 +1,24 @@ # coding=utf-8 +""" +批次处理模块 + +提供消息分批发送的辅助函数 +""" from typing import List def get_batch_header(format_type: str, batch_num: int, total_batches: int) -> str: + """根据 format_type 生成对应格式的批次头部 + + Args: + format_type: 推送类型(telegram, slack, wework_text, bark, feishu, dingtalk, n...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/notification/batch.py
Turn comments into proper docstrings
# coding=utf-8 import sqlite3 import shutil import pytz import re from datetime import datetime, timedelta from pathlib import Path from typing import Dict, List, Optional from trendradar.storage.base import StorageBackend, NewsData, RSSItem, RSSData from trendradar.storage.sqlite_mixin import SQLiteStorageMixin from...
--- +++ @@ -1,4 +1,9 @@ # coding=utf-8 +""" +本地存储后端 - SQLite + TXT/HTML + +使用 SQLite 作为主存储,支持可选的 TXT 快照和 HTML 报告 +""" import sqlite3 import shutil @@ -19,6 +24,14 @@ class LocalStorageBackend(SQLiteStorageMixin, StorageBackend): + """ + 本地存储后端 + + 使用 SQLite 数据库存储新闻数据,支持: + - 按日期组织的 SQLite 数据库文件 + ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/storage/local.py
Write docstrings describing functionality
# coding=utf-8 from datetime import datetime from typing import Any, Dict, List, Optional, Callable from trendradar.report.helpers import html_escape from trendradar.utils.time import convert_time_for_display from trendradar.ai.formatter import render_ai_analysis_html_rich def render_html_content( report_data: ...
--- +++ @@ -1,4 +1,9 @@ # coding=utf-8 +""" +HTML 报告渲染模块 + +提供 HTML 格式的热点新闻报告生成功能 +""" from datetime import datetime from typing import Any, Dict, List, Optional, Callable @@ -23,6 +28,25 @@ ai_analysis: Optional[Any] = None, show_new_section: bool = True, ) -> str: + """渲染HTML内容 + + Args: + ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/report/html.py
Add docstrings including usage examples
# coding=utf-8 import copy import re from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional from datetime import datetime @dataclass class ResolvedSchedule: period_key: Optional[str] # 命中的 period key,None=默认配置 period_name: Optional[str] # 命中的展示名称 day_plan: st...
--- +++ @@ -1,4 +1,10 @@ # coding=utf-8 +""" +时间线调度器 + +统一的时间线调度系统,替代分散的 push_window / analysis_window 逻辑。 +基于 periods + day_plans + week_map 模型实现灵活的时间段调度。 +""" import copy import re @@ -10,6 +16,7 @@ @dataclass class ResolvedSchedule: + """当前时间解析后的调度结果""" period_key: Optional[str] # 命中的 period key...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/core/scheduler.py
Add docstrings to make code maintainable
# coding=utf-8 from typing import Dict, List, Tuple, Optional, Callable from trendradar.core.frequency import matches_word_groups, _word_matches from trendradar.utils.time import DEFAULT_TIMEZONE def calculate_news_weight( title_data: Dict, rank_threshold: int, weight_config: Dict, ) -> float: ranks...
--- +++ @@ -1,4 +1,12 @@ # coding=utf-8 +""" +统计分析模块 + +提供新闻统计和分析功能: +- calculate_news_weight: 计算新闻权重 +- format_time_display: 格式化时间显示 +- count_word_frequency: 统计词频 +""" from typing import Dict, List, Tuple, Optional, Callable @@ -11,6 +19,17 @@ rank_threshold: int, weight_config: Dict, ) -> float: + "...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/core/analyzer.py
Add structured docstrings to improve clarity
# coding=utf-8 import hashlib import json from dataclasses import dataclass, field from pathlib import Path from typing import Any, Callable, Dict, List, Optional from trendradar.ai.client import AIClient @dataclass class AIFilterResult: tags: List[Dict] = field(default_factory=list) # [{"tag": str, "descri...
--- +++ @@ -1,4 +1,11 @@ # coding=utf-8 +""" +AI 智能筛选模块 + +通过 AI 对新闻进行标签分类: +1. 阶段 A:从用户兴趣描述中提取结构化标签 +2. 阶段 B:对新闻标题按标签进行批量分类 +""" import hashlib import json @@ -11,6 +18,7 @@ @dataclass class AIFilterResult: + """AI 筛选结果,传给报告和通知模块""" tags: List[Dict] = field(default_factory=list) # [{"tag": str, "de...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/ai/filter.py
Generate consistent documentation across files
# coding=utf-8 import html as html_lib import re from .analyzer import AIAnalysisResult def _escape_html(text: str) -> str: return html_lib.escape(text) if text else "" def _format_list_content(text: str) -> str: if not text: return "" # 去除首尾空白,防止 AI 返回的内容开头就有换行导致显示空行 text = text.strip...
--- +++ @@ -1,4 +1,9 @@ # coding=utf-8 +""" +AI 分析结果格式化模块 + +将 AI 分析结果格式化为各推送渠道的样式 +""" import html as html_lib import re @@ -6,10 +11,17 @@ def _escape_html(text: str) -> str: + """转义 HTML 特殊字符,防止 XSS 攻击""" return html_lib.escape(text) if text else "" def _format_list_content(text: str) -> str: + ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/ai/formatter.py
Add standardized docstrings across the file
# coding=utf-8 from datetime import datetime from typing import Optional, Tuple import pytz # 默认时区常量 - 仅作为 fallback,正常运行时使用 config.yaml 中的 app.timezone DEFAULT_TIMEZONE = "Asia/Shanghai" def get_configured_time(timezone: str = DEFAULT_TIMEZONE) -> datetime: try: tz = pytz.timezone(timezone) except ...
--- +++ @@ -1,4 +1,9 @@ # coding=utf-8 +""" +时间工具模块 + +本模块提供统一的时间处理函数,所有时区相关操作都应使用 DEFAULT_TIMEZONE 常量。 +""" from datetime import datetime from typing import Optional, Tuple @@ -10,6 +15,15 @@ def get_configured_time(timezone: str = DEFAULT_TIMEZONE) -> datetime: + """ + 获取配置时区的当前时间 + + Args: + ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/utils/time.py
Document this script properly
# coding=utf-8 from datetime import datetime from pathlib import Path from typing import Any, Dict, List, Optional, Tuple from trendradar.utils.time import ( DEFAULT_TIMEZONE, get_configured_time, format_date_folder, format_time_filename, get_current_time_display, convert_time_for_display, ...
--- +++ @@ -1,4 +1,9 @@ # coding=utf-8 +""" +应用上下文模块 + +提供配置上下文类,封装所有依赖配置的操作,消除全局状态和包装函数。 +""" from datetime import datetime from pathlib import Path @@ -39,8 +44,34 @@ class AppContext: + """ + 应用上下文类 + + 封装所有依赖配置的操作,提供统一的接口。 + 消除对全局 CONFIG 的依赖,提高可测试性。 + + 使用示例: + config = load_config() +...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/context.py
Add docstrings to incomplete code
# coding=utf-8 from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, List from trendradar.ai.client import AIClient @dataclass class TranslationResult: translated_text: str = "" # 翻译后的文本 original_text: str = "" # 原始文本 success: bool = False ...
--- +++ @@ -1,4 +1,10 @@ # coding=utf-8 +""" +AI 翻译器模块 + +对推送内容进行多语言翻译 +基于 LiteLLM 统一接口,支持 100+ AI 提供商 +""" from dataclasses import dataclass, field from pathlib import Path @@ -9,6 +15,7 @@ @dataclass class TranslationResult: + """翻译结果""" translated_text: str = "" # 翻译后的文本 original_text: str ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/ai/translator.py
Add standardized docstrings across the file
# coding=utf-8 from abc import ABC, abstractmethod from dataclasses import dataclass, field from typing import Dict, List, Optional, Any, Set @dataclass class NewsItem: title: str # 新闻标题 source_id: str # 来源平台ID(如 toutiao, baidu) source_name: str = "" ...
--- +++ @@ -1,4 +1,9 @@ # coding=utf-8 +""" +存储后端抽象基类和数据模型 + +定义统一的存储接口,所有存储后端都需要实现这些方法 +""" from abc import ABC, abstractmethod from dataclasses import dataclass, field @@ -7,6 +12,7 @@ @dataclass class NewsItem: + """新闻条目数据模型(热榜数据)""" title: str # 新闻标题 source_id: str ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/storage/base.py
Create docstrings for each class method
# coding=utf-8 import os from typing import Any, Dict, List from litellm import completion class AIClient: def __init__(self, config: Dict[str, Any]): self.model = config.get("MODEL", "deepseek/deepseek-chat") self.api_key = config.get("API_KEY") or os.environ.get("AI_API_KEY", "") self...
--- +++ @@ -1,4 +1,10 @@ # coding=utf-8 +""" +AI 客户端模块 + +基于 LiteLLM 的统一 AI 模型接口 +支持 100+ AI 提供商(OpenAI、DeepSeek、Gemini、Claude、国内模型等) +""" import os from typing import Any, Dict, List @@ -7,8 +13,23 @@ class AIClient: + """统一的 AI 客户端(基于 LiteLLM)""" def __init__(self, config: Dict[str, Any]): + ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/ai/client.py
Fill in missing docstrings in my code
# coding=utf-8 from datetime import datetime from typing import Dict, List, Optional, Callable from trendradar.report.formatter import format_title_for_platform # 默认区域顺序 DEFAULT_REGION_ORDER = ["hotlist", "rss", "new_items", "standalone", "ai_analysis"] def render_feishu_content( report_data: Dict, update...
--- +++ @@ -1,4 +1,9 @@ # coding=utf-8 +""" +通知内容渲染模块 + +提供多平台通知内容渲染功能,生成格式化的推送消息 +""" from datetime import datetime from typing import Dict, List, Optional, Callable @@ -20,6 +25,21 @@ rss_items: Optional[list] = None, show_new_section: bool = True, ) -> str: + """渲染飞书通知内容(支持热榜+RSS合并) + + Args: + ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/notification/renderer.py
Expand my code with proper documentation strings
# coding=utf-8 import json from dataclasses import dataclass, field from pathlib import Path from typing import Any, Callable, Dict, List, Optional from trendradar.ai.client import AIClient @dataclass class AIAnalysisResult: # 新版 5 核心板块 core_trends: str = "" # 核心热点与舆情态势 sentiment_controve...
--- +++ @@ -1,4 +1,10 @@ # coding=utf-8 +""" +AI 分析器模块 + +调用 AI 大模型对热点新闻进行深度分析 +基于 LiteLLM 统一接口,支持 100+ AI 提供商 +""" import json from dataclasses import dataclass, field @@ -10,6 +16,7 @@ @dataclass class AIAnalysisResult: + """AI 分析结果""" # 新版 5 核心板块 core_trends: str = "" # 核心热点与舆情态势 ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/ai/analyzer.py
Generate consistent docstrings
from extras.BLIP.models.med import BertConfig, BertModel from transformers import BertTokenizer import torch from torch import nn import torch.nn.functional as F from extras.BLIP.models.blip import create_vit, init_tokenizer, load_checkpoint class BLIP_Retrieval(nn.Module): def __init__(self, ...
--- +++ @@ -19,6 +19,12 @@ momentum = 0.995, negative_all_rank = False, ): + """ + Args: + med_config (str): path for the mixture of encoder-decoder model's configuration file + image_size (int): input image size + vit (...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/extras/BLIP/models/blip_retrieval.py
Help me comply with documentation standards
import math import os import warnings from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import Tensor, device, dtype, nn import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss import torch.nn.functional as F from transformers.activations im...
--- +++ @@ -1,3 +1,12 @@+''' + * Copyright (c) 2022, salesforce.com, inc. + * All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause + * By Junnan Li + * Based on huggingface code base + * https://gi...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/extras/BLIP/models/med.py
Help me comply with documentation standards
import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from timm.models.vision_transformer import _cfg, PatchEmbed from timm.models.registry import register_model from timm.models.layers import trunc_normal_, DropPath from timm.models.helpers import named_apply, adapt_input_c...
--- +++ @@ -1,3 +1,12 @@+''' + * Copyright (c) 2022, salesforce.com, inc. + * All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause + * By Junnan Li + * Based on timm code base + * https://github.co...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/extras/BLIP/models/vit.py
Generate NumPy-style docstrings
# coding=utf-8 import os import re from pathlib import Path from typing import Dict, List, Tuple, Optional, Union def _parse_word(word: str) -> Dict: display_name = None # 1. 优先处理显示名称 (=>) # 先切分出 "配置内容" 和 "显示名称" if '=>' in word: parts = re.split(r'\s*=>\s*', word, 1) word_config = pa...
--- +++ @@ -1,4 +1,17 @@ # coding=utf-8 +""" +频率词配置加载模块 + +负责从配置文件加载频率词规则,支持: +- 普通词组 +- 必须词(+前缀) +- 过滤词(!前缀) +- 全局过滤词([GLOBAL_FILTER] 区域) +- 最大显示数量(@前缀) +- 正则表达式(/pattern/ 语法) +- 显示名称(=> 别名 语法) +- 组别名([组别名] 语法,作为词组第一行) +""" import os import re @@ -7,6 +20,15 @@ def _parse_word(word: str) -> Dict: + """ + ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/core/frequency.py
Add docstrings with type hints explained
import cv2 import numpy as np from .matlab_cp2tform import get_similarity_transform_for_cv2 # reference facial points, a list of coordinates (x,y) REFERENCE_FACIAL_POINTS = [[30.29459953, 51.69630051], [65.53179932, 51.50139999], [48.02519989, 71.73660278], [33.54930115, 92.3655014], [62.72...
--- +++ @@ -17,6 +17,41 @@ def get_reference_facial_points(output_size=None, inner_padding_factor=0.0, outer_padding=(0, 0), default_square=False): + """ + Function: + ---------- + get reference 5 key points according to crop settings: + 0. Set default crop_size: + if default_squar...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/extras/facexlib/detection/align_trans.py
Replace inline comments with docstrings
import numpy as np import torch import torchvision from itertools import product as product from math import ceil class PriorBox(object): def __init__(self, cfg, image_size=None, phase='train'): super(PriorBox, self).__init__() self.min_sizes = cfg['min_sizes'] self.steps = cfg['steps'] ...
--- +++ @@ -37,6 +37,7 @@ def py_cpu_nms(dets, thresh): + """Pure Python NMS baseline.""" keep = torchvision.ops.nms( boxes=torch.Tensor(dets[:, :4]), scores=torch.Tensor(dets[:, 4]), @@ -47,6 +48,13 @@ def point_form(boxes): + """ Convert prior_boxes to (xmin, ymin, xmax, ymax) + ...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/extras/facexlib/detection/retinaface_utils.py
Write docstrings for this repository
# coding=utf-8 import re def strip_markdown(text: str) -> str: # 转换链接 [text](url) -> text url(保留 URL) text = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'\1 \2', text) # 先保护 URL,避免后续 markdown 清洗误伤链接中的下划线等字符 protected_urls: list[str] = [] def _protect_url(match: re.Match) -> str: protected_urls....
--- +++ @@ -1,9 +1,22 @@ # coding=utf-8 +""" +通知内容格式转换模块 + +提供不同推送平台间的格式转换功能 +""" import re def strip_markdown(text: str) -> str: + """去除文本中的 markdown 语法格式,用于个人微信推送 + + Args: + text: 包含 markdown 格式的文本 + + Returns: + 纯文本内容 + """ # 转换链接 [text](url) -> text url(保留 URL) text = re...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/notification/formatters.py
Add docstrings to meet PEP guidelines
# coding=utf-8 from __future__ import annotations from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional from trendradar.core.config import ( get_account_at_index, limit_accounts, parse_multi_account_config, validate_paired_configs, ) from .senders import ( send_to_bark, send_...
--- +++ @@ -1,4 +1,14 @@ # coding=utf-8 +""" +通知调度器模块 + +提供统一的通知分发接口。 +支持所有通知渠道的多账号配置,使用 `;` 分隔多个账号。 + +使用示例: + dispatcher = NotificationDispatcher(config, get_time_func, split_content_func) + results = dispatcher.dispatch_all(report_data, report_type, ...) +""" from __future__ import annotations @@ -34,6 +4...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/notification/dispatcher.py
Create structured documentation for my script
import cv2 import numpy as np import os import torch from torchvision.transforms.functional import normalize from extras.facexlib.detection import init_detection_model from extras.facexlib.parsing import init_parsing_model from extras.facexlib.utils.misc import img2tensor, imwrite def get_largest_face(det_faces, h, ...
--- +++ @@ -46,6 +46,7 @@ class FaceRestoreHelper(object): + """Helper for the face restoration pipeline (base class).""" def __init__(self, upscale_factor, @@ -105,6 +106,7 @@ self.upscale_factor = upscale_factor def read_image(self, img): + """img can be image pat...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/extras/facexlib/utils/face_restoration_helper.py
Add concise docstrings to each method
import cv2 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from PIL import Image from torchvision.models._utils import IntermediateLayerGetter as IntermediateLayerGetter from extras.facexlib.detection.align_trans import get_reference_facial_points, warp_and_crop_face from extras.f...
--- +++ @@ -259,6 +259,12 @@ # batched detection def batched_transform(self, frames, use_origin_size): + """ + Arguments: + frames: a list of PIL.Image, or torch.Tensor(shape=[n, h, w, c], + type=np.float32, BGR format). + use_origin_size: whether to use ori...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/extras/facexlib/detection/retinaface.py
Add structured docstrings to improve clarity
import numpy as np from numpy.linalg import inv, lstsq from numpy.linalg import matrix_rank as rank from numpy.linalg import norm class MatlabCp2tormException(Exception): def __str__(self): return 'In File {}:{}'.format(__file__, super.__str__(self)) def tformfwd(trans, uv): uv = np.hstack((uv, np....
--- +++ @@ -11,6 +11,23 @@ def tformfwd(trans, uv): + """ + Function: + ---------- + apply affine transform 'trans' to uv + + Parameters: + ---------- + @trans: 3x3 np.array + transform matrix + @uv: Kx2 np.array + each row is a pair of coordinates (x, y) + ...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/extras/facexlib/detection/matlab_cp2tform.py
Write docstrings for data processing functions
# coding=utf-8 from typing import Dict, List, Tuple, Optional def read_all_today_titles_from_storage( storage_manager, current_platform_ids: Optional[List[str]] = None, ) -> Tuple[Dict, Dict, Dict]: try: news_data = storage_manager.get_today_all_data() if not news_data or not news_data.i...
--- +++ @@ -1,4 +1,13 @@ # coding=utf-8 +""" +数据处理模块 + +提供数据读取和检测功能: +- read_all_today_titles: 从存储后端读取当天所有标题 +- detect_latest_new_titles: 检测最新批次的新增标题 + +Author: TrendRadar Team +""" from typing import Dict, List, Tuple, Optional @@ -7,6 +16,16 @@ storage_manager, current_platform_ids: Optional[List[str]] ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/core/data.py
Add documentation for all methods
# coding=utf-8 import smtplib import time import json from datetime import datetime from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import formataddr, formatdate, make_msgid from pathlib import Path from typing import Any, Callable, D...
--- +++ @@ -1,4 +1,19 @@ # coding=utf-8 +""" +消息发送器模块 + +将报告数据发送到各种通知渠道: +- 飞书 (Feishu/Lark) +- 钉钉 (DingTalk) +- 企业微信 (WeCom/WeWork) +- Telegram +- 邮件 (Email) +- ntfy +- Bark +- Slack + +每个发送函数都支持分批发送,并通过参数化配置实现与 CONFIG 的解耦。 +""" import smtplib import time @@ -19,6 +34,7 @@ def _render_ai_analysis(ai_analysis: ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/notification/senders.py
Document all public functions with docstrings
# coding=utf-8 from pathlib import Path from typing import Dict, List, Optional, Callable def prepare_report_data( stats: List[Dict], failed_ids: Optional[List] = None, new_titles: Optional[Dict] = None, id_to_name: Optional[Dict] = None, mode: str = "daily", rank_threshold: int = 3, matc...
--- +++ @@ -1,4 +1,11 @@ # coding=utf-8 +""" +报告生成模块 + +提供报告数据准备和 HTML 生成功能: +- prepare_report_data: 准备报告数据 +- generate_html_report: 生成 HTML 报告 +""" from pathlib import Path from typing import Dict, List, Optional, Callable @@ -15,6 +22,23 @@ load_frequency_words_func: Optional[Callable] = None, show_new_s...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/report/generator.py
Generate missing documentation strings
# coding=utf-8 import re from typing import List def clean_title(title: str) -> str: if not isinstance(title, str): title = str(title) cleaned_title = title.replace("\n", " ").replace("\r", " ") cleaned_title = re.sub(r"\s+", " ", cleaned_title) cleaned_title = cleaned_title.strip() retur...
--- +++ @@ -1,10 +1,28 @@ # coding=utf-8 +""" +报告辅助函数模块 + +提供报告生成相关的通用辅助函数 +""" import re from typing import List def clean_title(title: str) -> str: + """清理标题中的特殊字符 + + 清理规则: + - 将换行符(\n, \r)替换为空格 + - 将多个连续空白字符合并为单个空格 + - 去除首尾空白 + + Args: + title: 原始标题字符串 + + Returns: + 清理后的...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/report/helpers.py
Add return value explanations in docstrings
# coding=utf-8 from datetime import datetime from typing import Dict, List, Optional, Callable from trendradar.report.formatter import format_title_for_platform from trendradar.report.helpers import format_rank_display from trendradar.utils.time import DEFAULT_TIMEZONE, format_iso_time_friendly, convert_time_for_disp...
--- +++ @@ -1,4 +1,9 @@ # coding=utf-8 +""" +消息分批处理模块 + +提供消息内容分批拆分功能,确保消息大小不超过各平台限制 +""" from datetime import datetime from typing import Dict, List, Optional, Callable @@ -41,6 +46,34 @@ report_type: str = "热点分析报告", show_new_section: bool = True, ) -> List[str]: + """分批处理消息内容,确保词组标题+至少第一条新闻的完整性(支持热榜+...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/notification/splitter.py
Document my Python code with docstrings
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch from ldm_patched.modules import model_management from ldm_patched.modules.model_patcher im...
--- +++ @@ -23,6 +23,13 @@ load_device=model_management.text_encoder_device(), offload_device=model_management.text_encoder_offload_device() ) -> None: + """ + Uses SAM to calculate the image embedding for an image, and then + allow repeated, efficient mask prediction given pr...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/extras/sam/predictor.py
Write documentation strings for class attributes
# coding=utf-8 import sqlite3 from abc import abstractmethod from datetime import datetime from pathlib import Path from typing import Any, Dict, List, Optional from trendradar.storage.base import NewsItem, NewsData, RSSItem, RSSData from trendradar.utils.url import normalize_url class SQLiteStorageMixin: # ==...
--- +++ @@ -1,4 +1,9 @@ # coding=utf-8 +""" +SQLite 存储 Mixin + +提供共用的 SQLite 数据库操作逻辑,供 LocalStorageBackend 和 RemoteStorageBackend 复用。 +""" import sqlite3 from abc import abstractmethod @@ -11,6 +16,15 @@ class SQLiteStorageMixin: + """ + SQLite 存储操作 Mixin + + 子类需要实现以下抽象方法: + - _get_connection(date, ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/storage/sqlite_mixin.py
Generate consistent documentation across files
import warnings warnings.filterwarnings("ignore") from extras.BLIP.models.vit import VisionTransformer, interpolate_pos_embed from extras.BLIP.models.med import BertConfig, BertModel, BertLMHeadModel from transformers import BertTokenizer import torch from torch import nn import torch.nn.functional as F import os fr...
--- +++ @@ -1,3 +1,10 @@+''' + * Copyright (c) 2022, salesforce.com, inc. + * All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause + * By Junnan Li +''' import warnings warnings.filterwarnings("i...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/extras/BLIP/models/blip.py
Add docstrings explaining edge cases
# coding=utf-8 from urllib.parse import urlparse, urlunparse, parse_qs, urlencode from typing import Dict, Set # 各平台需要移除的特定参数 # - weibo: 有 band_rank(排名)和 Refer(来源)动态参数 # - 其他平台: URL 为路径格式或简单关键词查询,无需处理 PLATFORM_PARAMS_TO_REMOVE: Dict[str, Set[str]] = { # 微博:band_rank 是动态排名参数,Refer 是来源参数,t 是时间范围参数 # 示例:htt...
--- +++ @@ -1,4 +1,10 @@ # coding=utf-8 +""" +URL 处理工具模块 + +提供 URL 标准化功能,用于去重时消除动态参数的影响: +- normalize_url: 标准化 URL,去除动态参数 +""" from urllib.parse import urlparse, urlunparse, parse_qs, urlencode from typing import Dict, Set @@ -30,6 +36,31 @@ def normalize_url(url: str, platform_id: str = "") -> str: + """ + ...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/utils/url.py
Generate consistent docstrings
# coding=utf-8 import os from typing import Optional from trendradar.storage.base import StorageBackend, NewsData, RSSData from trendradar.utils.time import DEFAULT_TIMEZONE # 存储管理器单例 _storage_manager: Optional["StorageManager"] = None class StorageManager: def __init__( self, backend_type: s...
--- +++ @@ -1,4 +1,9 @@ # coding=utf-8 +""" +存储管理器 - 统一管理存储后端 + +根据环境和配置自动选择合适的存储后端 +""" import os from typing import Optional @@ -12,6 +17,15 @@ class StorageManager: + """ + 存储管理器 + + 功能: + - 自动检测运行环境(GitHub Actions / Docker / 本地) + - 根据配置选择存储后端(local / remote / auto) + - 提供统一的存储接口 + - 支持...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/storage/manager.py
Write reusable docstrings
# coding=utf-8 import pytz import re import shutil import sys import tempfile import sqlite3 from datetime import datetime, timedelta from pathlib import Path from typing import Dict, List, Optional try: import boto3 from botocore.config import Config as BotoConfig from botocore.exceptions import ClientEr...
--- +++ @@ -1,4 +1,11 @@ # coding=utf-8 +""" +远程存储后端(S3 兼容协议) + +支持 Cloudflare R2、阿里云 OSS、腾讯云 COS、AWS S3、MinIO 等 +使用 S3 兼容 API (boto3) 访问对象存储 +数据流程:下载当天 SQLite → 合并新数据 → 上传回远程 +""" import pytz import re @@ -32,6 +39,17 @@ class RemoteStorageBackend(SQLiteStorageMixin, StorageBackend): + """ + 远程云存储后端(S3 兼...
https://raw.githubusercontent.com/sansan0/TrendRadar/HEAD/trendradar/storage/remote.py
Create documentation for each function signature
import cv2 import os import os.path as osp import torch from torch.hub import download_url_to_file, get_dir from urllib.parse import urlparse ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def imwrite(img, file_path, params=None, auto_mkdir=True): if auto_mkdir: d...
--- +++ @@ -9,6 +9,18 @@ def imwrite(img, file_path, params=None, auto_mkdir=True): + """Write image to file. + + Args: + img (ndarray): Image array to be written. + file_path (str): Image file path. + params (None or list): Same as opencv's :func:`imwrite` interface. + auto_mkdir ...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/extras/facexlib/utils/misc.py
Add docstrings explaining edge cases
from abc import abstractmethod import torch as th import torch.nn as nn import torch.nn.functional as F from einops import rearrange from .util import ( checkpoint, avg_pool_nd, zero_module, timestep_embedding, AlphaBlender, ) from ..attention import SpatialTransformer, SpatialVideoTransformer, de...
--- +++ @@ -18,9 +18,15 @@ ops = ldm_patched.modules.ops.disable_weight_init class TimestepBlock(nn.Module): + """ + Any module where forward() takes timestep embeddings as a second argument. + """ @abstractmethod def forward(self, x, emb): + """ + Apply the module to `x` given `em...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/ldm/modules/diffusionmodules/openaimodel.py
Write beginner-friendly docstrings
from extras.BLIP.models.med import BertConfig, BertModel, BertLMHeadModel from transformers import BertTokenizer import transformers transformers.logging.set_verbosity_error() import torch from torch import nn import torch.nn.functional as F from extras.BLIP.models.blip import create_vit, init_tokenizer, load_checkpo...
--- +++ @@ -1,3 +1,10 @@+''' + * Copyright (c) 2022, salesforce.com, inc. + * All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause + * By Junnan Li +''' from extras.BLIP.models.med import BertConf...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/extras/BLIP/models/blip_pretrain.py
Provide docstrings following PEP 257
import torch from torch import nn class LitEma(nn.Module): def __init__(self, model, decay=0.9999, use_num_upates=True): super().__init__() if decay < 0.0 or decay > 1.0: raise ValueError('Decay must be between 0 and 1') self.m_name2s_name = {} self.register_buffer('de...
--- +++ @@ -57,8 +57,24 @@ assert not key in self.m_name2s_name def store(self, parameters): + """ + Save the current parameters for restoring later. + Args: + parameters: Iterable of `torch.nn.Parameter`; the parameters to be + temporarily stored. + ...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/ldm/modules/ema.py
Add docstrings to improve code quality
# adopted from # https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py # and # https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py # and # https://github.com/openai/gu...
--- +++ @@ -148,6 +148,16 @@ def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999): + """ + Create a beta schedule that discretizes the given alpha_t_bar function, + which defines the cumulative product of (1-beta) over time from t = [0,1]. + :param num_diffusion_timesteps: the num...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/ldm/modules/diffusionmodules/util.py
Add documentation for all methods
import torch # import pytorch_lightning as pl import torch.nn.functional as F from contextlib import contextmanager from typing import Any, Dict, List, Optional, Tuple, Union from ldm_patched.ldm.modules.distributions.distributions import DiagonalGaussianDistribution from ldm_patched.ldm.util import instantiate_from_...
--- +++ @@ -32,6 +32,11 @@ class AbstractAutoencoder(torch.nn.Module): + """ + This is the base class for all autoencoders, including image autoencoders, image autoencoders with discriminators, + unCLIP models, etc. Hence, it is fairly general, and specific features + (e.g. discriminator training, encod...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/ldm/models/autoencoder.py
Add docstrings to my Python code
import math import os import warnings from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import Tensor, device, dtype, nn import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss import torch.nn.functional as F from transformers.activations imp...
--- +++ @@ -40,6 +40,7 @@ class BertEmbeddings(nn.Module): + """Construct the embeddings from word and position embeddings.""" def __init__(self, config): super().__init__() @@ -580,12 +581,17 @@ class BertPreTrainedModel(PreTrainedModel): + """ + An abstract class to handle weights ini...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/extras/BLIP/models/nlvr_encoder.py
Help me add docstrings to my project
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py import torch class LatentRebatch: @classmethod def INPUT_TYPES(s): return {"required": { "latents": ("LATENT",), "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}), }...
--- +++ @@ -18,6 +18,7 @@ @staticmethod def get_batch(latents, list_ind, offset): + '''prepare a batch out of the list of latents''' samples = latents[list_ind]['samples'] shape = samples.shape mask = latents[list_ind]['noise_mask'] if 'noise_mask' in latents[list_ind] else ...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/contrib/external_rebatch.py
Add docstrings for better understanding
from contextlib import contextmanager import hashlib import math from pathlib import Path import shutil import urllib import warnings from PIL import Image import torch from torch import nn, optim from torch.utils import data def hf_datasets_augs_helper(examples, transform, image_key, mode='RGB'): images = [tran...
--- +++ @@ -13,11 +13,13 @@ def hf_datasets_augs_helper(examples, transform, image_key, mode='RGB'): + """Apply passed in transforms for HuggingFace Datasets.""" images = [transform(image.convert(mode)) for image in examples[image_key]] return {image_key: images} def append_dims(x, target_dims): +...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/k_diffusion/utils.py
Add docstrings including usage examples
# https://github.com/comfyanonymous/ComfyUI/blob/master/nodes.py #From https://github.com/kornia/kornia import math import torch import torch.nn.functional as F import ldm_patched.modules.model_management def get_canny_nms_kernel(device=None, dtype=None): return torch.tensor( [ [[[0.0, 0.0, ...
--- +++ @@ -8,6 +8,7 @@ import ldm_patched.modules.model_management def get_canny_nms_kernel(device=None, dtype=None): + """Utility function that returns 3x3 kernels for the Canny Non-maximal suppression.""" return torch.tensor( [ [[[0.0, 0.0, 0.0], [0.0, 1.0, -1.0], [0.0, 0.0, 0.0]]], ...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/contrib/external_canny.py
Write docstrings for backend logic
import math from scipy import integrate import torch from torch import nn import torchsde from tqdm.auto import trange, tqdm from . import utils def append_zero(x): return torch.cat([x, x.new_zeros([1])]) def get_sigmas_karras(n, sigma_min, sigma_max, rho=7., device='cpu'): ramp = torch.linspace(0, 1, n, ...
--- +++ @@ -14,6 +14,7 @@ def get_sigmas_karras(n, sigma_min, sigma_max, rho=7., device='cpu'): + """Constructs the noise schedule of Karras et al. (2022).""" ramp = torch.linspace(0, 1, n, device=device) min_inv_rho = sigma_min ** (1 / rho) max_inv_rho = sigma_max ** (1 / rho) @@ -22,27 +23,33 @@...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/k_diffusion/sampling.py
Generate helpful docstrings for debugging
import numpy as np import torch.nn as nn from torch.nn import functional as F class NormLayer(nn.Module): def __init__(self, channels, normalize_shape=None, norm_type='bn'): super(NormLayer, self).__init__() norm_type = norm_type.lower() self.norm_type = norm_type if norm_type == ...
--- +++ @@ -1,9 +1,17 @@+"""Modified from https://github.com/chaofengc/PSFRGAN +""" import numpy as np import torch.nn as nn from torch.nn import functional as F class NormLayer(nn.Module): + """Normalization Layers. + + Args: + channels: input channels, for batch norm and instance norm. + i...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/extras/facexlib/parsing/parsenet.py
Add concise docstrings to each method
import os from transformers import CLIPTokenizer import ldm_patched.modules.ops import torch import traceback import zipfile from . import model_management import ldm_patched.modules.clip_model import json def gen_empty_tokens(special_tokens, length): start_token = special_tokens.get("start", None) end_token ...
--- +++ @@ -59,6 +59,7 @@ return torch.cat(output, dim=-2).to(model_management.intermediate_device()), first_pooled class SDClipModel(torch.nn.Module, ClipTokenWeightEncoder): + """Uses the CLIP transformer encoder for text (from huggingface)""" LAYERS = [ "last", "pooled", @@ -380,...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/modules/sd1_clip.py
Write docstrings for utility functions
import importlib import torch from torch import optim import numpy as np from inspect import isfunction from PIL import Image, ImageDraw, ImageFont def log_txt_as_img(wh, xc, size=10): # wh a tuple of (width, height) # xc a list of captions to plot b = len(xc) txts = list() for bi in range(b): ...
--- +++ @@ -55,6 +55,10 @@ def mean_flat(tensor): + """ + https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/nn.py#L86 + Take the mean over all non-batch dimensions. + """ return tensor.mean(dim=list(range(1, len(tensor.shape)))) @@ -88,6 +...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/ldm/util.py
Replace inline comments with docstrings
import math import torch.nn as nn class CA_layer(nn.Module): def __init__(self, channel, reduction=16): super(CA_layer, self).__init__() # global average pooling self.gap = nn.AdaptiveAvgPool2d(1) self.fc = nn.Sequential( nn.Conv2d(channel, channel // reduction, kernel...
--- +++ @@ -39,6 +39,11 @@ class ECA_layer(nn.Module): + """Constructs a ECA module. + Args: + channel: Number of channels of the input feature map + k_size: Adaptive selection of kernel size + """ def __init__(self, channel): super(ECA_layer, self).__init__() @@ -70,6 +75,11 ...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/pfn/architecture/OmniSR/ChannelAttention.py
Add docstrings to existing functions
# pylint: skip-file # ----------------------------------------------------------------------------------- # SCUNet: Practical Blind Denoising via Swin-Conv-UNet and Data Synthesis, https://arxiv.org/abs/2203.13278 # Zhang, Kai and Li, Yawei and Liang, Jingyun and Cao, Jiezhang and Zhang, Yulun and Tang, Hao and Timofte...
--- +++ @@ -17,6 +17,7 @@ # Borrowed from https://github.com/cszn/SCUNet/blob/main/models/network_scunet.py class WMSA(nn.Module): + """Self-attention module in Swin Transformer""" def __init__(self, input_dim, output_dim, head_dim, window_size, type): super(WMSA, self).__init__() @@ -50,6 +51,12 ...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/pfn/architecture/SCUNet.py
Create simple docstrings for beginners
# pylint: skip-file # HAT from https://github.com/XPixelGroup/HAT/blob/main/hat/archs/hat_arch.py import math import re import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from .timm.helpers import to_2tuple from .timm.weight_init import trunc_normal_ def drop_path(x, dro...
--- +++ @@ -13,6 +13,9 @@ def drop_path(x, drop_prob: float = 0.0, training: bool = False): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). + From: https://github.com/huggingface/pytorch-image-models/blob/main/timm/layers/drop.py + """ if drop_prob == 0.0 ...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/pfn/architecture/HAT.py
Create Google-style docstrings for my code
# pylint: skip-file import math import re import numpy as np import torch import torch.nn as nn import torch.utils.checkpoint as checkpoint from einops import rearrange from einops.layers.torch import Rearrange from torch import Tensor from torch.nn import functional as F from .timm.drop import DropPath from .timm.we...
--- +++ @@ -16,6 +16,10 @@ def img2windows(img, H_sp, W_sp): + """ + Input: Image (B, C, H, W) + Output: Window Partition (B', N, C) + """ B, C, H, W = img.shape img_reshape = img.view(B, C, H // H_sp, H_sp, W // W_sp, W_sp) img_perm = ( @@ -25,6 +29,10 @@ def windows2img(img_splits_h...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/pfn/architecture/DAT.py
Generate docstrings for each module
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import functools import math import re from collections import OrderedDict import torch import torch.nn as nn import torch.nn.functional as F from . import block as B # Borrowed from https://github.com/rlaphoenix/VSGAN/blob/master/vsgan/archs/esrgan.py # Which enhance...
--- +++ @@ -24,6 +24,21 @@ upsampler: str = "upconv", mode: B.ConvMode = "CNA", ) -> None: + """ + ESRGAN - Enhanced Super-Resolution Generative Adversarial Networks. + By Xintao Wang, Ke Yu, Shixiang Wu, Jinjin Gu, Yihao Liu, Chao Dong, Yu Qiao, + and Chen Change Loy. ...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/pfn/architecture/RRDB.py
Add inline docstrings for readability
import torch import torch.nn as nn import torch.nn.functional as F def drop_block_2d( x, drop_prob: float = 0.1, block_size: int = 7, gamma_scale: float = 1.0, with_noise: bool = False, inplace: bool = False, batchwise: bool = False, ): _, C, H, W = x.shape total_size = W * H c...
--- +++ @@ -1,3 +1,19 @@+""" DropBlock, DropPath + +PyTorch implementations of DropBlock and DropPath (Stochastic Depth) regularization layers. + +Papers: +DropBlock: A regularization method for convolutional networks (https://arxiv.org/abs/1810.12890) + +Deep Networks with Stochastic Depth (https://arxiv.org/abs/1603....
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/pfn/architecture/timm/drop.py
Create documentation for each function signature
import math import warnings import torch from torch.nn.init import _calculate_fan_in_and_fan_out def _no_grad_trunc_normal_(tensor, mean, std, a, b): # Cut & paste from PyTorch official master until it's in a few official releases - RW # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/trun...
--- +++ @@ -46,12 +46,54 @@ def trunc_normal_( tensor: torch.Tensor, mean=0.0, std=1.0, a=-2.0, b=2.0 ) -> torch.Tensor: + r"""Fills the input Tensor with values drawn from a truncated + normal distribution. The values are effectively drawn from the + normal distribution :math:`\mathcal{N}(\text{mean}, \...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/pfn/architecture/timm/weight_init.py
Add standardized docstrings across the file
# pylint: skip-file # type: ignore import math import random import torch from torch import nn from .gfpganv1_arch import ResUpBlock from .stylegan2_bilinear_arch import ( ConvLayer, EqualConv2d, EqualLinear, ResBlock, ScaledLeakyReLU, StyleGAN2GeneratorBilinear, ) class StyleGAN2GeneratorBi...
--- +++ @@ -18,6 +18,18 @@ class StyleGAN2GeneratorBilinearSFT(StyleGAN2GeneratorBilinear): + """StyleGAN2 Generator with SFT modulation (Spatial Feature Transform). + It is the bilinear version. It does not use the complicated UpFirDnSmooth function that is not friendly for + deployment. It can be easily ...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/pfn/architecture/face/gfpgan_bilinear_arch.py
Generate documentation strings for clarity
#taken from https://github.com/TencentARC/T2I-Adapter import torch import torch.nn as nn from collections import OrderedDict def conv_nd(dims, *args, **kwargs): if dims == 1: return nn.Conv1d(*args, **kwargs) elif dims == 2: return nn.Conv2d(*args, **kwargs) elif dims == 3: return ...
--- +++ @@ -5,6 +5,9 @@ def conv_nd(dims, *args, **kwargs): + """ + Create a 1D, 2D, or 3D convolution module. + """ if dims == 1: return nn.Conv1d(*args, **kwargs) elif dims == 2: @@ -15,6 +18,9 @@ def avg_pool_nd(dims, *args, **kwargs): + """ + Create a 1D, 2D, or 3D average ...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/t2ia/adapter.py
Write reusable docstrings
# pylint: skip-file # ----------------------------------------------------------------------------------- # Swin2SR: Swin2SR: SwinV2 Transformer for Compressed Image Super-Resolution and Restoration, https://arxiv.org/abs/2209.11345 # Written by Conde and Choi et al. # From: https://raw.githubusercontent.com/mv-lab/swi...
--- +++ @@ -47,6 +47,13 @@ def window_partition(x, window_size): + """ + Args: + x: (B, H, W, C) + window_size (int): window size + Returns: + windows: (num_windows*B, window_size, window_size, C) + """ B, H, W, C = x.shape x = x.view(B, H // window_size, window_size, W //...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/pfn/architecture/Swin2SR.py
Add concise docstrings to each method
#!/usr/bin/env python3 import torch import torch.nn as nn import ldm_patched.modules.utils import ldm_patched.modules.ops def conv(n_in, n_out, **kwargs): return ldm_patched.modules.ops.disable_weight_init.Conv2d(n_in, n_out, 3, padding=1, **kwargs) class Clamp(nn.Module): def forward(self, x): retur...
--- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3 +""" +Tiny AutoEncoder for Stable Diffusion +(DNN for encoding / decoding SD's latent space) +""" import torch import torch.nn as nn @@ -44,6 +48,7 @@ latent_shift = 0.5 def __init__(self, encoder_path=None, decoder_path=None): + """Initialize pretrai...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/taesd/taesd.py
Generate docstrings with parameter types
#code taken from: https://github.com/wl-zhao/UniPC and modified import torch import torch.nn.functional as F import math from tqdm.auto import trange, tqdm class NoiseScheduleVP: def __init__( self, schedule='discrete', betas=None, alphas_cumprod=None, ...
--- +++ @@ -16,6 +16,85 @@ continuous_beta_0=0.1, continuous_beta_1=20., ): + """Create a wrapper class for the forward SDE (VP type). + + *** + Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t. + ...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/unipc/uni_pc.py
Create docstrings for reusable components
import torch import ldm_patched.modules.model_management import ldm_patched.modules.samplers import ldm_patched.modules.conds import ldm_patched.modules.utils import math import numpy as np def prepare_noise(latent_image, seed, noise_inds=None): generator = torch.manual_seed(seed) if noise_inds is None: ...
--- +++ @@ -7,6 +7,10 @@ import numpy as np def prepare_noise(latent_image, seed, noise_inds=None): + """ + creates random noise given a latent image and a seed. + optional arg skip can be used to skip and discard x number of noise generations for a given seed + """ generator = torch.manual_seed(see...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/modules/sample.py
Write docstrings for data processing functions
import math from typing import Optional import torch import torch.nn as nn import torch.nn.functional as F import logging as logger from torch import Tensor class VectorQuantizer(nn.Module): def __init__(self, codebook_size, emb_dim, beta): super(VectorQuantizer, self).__init__() self.codebook_si...
--- +++ @@ -1,3 +1,9 @@+""" +Modified from https://github.com/sczhou/CodeFormer +VQGAN code, adapted from the original created by the Unleashing Transformers authors: +https://github.com/samb-t/unleashing-transformers/blob/master/models/vqgan.py +This version of the arch specifically was gathered from an old version of...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/pfn/architecture/face/codeformer.py
Document functions with clear intent
import torch.nn as nn def conv3x3(inplanes, outplanes, stride=1): return nn.Conv2d( inplanes, outplanes, kernel_size=3, stride=stride, padding=1, bias=False ) class BasicBlock(nn.Module): expansion = 1 # output channel expansion ratio def __init__(self, inplanes, planes, stride=1, downsam...
--- +++ @@ -2,12 +2,27 @@ def conv3x3(inplanes, outplanes, stride=1): + """A simple wrapper for 3x3 convolution with padding. + + Args: + inplanes (int): Channel number of inputs. + outplanes (int): Channel number of outputs. + stride (int): Stride in convolution. Default: 1. + """ ...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/pfn/architecture/face/arcface_arch.py
Add docstrings for production code
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from __future__ import annotations from collections import OrderedDict try: from typing import Literal except ImportError: from typing_extensions import Literal import torch import torch.nn as nn #################### # Basic blocks #################### def ac...
--- +++ @@ -168,6 +168,11 @@ mode: ConvMode = "CNA", c2x2=False, ): + """ + Conv layer with padding, normalization, activation + mode: CNA --> Conv -> Norm -> Act + NAC --> Norm -> Act --> Conv (Identity Mappings in Deep Residual Networks, ECCV16) + """ if c2x2: return conv_...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/pfn/architecture/block.py
Add documentation for all methods
from __future__ import annotations import warnings from pathlib import Path from typing import Any, Literal import numpy as np import PIL import PIL.ImageOps import gradio.routes import importlib from gradio_client import utils as client_utils from gradio_client.documentation import document, set_documentation_grou...
--- +++ @@ -1,3 +1,4 @@+"""gr.Image() component.""" from __future__ import annotations @@ -46,6 +47,14 @@ ImgSerializable, TokenInterpretable, ): + """ + Creates an image component that can be used to upload/draw images (as an input) or display images (as an output). + Preprocessing: passes the ...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/modules/gradio_hijack.py
Document all public functions with docstrings
# pylint: skip-file # ----------------------------------------------------------------------------------- # SwinIR: Image Restoration Using Swin Transformer, https://arxiv.org/abs/2108.10257 # Originally Written by Ze Liu, Modified by Jingyun Liang. # --------------------------------------------------------------------...
--- +++ @@ -45,6 +45,14 @@ def window_partition(x, window_size): + """ + Args: + x: (B, H, W, C) + window_size (int): window size + + Returns: + windows: (num_windows*B, window_size, window_size, C) + """ B, H, W, C = x.shape x = x.view(B, H // window_size, window_size, W ...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/pfn/architecture/SwinIR.py
Generate docstrings with parameter types
# pylint: skip-file # type: ignore import math import random import torch from torch import nn from torch.nn import functional as F from .fused_act import FusedLeakyReLU from .stylegan2_arch import ( ConvLayer, EqualConv2d, EqualLinear, ResBlock, ScaledLeakyReLU, StyleGAN2Generator, ) class ...
--- +++ @@ -19,6 +19,18 @@ class StyleGAN2GeneratorSFT(StyleGAN2Generator): + """StyleGAN2 Generator with SFT modulation (Spatial Feature Transform). + Args: + out_size (int): The spatial size of outputs. + num_style_feat (int): Channel number of style features. Default: 512. + num_mlp (i...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/pfn/architecture/face/gfpganv1_arch.py
Write docstrings describing each step
# pylint: skip-file # type: ignore import math import random import torch from torch import nn from torch.nn import functional as F from .stylegan2_clean_arch import StyleGAN2GeneratorClean class StyleGAN2GeneratorCSFT(StyleGAN2GeneratorClean): def __init__( self, out_size, num_style_fe...
--- +++ @@ -11,6 +11,16 @@ class StyleGAN2GeneratorCSFT(StyleGAN2GeneratorClean): + """StyleGAN2 Generator with SFT modulation (Spatial Feature Transform). + It is the clean version without custom compiled CUDA extensions used in StyleGAN2. + Args: + out_size (int): The spatial size of outputs. + ...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/pfn/architecture/face/gfpganv1_clean_arch.py
Document this module using docstrings
# pylint: skip-file # type: ignore import math import random import torch from torch import nn from torch.nn import functional as F from .fused_act import FusedLeakyReLU, fused_leaky_relu from .upfirdn2d import upfirdn2d class NormStyleCode(nn.Module): def forward(self, x): return x * torch.rsqrt(torch....
--- +++ @@ -13,10 +13,26 @@ class NormStyleCode(nn.Module): def forward(self, x): + """Normalize the style codes. + + Args: + x (Tensor): Style codes with shape (b, c). + + Returns: + Tensor: Normalized tensor. + """ return x * torch.rsqrt(torch.mean(x**...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/pfn/architecture/face/stylegan2_arch.py
Write docstrings describing functionality
# pylint: skip-file # type: ignore import math import random import torch from torch import nn from torch.nn import functional as F from .fused_act import FusedLeakyReLU, fused_leaky_relu class NormStyleCode(nn.Module): def forward(self, x): return x * torch.rsqrt(torch.mean(x**2, dim=1, keepdim=True) +...
--- +++ @@ -12,10 +12,27 @@ class NormStyleCode(nn.Module): def forward(self, x): + """Normalize the style codes. + Args: + x (Tensor): Style codes with shape (b, c). + Returns: + Tensor: Normalized tensor. + """ return x * torch.rsqrt(torch.mean(x**2, d...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/pfn/architecture/face/stylegan2_bilinear_arch.py
Fill in missing docstrings in my code
from pathlib import Path import numpy as np import datetime import random import math import os import cv2 import re from typing import List, Tuple, AnyStr, NamedTuple import json import hashlib from PIL import Image import modules.config import modules.sdxl_styles from modules.flags import Performance LANCZOS = (...
--- +++ @@ -44,6 +44,18 @@ def resize_image(im, width, height, resize_mode=1): + """ + Resizes an image with the specified resize_mode, width, and height. + + Args: + resize_mode: The mode to use when resizing the image. + 0: Resize the image to the specified width and height. + ...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/modules/util.py
Add standardized docstrings across the file
# pylint: skip-file # type: ignore import math import torch from torch import nn from torch.nn import functional as F from torch.nn import init from torch.nn.modules.batchnorm import _BatchNorm @torch.no_grad() def default_init_weights(module_list, scale=1, bias_fill=0, **kwargs): if not isinstance(module_list, ...
--- +++ @@ -11,6 +11,14 @@ @torch.no_grad() def default_init_weights(module_list, scale=1, bias_fill=0, **kwargs): + """Initialize network weights. + Args: + module_list (list[nn.Module] | nn.Module): Modules to be initialized. + scale (float): Scale initialized weights, especially for residual +...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/pfn/architecture/face/stylegan2_clean_arch.py
Add docstrings to existing functions
# pylint: skip-file # type: ignore import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class VectorQuantizer(nn.Module): def __init__(self, n_e, e_dim, beta): super(VectorQuantizer, self).__init__() self.n_e = n_e self.e_dim = e_dim self.beta = be...
--- +++ @@ -1,5 +1,7 @@ # pylint: skip-file # type: ignore +"""Modified from https://github.com/wzhouxiff/RestoreFormer +""" import numpy as np import torch import torch.nn as nn @@ -7,6 +9,16 @@ class VectorQuantizer(nn.Module): + """ + see https://github.com/MishaLaskin/vqvae/blob/d761a999e2267766400dc6...
https://raw.githubusercontent.com/lllyasviel/Fooocus/HEAD/ldm_patched/pfn/architecture/face/restoreformer_arch.py
Generate docstrings with parameter types
import json import os import pprint import re import socket import subprocess import sys import threading import time from pathlib import Path from typing import Any, List import llama_cpp_binaries import requests from modules import shared from modules.image_utils import ( convert_image_attachments_to_pil, c...
--- +++ @@ -27,6 +27,9 @@ class LlamaServer: def __init__(self, model_path, server_path=None): + """ + Initialize and start a server for llama.cpp models. + """ self.model_path = model_path self.server_path = server_path self.port = self._find_available_port() @@ -...
https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/llama_cpp_server.py
Generate docstrings for each module
import base64 import io import re import time from datetime import date from pathlib import Path import gradio as gr import requests import torch from PIL import Image from modules import shared from modules.models import load_model, unload_model from modules.ui import create_refresh_button torch._C._jit_set_profili...
--- +++ @@ -107,6 +107,10 @@ def input_modifier(string): + """ + This function is applied to your text inputs before + they are fed into the model. + """ global params @@ -189,6 +193,9 @@ # TODO: how do I make the UI history ignore the resulting pictures (I don't want HTML to appear in history)...
https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/extensions/sd_api_pictures/script.py
Improve my code by adding docstrings
import base64 import io import os from pathlib import Path from typing import Any, List, Tuple from PIL import Image from modules.logging_colors import logger def open_image_safely(path): if path is None or not isinstance(path, str) or not Path(path).exists(): return None if os.path.islink(path): ...
--- +++ @@ -24,6 +24,7 @@ def convert_pil_to_base64(image: Image.Image) -> str: + """Converts a PIL Image to a base64 encoded string.""" buffered = io.BytesIO() # Save image to an in-memory bytes buffer in PNG format image.save(buffered, format="PNG") @@ -32,6 +33,7 @@ def decode_base64_image(...
https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/image_utils.py
Annotate my code with docstrings
import bisect import re from datetime import datetime import extensions.superboogav2.parameters as parameters from .chromadb import ChromaCollector from .data_preprocessor import TextPreprocessorBuilder, TextSummarizer def preprocess_text_no_summary(text) -> str: builder = TextPreprocessorBuilder(text) if ...
--- +++ @@ -1,3 +1,8 @@+""" +This module is responsible for processing the corpus and feeding it into chromaDB. It will receive a corpus of text. +It will then split it into chunks of specified length. For each of those chunks, it will append surrounding context. +It will only include full words. +""" import bisect ...
https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/extensions/superboogav2/data_processor.py
Generate consistent documentation across files
import html import gradio as gr from deep_translator import GoogleTranslator params = { "activate": True, "language string": "ja", } language_codes = {'Afrikaans': 'af', 'Albanian': 'sq', 'Amharic': 'am', 'Arabic': 'ar', 'Armenian': 'hy', 'Azerbaijani': 'az', 'Basque': 'eu', 'Belarusian': 'be', 'Bengali': 'b...
--- +++ @@ -12,6 +12,10 @@ def input_modifier(string): + """ + This function is applied to your text inputs before + they are fed into the model. + """ if not params['activate']: return string @@ -19,6 +23,9 @@ def output_modifier(string): + """ + This function is applied to th...
https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/extensions/google_translate/script.py
Write docstrings for backend logic
import ast import copy import html import pprint import random import time import traceback import numpy as np import modules.shared as shared from modules import models from modules.callbacks import Iteratorize from modules.extensions import apply_extensions from modules.html_generator import generate_basic_html fro...
--- +++ @@ -206,6 +206,9 @@ def generate_reply_wrapper(question, state, stopping_strings=None): + """ + Returns formatted outputs for the UI + """ reply = question if not shared.is_seq2seq else '' yield formatted_outputs(reply, shared.model_name) @@ -484,6 +487,9 @@ def generate_reply_custo...
https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/text_generation.py
Create simple docstrings for beginners
import time import modules.shared as shared from modules.logging_colors import logger from modules.utils import resolve_model_path def get_quantization_config(quant_method): import torch # Import BitsAndBytesConfig from BOTH libraries to be safe from diffusers import BitsAndBytesConfig as DiffusersBnBCon...
--- +++ @@ -6,6 +6,10 @@ def get_quantization_config(quant_method): + """ + Get the appropriate quantization config based on the selected method. + Applies quantization to both the transformer and the text_encoder. + """ import torch # Import BitsAndBytesConfig from BOTH libraries to be safe ...
https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/image_models.py
Add return value explanations in docstrings
import math import queue import threading import traceback from pathlib import Path from typing import Any, List, Tuple import torch from exllamav3 import Cache, Config, Generator, Model, Tokenizer from exllamav3.cache import CacheLayer_fp16, CacheLayer_quant from exllamav3.generator import Job from exllamav3.generat...
--- +++ @@ -39,6 +39,7 @@ class LogitBiasFilter(Filter): + """Filter subclass that applies a static additive logit bias mask.""" def __init__(self, tokenizer, logit_bias_dict): super().__init__(tokenizer=tokenizer, trigger_token=None, prefix_str=None, eos_after_completed=False) @@ -254,9 +255,14 ...
https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/exllamav3.py
Add docstrings following best practices
# Code based on the Sane List Extension for Python-Markdown # ======================================= # Modify the behavior of Lists in Python-Markdown to act in a sane manner. # See https://Python-Markdown.github.io/extensions/sane_lists # for documentation. # Original code Copyright 2011 [Waylan Limberg](http://ac...
--- +++ @@ -12,6 +12,9 @@ # License: [BSD](https://opensource.org/licenses/bsd-license.php) +""" +Modify the behavior of Lists in Python-Markdown to act in a sane manner. +""" from __future__ import annotations @@ -37,6 +40,16 @@ class SaneListIndentProcessor(ListIndentProcessor): + """ Process children...
https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/sane_markdown_lists.py
Add inline docstrings for readability
import copy import threading from pathlib import Path import gradio as gr import yaml import extensions import modules.extensions as extensions_module from modules import shared from modules.chat import load_history from modules.utils import gradio # Global state for auto-saving UI settings with debouncing _auto_sav...
--- +++ @@ -363,6 +363,7 @@ def store_current_state_and_debounce(interface_state, preset, extensions, show_controls, theme_state): + """Store current state and trigger debounced save""" global _auto_save_timer, _last_interface_state, _last_preset, _last_extensions, _last_show_controls, _last_theme_state ...
https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/ui.py