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(__name__) router = APIRouter(prefix="/ollama") class ModelRequest(BaseModel): model_name: str class OllamaStatusResponse(BaseModel): installed: bool running: bool available_models: List[str] server_url: str error: str | None = None class ActionResponse(BaseModel): success: bool message: str class RecommendedModel(BaseModel): display_name: str model_name: str provider: str class ProgressResponse(BaseModel): status: str percentage: float | None = None message: str | None = None phase: str | None = None bytes_downloaded: int | None = None total_bytes: int | None = None @router.get( "/status", response_model=OllamaStatusResponse, responses={ 500: {"model": ErrorResponse, "description": "Internal server error"}, }, ) async def get_ollama_status(): try: status = await ollama_service.check_ollama_status() return OllamaStatusResponse(**status) except Exception as e: logger.error(f"Failed to check Ollama status: {e}") raise HTTPException(status_code=500, detail=f"Failed to check Ollama status: {str(e)}") @router.post( "/start", response_model=ActionResponse, responses={ 400: {"model": ErrorResponse, "description": "Bad request"}, 500: {"model": ErrorResponse, "description": "Internal server error"}, }, ) async def start_ollama_server(): try: # First check if it's already running status = await ollama_service.check_ollama_status() if not status["installed"]: raise HTTPException(status_code=400, detail="Ollama is not installed on this system") if status["running"]: return ActionResponse(success=True, message="Ollama server is already running") result = await ollama_service.start_server() if not result["success"]: logger.error(f"Failed to start Ollama server: {result['message']}") raise HTTPException(status_code=500, detail=result["message"]) return ActionResponse(**result) except HTTPException: raise except Exception as e: logger.error(f"Unexpected error starting Ollama server: {e}") raise HTTPException(status_code=500, detail=f"Failed to start Ollama server: {str(e)}") @router.post( "/stop", response_model=ActionResponse, responses={ 400: {"model": ErrorResponse, "description": "Bad request"}, 500: {"model": ErrorResponse, "description": "Internal server error"}, }, ) async def stop_ollama_server(): try: # First check if it's installed status = await ollama_service.check_ollama_status() if not status["installed"]: raise HTTPException(status_code=400, detail="Ollama is not installed on this system") if not status["running"]: return ActionResponse(success=True, message="Ollama server is already stopped") result = await ollama_service.stop_server() if not result["success"]: logger.error(f"Failed to stop Ollama server: {result['message']}") raise HTTPException(status_code=500, detail=result["message"]) return ActionResponse(**result) except HTTPException: raise except Exception as e: logger.error(f"Unexpected error stopping Ollama server: {e}") raise HTTPException(status_code=500, detail=f"Failed to stop Ollama server: {str(e)}") @router.post( "/models/download", response_model=ActionResponse, responses={ 400: {"model": ErrorResponse, "description": "Bad request"}, 500: {"model": ErrorResponse, "description": "Internal server error"}, }, ) async def download_model(request: ModelRequest): try: logger.info(f"Download request for model: {request.model_name}") # Check current status status = await ollama_service.check_ollama_status() logger.debug(f"Current Ollama status: installed={status['installed']}, running={status['running']}") if not status["installed"]: raise HTTPException(status_code=400, detail="Ollama is not installed on this system") if not status["running"]: raise HTTPException(status_code=400, detail="Ollama server is not running. Please start it first.") result = await ollama_service.download_model(request.model_name) if not result["success"]: logger.error(f"Failed to download model {request.model_name}: {result['message']}") raise HTTPException(status_code=500, detail=result["message"]) logger.info(f"Successfully downloaded model: {request.model_name}") return ActionResponse(**result) except HTTPException: raise except Exception as e: logger.error(f"Unexpected error downloading model {request.model_name}: {e}") raise HTTPException(status_code=500, detail=f"Failed to download model: {str(e)}") @router.post( "/models/download/progress", responses={ 400: {"model": ErrorResponse, "description": "Bad request"}, 500: {"model": ErrorResponse, "description": "Internal server error"}, }, ) async def download_model_with_progress(request: ModelRequest): try: logger.info(f"Progress download request for model: {request.model_name}") # Check current status status = await ollama_service.check_ollama_status() logger.debug(f"Current Ollama status: installed={status['installed']}, running={status['running']}") if not status["installed"]: raise HTTPException(status_code=400, detail="Ollama is not installed on this system") if not status["running"]: raise HTTPException(status_code=400, detail="Ollama server is not running. Please start it first.") # Return Server-Sent Events stream return StreamingResponse( ollama_service.download_model_with_progress(request.model_name), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "*", } ) except HTTPException: raise except Exception as e: logger.error(f"Unexpected error setting up progress download for {request.model_name}: {e}") raise HTTPException(status_code=500, detail=f"Failed to start progress download: {str(e)}") @router.get( "/models/download/progress/{model_name}", response_model=ProgressResponse, responses={ 404: {"model": ErrorResponse, "description": "Model download not found"}, 500: {"model": ErrorResponse, "description": "Internal server error"}, }, ) async def get_download_progress(model_name: str): try: progress = ollama_service.get_download_progress(model_name) if progress is None: raise HTTPException(status_code=404, detail=f"No active download found for model: {model_name}") return ProgressResponse(**progress) except HTTPException: raise except Exception as e: logger.error(f"Error getting download progress for {model_name}: {e}") raise HTTPException(status_code=500, detail=f"Failed to get download progress: {str(e)}") @router.get( "/models/downloads/active", response_model=Dict[str, ProgressResponse], responses={ 500: {"model": ErrorResponse, "description": "Internal server error"}, }, ) async def get_active_downloads(): try: active_downloads = {} all_progress = ollama_service.get_all_download_progress() # Only return downloads that are actually active (not completed, error, or cancelled) for model_name, progress in all_progress.items(): if progress.get("status") in ["starting", "downloading"]: active_downloads[model_name] = ProgressResponse(**progress) return active_downloads except Exception as e: logger.error(f"Error getting active downloads: {e}") raise HTTPException(status_code=500, detail=f"Failed to get active downloads: {str(e)}") @router.delete( "/models/{model_name}", response_model=ActionResponse, responses={ 400: {"model": ErrorResponse, "description": "Bad request"}, 500: {"model": ErrorResponse, "description": "Internal server error"}, }, ) async def delete_model(model_name: str): try: logger.info(f"Delete request for model: {model_name}") # Check current status status = await ollama_service.check_ollama_status() logger.debug(f"Current Ollama status: installed={status['installed']}, running={status['running']}") if not status["installed"]: raise HTTPException(status_code=400, detail="Ollama is not installed on this system") if not status["running"]: raise HTTPException(status_code=400, detail="Ollama server is not running. Please start it first.") result = await ollama_service.delete_model(model_name) if not result["success"]: logger.error(f"Failed to delete model {model_name}: {result['message']}") raise HTTPException(status_code=500, detail=result["message"]) logger.info(f"Successfully deleted model: {model_name}") return ActionResponse(**result) except HTTPException: raise except Exception as e: logger.error(f"Unexpected error deleting model {model_name}: {e}") raise HTTPException(status_code=500, detail=f"Failed to delete model: {str(e)}") @router.get( "/models/recommended", response_model=List[RecommendedModel], responses={ 500: {"model": ErrorResponse, "description": "Internal server error"}, }, ) async def get_recommended_models(): try: models = await ollama_service.get_recommended_models() return [RecommendedModel(**model) for model in models] except Exception as e: logger.error(f"Failed to get recommended models: {e}") raise HTTPException(status_code=500, detail=f"Failed to get recommended models: {str(e)}") @router.delete( "/models/download/{model_name}", response_model=ActionResponse, responses={ 404: {"model": ErrorResponse, "description": "Download not found"}, 500: {"model": ErrorResponse, "description": "Internal server error"}, }, ) async def cancel_download(model_name: str): try: logger.info(f"Cancel download request for model: {model_name}") success = ollama_service.cancel_download(model_name) if success: return ActionResponse(success=True, message=f"Download cancelled for {model_name}") else: raise HTTPException(status_code=404, detail=f"No active download found for model: {model_name}") except HTTPException: raise except Exception as e: logger.error(f"Unexpected error cancelling download for {model_name}: {e}") raise HTTPException(status_code=500, detail=f"Failed to cancel download: {str(e)}")
--- +++ @@ -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 Ollama server.""" try: # First check if it's already running status = await ollama_service.check_ollama_status() @@ -93,6 +95,7 @@ }, ) async def stop_ollama_server(): + """Stop the Ollama server.""" try: # First check if it's installed status = await ollama_service.check_ollama_status() @@ -124,6 +127,7 @@ }, ) async def download_model(request: ModelRequest): + """Download an Ollama model (legacy endpoint).""" try: logger.info(f"Download request for model: {request.model_name}") @@ -159,6 +163,7 @@ }, ) async def download_model_with_progress(request: ModelRequest): + """Download an Ollama model with real-time progress updates via Server-Sent Events.""" try: logger.info(f"Progress download request for model: {request.model_name}") @@ -198,6 +203,7 @@ }, ) async def get_download_progress(model_name: str): + """Get current download progress for a specific model.""" try: progress = ollama_service.get_download_progress(model_name) if progress is None: @@ -218,6 +224,7 @@ }, ) async def get_active_downloads(): + """Get all currently active model downloads.""" try: active_downloads = {} all_progress = ollama_service.get_all_download_progress() @@ -241,6 +248,7 @@ }, ) async def delete_model(model_name: str): + """Delete an Ollama model.""" try: logger.info(f"Delete request for model: {model_name}") @@ -276,6 +284,7 @@ }, ) async def get_recommended_models(): + """Get list of recommended Ollama models.""" try: models = await ollama_service.get_recommended_models() return [RecommendedModel(**model) for model in models] @@ -292,6 +301,7 @@ }, ) async def cancel_download(model_name: str): + """Cancel an active model download.""" try: logger.info(f"Cancel download request for model: {model_name}")
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, max_retries: int = 3, default_factory=None, ) -> BaseModel: # Extract model configuration if state is provided and agent_name is available if state and agent_name: model_name, model_provider = get_agent_model_config(state, agent_name) else: # Use system defaults when no state or agent_name is provided model_name = "gpt-4.1" model_provider = "OPENAI" # Extract API keys from state if available api_keys = None if state: request = state.get("metadata", {}).get("request") if request and hasattr(request, 'api_keys'): api_keys = request.api_keys model_info = get_model_info(model_name, model_provider) llm = get_model(model_name, model_provider, api_keys) # For non-JSON support models, we can use structured output if not (model_info and not model_info.has_json_mode()): llm = llm.with_structured_output( pydantic_model, method="json_mode", ) # Call the LLM with retries for attempt in range(max_retries): try: # Call the LLM result = llm.invoke(prompt) # For non-JSON support models, we need to extract and parse the JSON manually if model_info and not model_info.has_json_mode(): parsed_result = extract_json_from_response(result.content) if parsed_result: return pydantic_model(**parsed_result) else: return result except Exception as e: if agent_name: progress.update_status(agent_name, None, f"Error - retry {attempt + 1}/{max_retries}") if attempt == max_retries - 1: print(f"Error in LLM call after {max_retries} attempts: {e}") # Use default_factory if provided, otherwise create a basic default if default_factory: return default_factory() return create_default_response(pydantic_model) # This should never be reached due to the retry logic above return create_default_response(pydantic_model) def create_default_response(model_class: type[BaseModel]) -> BaseModel: default_values = {} for field_name, field in model_class.model_fields.items(): if field.annotation == str: default_values[field_name] = "Error in analysis, using default" elif field.annotation == float: default_values[field_name] = 0.0 elif field.annotation == int: default_values[field_name] = 0 elif hasattr(field.annotation, "__origin__") and field.annotation.__origin__ == dict: default_values[field_name] = {} else: # For other types (like Literal), try to use the first allowed value if hasattr(field.annotation, "__args__"): default_values[field_name] = field.annotation.__args__[0] else: default_values[field_name] = None return model_class(**default_values) def extract_json_from_response(content: str) -> dict | None: try: json_start = content.find("```json") if json_start != -1: json_text = content[json_start + 7 :] # Skip past ```json json_end = json_text.find("```") if json_end != -1: json_text = json_text[:json_end].strip() return json.loads(json_text) except Exception as e: print(f"Error extracting JSON from response: {e}") return None def get_agent_model_config(state, agent_name): request = state.get("metadata", {}).get("request") if request and hasattr(request, 'get_agent_model_config'): # Get agent-specific model configuration model_name, model_provider = request.get_agent_model_config(agent_name) # Ensure we have valid values if model_name and model_provider: return model_name, model_provider.value if hasattr(model_provider, 'value') else str(model_provider) # Fall back to global configuration (system defaults) model_name = state.get("metadata", {}).get("model_name") or "gpt-4.1" model_provider = state.get("metadata", {}).get("model_provider") or "OPENAI" # Convert enum to string if necessary if hasattr(model_provider, 'value'): model_provider = model_provider.value return model_name, model_provider
--- +++ @@ -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: + prompt: The prompt to send to the LLM + pydantic_model: The Pydantic model class to structure the output + agent_name: Optional name of the agent for progress updates and model config extraction + state: Optional state object to extract agent-specific model configuration + max_retries: Maximum number of retries (default: 3) + default_factory: Optional factory function to create default response on failure + + Returns: + An instance of the specified Pydantic model + """ # Extract model configuration if state is provided and agent_name is available if state and agent_name: @@ -70,6 +85,7 @@ def create_default_response(model_class: type[BaseModel]) -> BaseModel: + """Creates a safe default response based on the model's fields.""" default_values = {} for field_name, field in model_class.model_fields.items(): if field.annotation == str: @@ -91,6 +107,7 @@ def extract_json_from_response(content: str) -> dict | None: + """Extracts JSON from markdown-formatted response.""" try: json_start = content.find("```json") if json_start != -1: @@ -105,6 +122,11 @@ def get_agent_model_config(state, agent_name): + """ + Get model configuration for a specific agent from the state. + Falls back to global model configuration if agent-specific config is not available. + Always returns valid model_name and model_provider values. + """ request = state.get("metadata", {}).get("request") if request and hasattr(request, 'get_agent_model_config'): @@ -122,4 +144,4 @@ if hasattr(model_provider, 'value'): model_provider = model_provider.value - return model_name, model_provider+ return model_name, model_provider
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 = { "today": 0, "yesterday": 1, } # 日期范围表达式(用于 resolve_date_range_expression) RANGE_EXPRESSIONS = { # 中文表达式 "今天": "today", "昨天": "yesterday", "本周": "this_week", "这周": "this_week", "当前周": "this_week", "上周": "last_week", "本月": "this_month", "这个月": "this_month", "当前月": "this_month", "上月": "last_month", "上个月": "last_month", "最近3天": "last_3_days", "近3天": "last_3_days", "最近7天": "last_7_days", "近7天": "last_7_days", "最近一周": "last_7_days", "过去一周": "last_7_days", "最近14天": "last_14_days", "近14天": "last_14_days", "最近两周": "last_14_days", "过去两周": "last_14_days", "最近30天": "last_30_days", "近30天": "last_30_days", "最近一个月": "last_30_days", "过去一个月": "last_30_days", # 英文表达式 "today": "today", "yesterday": "yesterday", "this week": "this_week", "current week": "this_week", "last week": "last_week", "this month": "this_month", "current month": "this_month", "last month": "last_month", "last 3 days": "last_3_days", "past 3 days": "last_3_days", "last 7 days": "last_7_days", "past 7 days": "last_7_days", "past week": "last_7_days", "last 14 days": "last_14_days", "past 14 days": "last_14_days", "last 30 days": "last_30_days", "past 30 days": "last_30_days", "past month": "last_30_days", } # 星期映射 WEEKDAY_CN = { "一": 0, "二": 1, "三": 2, "四": 3, "五": 4, "六": 5, "日": 6, "天": 6 } WEEKDAY_EN = { "monday": 0, "tuesday": 1, "wednesday": 2, "thursday": 3, "friday": 4, "saturday": 5, "sunday": 6 } @staticmethod def parse_date_query(date_query: str) -> datetime: if not date_query or not isinstance(date_query, str): raise InvalidParameterError( "日期查询字符串不能为空", suggestion="请提供有效的日期查询,如:今天、昨天、2025-10-10" ) date_query = date_query.strip().lower() # 1. 尝试解析中文常用相对日期 if date_query in DateParser.CN_DATE_MAPPING: days_ago = DateParser.CN_DATE_MAPPING[date_query] return datetime.now() - timedelta(days=days_ago) # 2. 尝试解析英文常用相对日期 if date_query in DateParser.EN_DATE_MAPPING: days_ago = DateParser.EN_DATE_MAPPING[date_query] return datetime.now() - timedelta(days=days_ago) # 3. 尝试解析 "N天前" 或 "N days ago" cn_days_ago_match = re.match(r'(\d+)\s*天前', date_query) if cn_days_ago_match: days = int(cn_days_ago_match.group(1)) if days > 365: raise InvalidParameterError( f"天数过大: {days}天", suggestion="请使用小于365天的相对日期或使用绝对日期" ) return datetime.now() - timedelta(days=days) en_days_ago_match = re.match(r'(\d+)\s*days?\s+ago', date_query) if en_days_ago_match: days = int(en_days_ago_match.group(1)) if days > 365: raise InvalidParameterError( f"天数过大: {days}天", suggestion="请使用小于365天的相对日期或使用绝对日期" ) return datetime.now() - timedelta(days=days) # 4. 尝试解析星期(中文):上周一、本周三 cn_weekday_match = re.match(r'(上|本)周([一二三四五六日天])', date_query) if cn_weekday_match: week_type = cn_weekday_match.group(1) # 上 或 本 weekday_str = cn_weekday_match.group(2) target_weekday = DateParser.WEEKDAY_CN[weekday_str] return DateParser._get_date_by_weekday(target_weekday, week_type == "上") # 5. 尝试解析星期(英文):last monday、this friday en_weekday_match = re.match(r'(last|this)\s+(monday|tuesday|wednesday|thursday|friday|saturday|sunday)', date_query) if en_weekday_match: week_type = en_weekday_match.group(1) # last 或 this weekday_str = en_weekday_match.group(2) target_weekday = DateParser.WEEKDAY_EN[weekday_str] return DateParser._get_date_by_weekday(target_weekday, week_type == "last") # 6. 尝试解析绝对日期:YYYY-MM-DD iso_date_match = re.match(r'(\d{4})-(\d{1,2})-(\d{1,2})', date_query) if iso_date_match: year = int(iso_date_match.group(1)) month = int(iso_date_match.group(2)) day = int(iso_date_match.group(3)) try: return datetime(year, month, day) except ValueError as e: raise InvalidParameterError( f"无效的日期: {date_query}", suggestion=f"日期值错误: {str(e)}" ) # 7. 尝试解析中文日期:MM月DD日 或 YYYY年MM月DD日 cn_date_match = re.match(r'(?:(\d{4})年)?(\d{1,2})月(\d{1,2})日', date_query) if cn_date_match: year_str = cn_date_match.group(1) month = int(cn_date_match.group(2)) day = int(cn_date_match.group(3)) # 如果没有年份,使用当前年份 if year_str: year = int(year_str) else: year = datetime.now().year # 如果月份大于当前月份,说明是去年 current_month = datetime.now().month if month > current_month: year -= 1 try: return datetime(year, month, day) except ValueError as e: raise InvalidParameterError( f"无效的日期: {date_query}", suggestion=f"日期值错误: {str(e)}" ) # 8. 尝试解析斜杠格式:YYYY/MM/DD 或 MM/DD slash_date_match = re.match(r'(?:(\d{4})/)?(\d{1,2})/(\d{1,2})', date_query) if slash_date_match: year_str = slash_date_match.group(1) month = int(slash_date_match.group(2)) day = int(slash_date_match.group(3)) if year_str: year = int(year_str) else: year = datetime.now().year current_month = datetime.now().month if month > current_month: year -= 1 try: return datetime(year, month, day) except ValueError as e: raise InvalidParameterError( f"无效的日期: {date_query}", suggestion=f"日期值错误: {str(e)}" ) # 如果所有格式都不匹配 raise InvalidParameterError( f"无法识别的日期格式: {date_query}", suggestion=( "支持的格式:\n" "- 相对日期: 今天、昨天、前天、3天前、today、yesterday、3 days ago\n" "- 星期: 上周一、本周三、last monday、this friday\n" "- 绝对日期: 2025-10-10、10月10日、2025年10月10日" ) ) @staticmethod def _get_date_by_weekday(target_weekday: int, is_last_week: bool) -> datetime: today = datetime.now() current_weekday = today.weekday() # 计算天数差 if is_last_week: # 上周的某一天 days_diff = current_weekday - target_weekday + 7 else: # 本周的某一天 days_diff = current_weekday - target_weekday if days_diff < 0: days_diff += 7 return today - timedelta(days=days_diff) @staticmethod def format_date_folder(date: datetime) -> str: return date.strftime("%Y-%m-%d") @staticmethod def validate_date_not_future(date: datetime) -> None: if date.date() > datetime.now().date(): raise InvalidParameterError( f"不能查询未来的日期: {date.strftime('%Y-%m-%d')}", suggestion="请使用今天或过去的日期" ) @staticmethod def validate_date_not_too_old(date: datetime, max_days: int = 365) -> None: days_ago = (datetime.now().date() - date.date()).days if days_ago > max_days: raise InvalidParameterError( f"日期太久远: {date.strftime('%Y-%m-%d')} ({days_ago}天前)", suggestion=f"请查询{max_days}天内的数据" ) @staticmethod def resolve_date_range_expression(expression: str) -> Dict: if not expression or not isinstance(expression, str): raise InvalidParameterError( "日期表达式不能为空", suggestion="请提供有效的日期表达式,如:本周、最近7天、last week" ) expression_lower = expression.strip().lower() today = datetime.now() today_str = today.strftime("%Y-%m-%d") # 1. 尝试匹配预定义表达式 normalized = DateParser.RANGE_EXPRESSIONS.get(expression_lower) # 2. 尝试匹配动态 "最近N天" / "last N days" 模式 if not normalized: # 中文: 最近N天 cn_match = re.match(r'最近(\d+)天', expression_lower) if cn_match: days = int(cn_match.group(1)) normalized = f"last_{days}_days" # 英文: last N days en_match = re.match(r'(?:last|past)\s+(\d+)\s+days?', expression_lower) if en_match: days = int(en_match.group(1)) normalized = f"last_{days}_days" if not normalized: # 提供支持的表达式列表 supported_cn = ["今天", "昨天", "本周", "上周", "本月", "上月", "最近7天", "最近30天", "最近N天"] supported_en = ["today", "yesterday", "this week", "last week", "this month", "last month", "last 7 days", "last N days"] raise InvalidParameterError( f"无法识别的日期表达式: {expression}", suggestion=f"支持的表达式:\n中文: {', '.join(supported_cn)}\n英文: {', '.join(supported_en)}" ) # 3. 根据 normalized 类型计算日期范围 start_date, end_date, description = DateParser._calculate_date_range( normalized, today ) return { "success": True, "expression": expression, "normalized": normalized, "date_range": { "start": start_date.strftime("%Y-%m-%d"), "end": end_date.strftime("%Y-%m-%d") }, "current_date": today_str, "description": description } @staticmethod def _calculate_date_range( normalized: str, today: datetime ) -> Tuple[datetime, datetime, str]: # 单日类型 if normalized == "today": return today, today, "今天" if normalized == "yesterday": yesterday = today - timedelta(days=1) return yesterday, yesterday, "昨天" # 本周(周一到周日) if normalized == "this_week": # 计算本周一 weekday = today.weekday() # 0=周一, 6=周日 start = today - timedelta(days=weekday) end = start + timedelta(days=6) # 如果本周还没结束,end 不能超过今天 if end > today: end = today return start, end, f"本周(周一到周日,{start.strftime('%m-%d')} 至 {end.strftime('%m-%d')})" # 上周(上周一到上周日) if normalized == "last_week": weekday = today.weekday() # 本周一 this_monday = today - timedelta(days=weekday) # 上周一 start = this_monday - timedelta(days=7) end = start + timedelta(days=6) return start, end, f"上周({start.strftime('%m-%d')} 至 {end.strftime('%m-%d')})" # 本月(本月1日到今天) if normalized == "this_month": start = today.replace(day=1) return start, today, f"本月({start.strftime('%m-%d')} 至 {today.strftime('%m-%d')})" # 上月(上月1日到上月最后一天) if normalized == "last_month": # 上月最后一天 = 本月1日 - 1天 first_of_this_month = today.replace(day=1) end = first_of_this_month - timedelta(days=1) start = end.replace(day=1) return start, end, f"上月({start.strftime('%Y-%m-%d')} 至 {end.strftime('%Y-%m-%d')})" # 最近N天 (last_N_days 格式) match = re.match(r'last_(\d+)_days', normalized) if match: days = int(match.group(1)) start = today - timedelta(days=days - 1) # 包含今天,所以是 days-1 return start, today, f"最近{days}天({start.strftime('%m-%d')} 至 {today.strftime('%m-%d')})" # 兜底:返回今天 return today, today, "今天(默认)" @staticmethod def get_supported_expressions() -> Dict[str, list]: return { "单日": ["今天", "昨天", "today", "yesterday"], "周": ["本周", "上周", "this week", "last week"], "月": ["本月", "上月", "this month", "last month"], "最近N天": ["最近3天", "最近7天", "最近14天", "最近30天", "last 3 days", "last 7 days", "last 14 days", "last 30 days"], "动态天数": ["最近N天", "last N days"] }
--- +++ @@ -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: + """ + 解析日期查询字符串 + + 支持的格式: + - 相对日期(中文):今天、昨天、前天、大前天、N天前 + - 相对日期(英文):today、yesterday、N days ago + - 星期(中文):上周一、上周二、本周三 + - 星期(英文):last monday、this friday + - 绝对日期:2025-10-10、10月10日、2025年10月10日 + + Args: + date_query: 日期查询字符串 + + Returns: + datetime对象 + + Raises: + InvalidParameterError: 日期格式无法识别 + + Examples: + >>> DateParser.parse_date_query("今天") + datetime(2025, 10, 11) + >>> DateParser.parse_date_query("昨天") + datetime(2025, 10, 10) + >>> DateParser.parse_date_query("3天前") + datetime(2025, 10, 8) + >>> DateParser.parse_date_query("2025-10-10") + datetime(2025, 10, 10) + """ if not date_query or not isinstance(date_query, str): raise InvalidParameterError( "日期查询字符串不能为空", @@ -214,6 +249,16 @@ @staticmethod def _get_date_by_weekday(target_weekday: int, is_last_week: bool) -> datetime: + """ + 根据星期几获取日期 + + Args: + target_weekday: 目标星期 (0=周一, 6=周日) + is_last_week: 是否是上周 + + Returns: + datetime对象 + """ today = datetime.now() current_weekday = today.weekday() @@ -231,10 +276,32 @@ @staticmethod def format_date_folder(date: datetime) -> str: + """ + 将日期格式化为文件夹名称 + + Args: + date: datetime对象 + + Returns: + 文件夹名称,格式: YYYY-MM-DD + + Examples: + >>> DateParser.format_date_folder(datetime(2025, 10, 11)) + '2025-10-11' + """ return date.strftime("%Y-%m-%d") @staticmethod def validate_date_not_future(date: datetime) -> None: + """ + 验证日期不在未来 + + Args: + date: 待验证的日期 + + Raises: + InvalidParameterError: 日期在未来 + """ if date.date() > datetime.now().date(): raise InvalidParameterError( f"不能查询未来的日期: {date.strftime('%Y-%m-%d')}", @@ -243,6 +310,16 @@ @staticmethod def validate_date_not_too_old(date: datetime, max_days: int = 365) -> None: + """ + 验证日期不太久远 + + Args: + date: 待验证的日期 + max_days: 最大天数 + + Raises: + InvalidParameterError: 日期太久远 + """ days_ago = (datetime.now().date() - date.date()).days if days_ago > max_days: raise InvalidParameterError( @@ -252,6 +329,44 @@ @staticmethod def resolve_date_range_expression(expression: str) -> Dict: + """ + 将自然语言日期表达式解析为标准日期范围 + + 这是专门为 MCP 工具设计的方法,用于在服务器端解析日期表达式, + 避免 AI 模型自己计算日期导致的不一致问题。 + + Args: + expression: 自然语言日期表达式,支持: + - 单日: "今天", "昨天", "today", "yesterday" + - 本周/上周: "本周", "上周", "this week", "last week" + - 本月/上月: "本月", "上月", "this month", "last month" + - 最近N天: "最近7天", "最近30天", "last 7 days", "last 30 days" + - 动态N天: "最近5天", "last 10 days" + + Returns: + 解析结果字典: + { + "success": True, + "expression": "本周", + "normalized": "this_week", + "date_range": { + "start": "2025-11-18", + "end": "2025-11-24" + }, + "current_date": "2025-11-26", + "description": "本周(周一到周日)" + } + + Raises: + InvalidParameterError: 无法识别的日期表达式 + + Examples: + >>> DateParser.resolve_date_range_expression("本周") + {"success": True, "date_range": {"start": "2025-11-18", "end": "2025-11-24"}, ...} + + >>> DateParser.resolve_date_range_expression("最近7天") + {"success": True, "date_range": {"start": "2025-11-20", "end": "2025-11-26"}, ...} + """ if not expression or not isinstance(expression, str): raise InvalidParameterError( "日期表达式不能为空", @@ -312,6 +427,16 @@ normalized: str, today: datetime ) -> Tuple[datetime, datetime, str]: + """ + 根据标准化的日期类型计算实际日期范围 + + Args: + normalized: 标准化的日期类型 + today: 当前日期 + + Returns: + (start_date, end_date, description) 元组 + """ # 单日类型 if normalized == "today": return today, today, "今天" @@ -366,6 +491,12 @@ @staticmethod def get_supported_expressions() -> Dict[str, list]: + """ + 获取支持的日期表达式列表 + + Returns: + 分类的表达式列表 + """ return { "单日": ["今天", "昨天", "today", "yesterday"], "周": ["本周", "上周", "this week", "last week"], @@ -373,4 +504,4 @@ "最近N天": ["最近3天", "最近7天", "最近14天", "最近30天", "last 3 days", "last 7 days", "last 14 days", "last 30 days"], "动态天数": ["最近N天", "last N days"] - }+ }
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_date_range from ..utils.errors import MCPError, InvalidParameterError, DataNotFoundError class SearchTools: def __init__(self, project_root: str = None): self.data_service = DataService(project_root) def search_news_unified( self, query: str, search_mode: str = "keyword", date_range: Optional[Union[Dict[str, str], str]] = None, platforms: Optional[List[str]] = None, limit: int = 50, sort_by: str = "relevance", threshold: float = 0.6, include_url: bool = False, include_rss: bool = False, rss_limit: int = 20 ) -> Dict: try: # 参数验证 query = validate_keyword(query) if search_mode not in ["keyword", "fuzzy", "entity"]: raise InvalidParameterError( f"无效的搜索模式: {search_mode}", suggestion="支持的模式: keyword, fuzzy, entity" ) if sort_by not in ["relevance", "weight", "date"]: raise InvalidParameterError( f"无效的排序方式: {sort_by}", suggestion="支持的排序: relevance, weight, date" ) limit = validate_limit(limit, default=50) threshold = validate_threshold(threshold, default=0.6, min_value=0.0, max_value=1.0) # 处理日期范围 if date_range: from ..utils.validators import validate_date_range date_range_tuple = validate_date_range(date_range) start_date, end_date = date_range_tuple else: # 不指定日期时,使用最新可用数据日期(而非 datetime.now()) earliest, latest = self.data_service.get_available_date_range() if latest is None: # 没有任何可用数据 return { "success": False, "error": { "code": "NO_DATA_AVAILABLE", "message": "output 目录下没有可用的新闻数据", "suggestion": "请先运行爬虫生成数据,或检查 output 目录" } } # 使用最新可用日期 start_date = end_date = latest # 收集所有匹配的新闻 all_matches = [] current_date = start_date while current_date <= end_date: try: all_titles, id_to_name, timestamps = self.data_service.parser.read_all_titles_for_date( date=current_date, platform_ids=platforms ) # 根据搜索模式执行不同的搜索逻辑 if search_mode == "keyword": matches = self._search_by_keyword_mode( query, all_titles, id_to_name, current_date, include_url ) elif search_mode == "fuzzy": matches = self._search_by_fuzzy_mode( query, all_titles, id_to_name, current_date, threshold, include_url ) else: # entity matches = self._search_by_entity_mode( query, all_titles, id_to_name, current_date, include_url ) all_matches.extend(matches) except DataNotFoundError: # 该日期没有数据,继续下一天 pass current_date += timedelta(days=1) if not all_matches: # 获取可用日期范围用于错误提示 earliest, latest = self.data_service.get_available_date_range() # 判断时间范围描述 if start_date.date() == datetime.now().date() and start_date == end_date: time_desc = "今天" elif start_date == end_date: time_desc = start_date.strftime("%Y-%m-%d") else: time_desc = f"{start_date.strftime('%Y-%m-%d')} 至 {end_date.strftime('%Y-%m-%d')}" # 构建错误消息 if earliest and latest: available_desc = f"{earliest.strftime('%Y-%m-%d')} 至 {latest.strftime('%Y-%m-%d')}" message = f"未找到匹配的新闻(查询范围: {time_desc},可用数据: {available_desc})" else: message = f"未找到匹配的新闻({time_desc})" result = { "success": True, "results": [], "total": 0, "query": query, "search_mode": search_mode, "time_range": time_desc, "message": message } return result # 统一排序逻辑 if sort_by == "relevance": all_matches.sort(key=lambda x: x.get("similarity_score", 1.0), reverse=True) elif sort_by == "weight": from .analytics import calculate_news_weight all_matches.sort(key=lambda x: calculate_news_weight(x), reverse=True) elif sort_by == "date": all_matches.sort(key=lambda x: x.get("date", ""), reverse=True) # 限制返回数量 results = all_matches[:limit] # 构建时间范围描述(正确判断是否为今天) if start_date.date() == datetime.now().date() and start_date == end_date: time_range_desc = "今天" elif start_date == end_date: time_range_desc = start_date.strftime("%Y-%m-%d") else: time_range_desc = f"{start_date.strftime('%Y-%m-%d')} 至 {end_date.strftime('%Y-%m-%d')}" result = { "success": True, "summary": { "description": f"新闻搜索结果({search_mode}模式)", "total_found": len(all_matches), "returned": len(results), "requested_limit": limit, "search_mode": search_mode, "query": query, "platforms": platforms or "所有平台", "time_range": time_range_desc, "sort_by": sort_by }, "data": results } if search_mode == "fuzzy": result["summary"]["threshold"] = threshold if len(all_matches) < limit: result["note"] = f"模糊搜索模式下,相似度阈值 {threshold} 仅匹配到 {len(all_matches)} 条结果" # 如果启用 RSS 搜索,同时搜索 RSS 数据 if include_rss: rss_results = self._search_rss_by_keyword( query=query, start_date=start_date, end_date=end_date, limit=rss_limit, include_url=include_url ) result["rss"] = rss_results["items"] result["rss_total"] = rss_results["total"] result["summary"]["include_rss"] = True result["summary"]["rss_found"] = rss_results["total"] result["summary"]["rss_returned"] = len(rss_results["items"]) return result except MCPError as e: return { "success": False, "error": e.to_dict() } except Exception as e: return { "success": False, "error": { "code": "INTERNAL_ERROR", "message": str(e) } } def _search_by_keyword_mode( self, query: str, all_titles: Dict, id_to_name: Dict, current_date: datetime, include_url: bool ) -> List[Dict]: matches = [] query_lower = query.lower() for platform_id, titles in all_titles.items(): platform_name = id_to_name.get(platform_id, platform_id) for title, info in titles.items(): # 精确包含判断 if query_lower in title.lower(): news_item = { "title": title, "platform": platform_id, "platform_name": platform_name, "date": current_date.strftime("%Y-%m-%d"), "similarity_score": 1.0, # 精确匹配,相似度为1 "ranks": info.get("ranks", []), "count": len(info.get("ranks", [])), "rank": info["ranks"][0] if info["ranks"] else 999 } # 条件性添加 URL 字段 if include_url: news_item["url"] = info.get("url", "") news_item["mobileUrl"] = info.get("mobileUrl", "") matches.append(news_item) return matches def _search_by_fuzzy_mode( self, query: str, all_titles: Dict, id_to_name: Dict, current_date: datetime, threshold: float, include_url: bool ) -> List[Dict]: matches = [] for platform_id, titles in all_titles.items(): platform_name = id_to_name.get(platform_id, platform_id) for title, info in titles.items(): # 模糊匹配 is_match, similarity = self._fuzzy_match(query, title, threshold) if is_match: news_item = { "title": title, "platform": platform_id, "platform_name": platform_name, "date": current_date.strftime("%Y-%m-%d"), "similarity_score": round(similarity, 4), "ranks": info.get("ranks", []), "count": len(info.get("ranks", [])), "rank": info["ranks"][0] if info["ranks"] else 999 } # 条件性添加 URL 字段 if include_url: news_item["url"] = info.get("url", "") news_item["mobileUrl"] = info.get("mobileUrl", "") matches.append(news_item) return matches def _search_by_entity_mode( self, query: str, all_titles: Dict, id_to_name: Dict, current_date: datetime, include_url: bool ) -> List[Dict]: matches = [] for platform_id, titles in all_titles.items(): platform_name = id_to_name.get(platform_id, platform_id) for title, info in titles.items(): # 实体搜索:精确包含实体名称 if query in title: news_item = { "title": title, "platform": platform_id, "platform_name": platform_name, "date": current_date.strftime("%Y-%m-%d"), "similarity_score": 1.0, "ranks": info.get("ranks", []), "count": len(info.get("ranks", [])), "rank": info["ranks"][0] if info["ranks"] else 999 } # 条件性添加 URL 字段 if include_url: news_item["url"] = info.get("url", "") news_item["mobileUrl"] = info.get("mobileUrl", "") matches.append(news_item) return matches def _calculate_similarity(self, text1: str, text2: str) -> float: # 使用 difflib.SequenceMatcher 计算序列相似度 return SequenceMatcher(None, text1.lower(), text2.lower()).ratio() def _fuzzy_match(self, query: str, text: str, threshold: float = 0.3) -> Tuple[bool, float]: # 直接包含判断 if query.lower() in text.lower(): return True, 1.0 # 计算整体相似度 similarity = self._calculate_similarity(query, text) if similarity >= threshold: return True, similarity # 分词后的部分匹配 query_words = set(self._extract_keywords(query)) text_words = set(self._extract_keywords(text)) if not query_words or not text_words: return False, 0.0 # 计算关键词重合度 common_words = query_words & text_words keyword_overlap = len(common_words) / len(query_words) if keyword_overlap >= 0.5: # 50%的关键词重合 return True, keyword_overlap return False, similarity def _extract_keywords(self, text: str, min_length: int = 2) -> List[str]: # 移除URL和特殊字符 text = re.sub(r'http[s]?://\S+', '', text) text = re.sub(r'\[.*?\]', '', text) # 移除方括号内容 # 使用正则表达式分词(中文和英文) words = re.findall(r'[\w]+', text) # 过滤短词 keywords = [word for word in words if word and len(word) >= min_length] return keywords def _calculate_keyword_overlap(self, keywords1: List[str], keywords2: List[str]) -> float: if not keywords1 or not keywords2: return 0.0 set1 = set(keywords1) set2 = set(keywords2) # Jaccard 相似度 intersection = len(set1 & set2) union = len(set1 | set2) if union == 0: return 0.0 return intersection / union def _jaccard_similarity(self, list1: List[str], list2: List[str]) -> float: if not list1 or not list2: return 0.0 set1 = set(list1) set2 = set(list2) intersection = len(set1 & set2) union = len(set1 | set2) if union == 0: return 0.0 return intersection / union def search_related_news_history( self, reference_title: str, time_preset: str = "yesterday", start_date: Optional[datetime] = None, end_date: Optional[datetime] = None, threshold: float = 0.4, limit: int = 50, include_url: bool = False ) -> Dict: try: # 参数验证 reference_title = validate_keyword(reference_title) threshold = validate_threshold(threshold, default=0.4, min_value=0.0, max_value=1.0) limit = validate_limit(limit, default=50) # 确定查询日期范围 today = datetime.now() if time_preset == "yesterday": search_start = today - timedelta(days=1) search_end = today - timedelta(days=1) elif time_preset == "last_week": search_start = today - timedelta(days=7) search_end = today - timedelta(days=1) elif time_preset == "last_month": search_start = today - timedelta(days=30) search_end = today - timedelta(days=1) elif time_preset == "custom": if not start_date or not end_date: raise InvalidParameterError( "自定义时间范围需要提供 start_date 和 end_date", suggestion="请提供 start_date 和 end_date 参数" ) search_start = start_date search_end = end_date else: raise InvalidParameterError( f"不支持的时间范围: {time_preset}", suggestion="请使用 'yesterday', 'last_week', 'last_month' 或 'custom'" ) # 提取参考文本的关键词 reference_keywords = self._extract_keywords(reference_title) if not reference_keywords: raise InvalidParameterError( "无法从参考文本中提取关键词", suggestion="请提供更详细的文本内容" ) # 收集所有相关新闻 all_related_news = [] current_date = search_start while current_date <= search_end: try: # 读取该日期的数据 all_titles, id_to_name, _ = self.data_service.parser.read_all_titles_for_date(current_date) # 搜索相关新闻 for platform_id, titles in all_titles.items(): platform_name = id_to_name.get(platform_id, platform_id) for title, info in titles.items(): # 计算标题相似度 title_similarity = self._calculate_similarity(reference_title, title) # 提取标题关键词 title_keywords = self._extract_keywords(title) # 计算关键词重合度 keyword_overlap = self._calculate_keyword_overlap( reference_keywords, title_keywords ) # 综合相似度 (70% 关键词重合 + 30% 文本相似度) combined_score = keyword_overlap * 0.7 + title_similarity * 0.3 if combined_score >= threshold: news_item = { "title": title, "platform": platform_id, "platform_name": platform_name, "date": current_date.strftime("%Y-%m-%d"), "similarity_score": round(combined_score, 4), "keyword_overlap": round(keyword_overlap, 4), "text_similarity": round(title_similarity, 4), "common_keywords": list(set(reference_keywords) & set(title_keywords)), "rank": info["ranks"][0] if info["ranks"] else 0 } # 条件性添加 URL 字段 if include_url: news_item["url"] = info.get("url", "") news_item["mobileUrl"] = info.get("mobileUrl", "") all_related_news.append(news_item) except DataNotFoundError: # 该日期没有数据,继续下一天 pass except Exception as e: # 记录错误但继续处理其他日期 print(f"Warning: 处理日期 {current_date.strftime('%Y-%m-%d')} 时出错: {e}") # 移动到下一天 current_date += timedelta(days=1) if not all_related_news: return { "success": True, "results": [], "total": 0, "query": reference_title, "time_preset": time_preset, "date_range": { "start": search_start.strftime("%Y-%m-%d"), "end": search_end.strftime("%Y-%m-%d") }, "message": "未找到相关新闻" } # 按相似度排序 all_related_news.sort(key=lambda x: x["similarity_score"], reverse=True) # 限制返回数量 results = all_related_news[:limit] # 统计信息 platform_distribution = Counter([news["platform"] for news in all_related_news]) date_distribution = Counter([news["date"] for news in all_related_news]) result = { "success": True, "summary": { "description": "历史相关新闻搜索结果", "total_found": len(all_related_news), "returned": len(results), "requested_limit": limit, "threshold": threshold, "reference_title": reference_title, "reference_keywords": reference_keywords, "time_preset": time_preset, "date_range": { "start": search_start.strftime("%Y-%m-%d"), "end": search_end.strftime("%Y-%m-%d") } }, "data": results, "statistics": { "platform_distribution": dict(platform_distribution), "date_distribution": dict(date_distribution), "avg_similarity": round( sum([news["similarity_score"] for news in all_related_news]) / len(all_related_news), 4 ) if all_related_news else 0.0 } } if len(all_related_news) < limit: result["note"] = f"相关性阈值 {threshold} 下仅找到 {len(all_related_news)} 条相关新闻" return result except MCPError as e: return { "success": False, "error": e.to_dict() } except Exception as e: return { "success": False, "error": { "code": "INTERNAL_ERROR", "message": str(e) } } def find_related_news_unified( self, reference_title: str, date_range: Optional[Union[Dict[str, str], str]] = None, threshold: float = 0.5, limit: int = 50, include_url: bool = False ) -> Dict: try: # 参数验证 reference_title = validate_keyword(reference_title) threshold = validate_threshold(threshold, default=0.5, min_value=0.0, max_value=1.0) limit = validate_limit(limit, default=50) # 确定日期范围 today = datetime.now() # 规范化 date_range(处理 JSON 字符串序列化问题) date_range = normalize_date_range(date_range) if date_range is None or date_range == "today": # 只查询今天 search_dates = [today] elif isinstance(date_range, str): # 预设时间范围 if date_range == "yesterday": search_dates = [today - timedelta(days=1)] elif date_range == "last_week": search_dates = [today - timedelta(days=i) for i in range(7)] elif date_range == "last_month": search_dates = [today - timedelta(days=i) for i in range(30)] else: # 单日字符串格式 try: single_date = datetime.strptime(date_range, "%Y-%m-%d") search_dates = [single_date] except ValueError: search_dates = [today] elif isinstance(date_range, dict): # 日期范围对象 start_str = date_range.get("start") end_str = date_range.get("end") if start_str and end_str: start_date = datetime.strptime(start_str, "%Y-%m-%d") end_date = datetime.strptime(end_str, "%Y-%m-%d") search_dates = [] current = start_date while current <= end_date: search_dates.append(current) current += timedelta(days=1) else: search_dates = [today] else: search_dates = [today] # 提取参考标题的关键词 reference_keywords = self._extract_keywords(reference_title) # 收集所有相关新闻 all_related_news = [] for search_date in search_dates: try: all_titles, id_to_name, _ = self.data_service.parser.read_all_titles_for_date(search_date) for platform_id, titles in all_titles.items(): platform_name = id_to_name.get(platform_id, platform_id) for title, info in titles.items(): if title == reference_title: continue # 计算相似度(使用混合算法) text_similarity = self._calculate_similarity(reference_title, title) # 如果有关键词,也计算关键词重合度 if reference_keywords: title_keywords = self._extract_keywords(title) keyword_similarity = self._jaccard_similarity(reference_keywords, title_keywords) # 混合相似度:70% 文本 + 30% 关键词 similarity = 0.7 * text_similarity + 0.3 * keyword_similarity else: similarity = text_similarity if similarity >= threshold: news_item = { "title": title, "platform": platform_id, "platform_name": platform_name, "date": search_date.strftime("%Y-%m-%d"), "similarity": round(similarity, 3), "rank": info["ranks"][0] if info["ranks"] else 0 } if include_url: news_item["url"] = info.get("url", "") all_related_news.append(news_item) except Exception: # 某天数据读取失败,跳过 continue # 按相似度排序 all_related_news.sort(key=lambda x: x["similarity"], reverse=True) # 限制数量 results = all_related_news[:limit] # 统计信息 from collections import Counter platform_dist = Counter([n["platform_name"] for n in all_related_news]) date_dist = Counter([n["date"] for n in all_related_news]) return { "success": True, "summary": { "description": "相关新闻搜索结果", "total_found": len(all_related_news), "returned": len(results), "reference_title": reference_title, "threshold": threshold, "date_range": { "start": min(search_dates).strftime("%Y-%m-%d"), "end": max(search_dates).strftime("%Y-%m-%d") } if search_dates else None }, "data": results, "statistics": { "platform_distribution": dict(platform_dist), "date_distribution": dict(date_dist) } } except MCPError as e: return {"success": False, "error": e.to_dict()} except Exception as e: return {"success": False, "error": {"code": "INTERNAL_ERROR", "message": str(e)}} def _search_rss_by_keyword( self, query: str, start_date: datetime, end_date: datetime, limit: int = 20, include_url: bool = False ) -> Dict: all_rss_matches = [] query_lower = query.lower() current_date = start_date while current_date <= end_date: try: # 读取该日期的 RSS 数据 all_titles, id_to_name, _ = self.data_service.parser.read_all_titles_for_date( date=current_date, platform_ids=None, db_type="rss" ) for feed_id, items in all_titles.items(): feed_name = id_to_name.get(feed_id, feed_id) for title, info in items.items(): # 关键词匹配(标题或摘要) title_match = query_lower in title.lower() summary = info.get("summary", "") summary_match = query_lower in summary.lower() if summary else False if title_match or summary_match: rss_item = { "title": title, "feed_id": feed_id, "feed_name": feed_name, "date": current_date.strftime("%Y-%m-%d"), "published_at": info.get("published_at", ""), "author": info.get("author", ""), "match_in": "title" if title_match else "summary" } if include_url: rss_item["url"] = info.get("url", "") all_rss_matches.append(rss_item) except DataNotFoundError: # 该日期没有 RSS 数据,继续下一天 pass except Exception: # 其他错误,跳过 pass current_date += timedelta(days=1) # 按发布时间排序(最新的在前) all_rss_matches.sort(key=lambda x: x.get("published_at", ""), reverse=True) return { "items": all_rss_matches[:limit], "total": len(all_rss_matches) }
--- +++ @@ -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: 项目根目录 + """ self.data_service = DataService(project_root) def search_news_unified( @@ -28,6 +40,41 @@ include_rss: bool = False, rss_limit: int = 20 ) -> Dict: + """ + 统一新闻搜索工具 - 整合多种搜索模式,支持同时搜索热榜和RSS + + Args: + query: 查询内容(必需)- 关键词、内容片段或实体名称 + search_mode: 搜索模式,可选值: + - "keyword": 精确关键词匹配(默认) + - "fuzzy": 模糊内容匹配(使用相似度算法) + - "entity": 实体名称搜索(自动按权重排序) + date_range: 日期范围(可选) + - **格式**: {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"} + - **示例**: {"start": "2025-01-01", "end": "2025-01-07"} + - **默认**: 不指定时默认查询今天 + - **注意**: start和end可以相同(表示单日查询) + platforms: 平台过滤列表,如 ['zhihu', 'weibo'] + limit: 热榜返回条数限制,默认50 + sort_by: 排序方式,可选值: + - "relevance": 按相关度排序(默认) + - "weight": 按新闻权重排序 + - "date": 按日期排序 + threshold: 相似度阈值(仅fuzzy模式有效),0-1之间,默认0.6 + include_url: 是否包含URL链接,默认False(节省token) + include_rss: 是否同时搜索RSS数据,默认False + rss_limit: RSS返回条数限制,默认20 + + Returns: + 搜索结果字典,包含匹配的新闻列表(热榜和RSS分开展示) + + Examples: + - search_news_unified(query="人工智能", search_mode="keyword") + - search_news_unified(query="特斯拉降价", search_mode="fuzzy", threshold=0.4) + - search_news_unified(query="马斯克", search_mode="entity", limit=20) + - search_news_unified(query="AI", include_rss=True) # 同时搜索热榜和RSS + - search_news_unified(query="iPhone 16", date_range={"start": "2025-01-01", "end": "2025-01-07"}) + """ try: # 参数验证 query = validate_keyword(query) @@ -213,6 +260,18 @@ current_date: datetime, include_url: bool ) -> List[Dict]: + """ + 关键词搜索模式(精确匹配) + + Args: + query: 搜索关键词 + all_titles: 所有标题字典 + id_to_name: 平台ID到名称映射 + current_date: 当前日期 + + Returns: + 匹配的新闻列表 + """ matches = [] query_lower = query.lower() @@ -251,6 +310,19 @@ threshold: float, include_url: bool ) -> List[Dict]: + """ + 模糊搜索模式(使用相似度算法) + + Args: + query: 搜索内容 + all_titles: 所有标题字典 + id_to_name: 平台ID到名称映射 + current_date: 当前日期 + threshold: 相似度阈值 + + Returns: + 匹配的新闻列表 + """ matches = [] for platform_id, titles in all_titles.items(): @@ -289,6 +361,18 @@ current_date: datetime, include_url: bool ) -> List[Dict]: + """ + 实体搜索模式(自动按权重排序) + + Args: + query: 实体名称 + all_titles: 所有标题字典 + id_to_name: 平台ID到名称映射 + current_date: 当前日期 + + Returns: + 匹配的新闻列表 + """ matches = [] for platform_id, titles in all_titles.items(): @@ -318,10 +402,31 @@ return matches def _calculate_similarity(self, text1: str, text2: str) -> float: + """ + 计算两个文本的相似度 + + Args: + text1: 文本1 + text2: 文本2 + + Returns: + 相似度分数 (0-1之间) + """ # 使用 difflib.SequenceMatcher 计算序列相似度 return SequenceMatcher(None, text1.lower(), text2.lower()).ratio() def _fuzzy_match(self, query: str, text: str, threshold: float = 0.3) -> Tuple[bool, float]: + """ + 模糊匹配函数 + + Args: + query: 查询文本 + text: 待匹配文本 + threshold: 匹配阈值 + + Returns: + (是否匹配, 相似度分数) + """ # 直接包含判断 if query.lower() in text.lower(): return True, 1.0 @@ -348,6 +453,16 @@ return False, similarity def _extract_keywords(self, text: str, min_length: int = 2) -> List[str]: + """ + 从文本中提取关键词 + + Args: + text: 输入文本 + min_length: 最小词长 + + Returns: + 关键词列表 + """ # 移除URL和特殊字符 text = re.sub(r'http[s]?://\S+', '', text) text = re.sub(r'\[.*?\]', '', text) # 移除方括号内容 @@ -361,6 +476,16 @@ return keywords def _calculate_keyword_overlap(self, keywords1: List[str], keywords2: List[str]) -> float: + """ + 计算两个关键词列表的重合度 + + Args: + keywords1: 关键词列表1 + keywords2: 关键词列表2 + + Returns: + 重合度分数 (0-1之间) + """ if not keywords1 or not keywords2: return 0.0 @@ -377,6 +502,16 @@ return intersection / union def _jaccard_similarity(self, list1: List[str], list2: List[str]) -> float: + """ + 计算两个列表的 Jaccard 相似度 + + Args: + list1: 列表1 + list2: 列表2 + + Returns: + Jaccard 相似度 (0-1之间) + """ if not list1 or not list2: return 0.0 @@ -401,6 +536,36 @@ limit: int = 50, include_url: bool = False ) -> Dict: + """ + 在历史数据中搜索与给定新闻相关的新闻 + + Args: + reference_title: 参考新闻标题或内容 + time_preset: 时间范围预设值,可选: + - "yesterday": 昨天 + - "last_week": 上周 (7天) + - "last_month": 上个月 (30天) + - "custom": 自定义日期范围(需要提供 start_date 和 end_date) + start_date: 自定义开始日期(仅当 time_preset="custom" 时有效) + end_date: 自定义结束日期(仅当 time_preset="custom" 时有效) + threshold: 相似度阈值 (0-1之间),默认0.4 + limit: 返回条数限制,默认50 + include_url: 是否包含URL链接,默认False(节省token) + + Returns: + 搜索结果字典,包含相关新闻列表 + + Example: + >>> tools = SearchTools() + >>> result = tools.search_related_news_history( + ... reference_title="人工智能技术突破", + ... time_preset="last_week", + ... threshold=0.4, + ... limit=50 + ... ) + >>> for news in result['results']: + ... print(f"{news['date']}: {news['title']} (相似度: {news['similarity_score']})") + """ try: # 参数验证 reference_title = validate_keyword(reference_title) @@ -579,6 +744,25 @@ limit: int = 50, include_url: bool = False ) -> Dict: + """ + 统一的相关新闻查找工具 - 整合相似新闻和历史相关搜索 + + Args: + reference_title: 参考新闻标题 + date_range: 日期范围(可选) + - 不指定: 只查询今天的数据 + - {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}: 查询指定日期范围 + - "today": 今天 + - "yesterday": 昨天 + - "last_week": 最近7天 + - "last_month": 最近30天 + threshold: 相似度阈值,0-1之间,默认0.5 + limit: 返回条数限制,默认50 + include_url: 是否包含URL链接,默认False + + Returns: + 相关新闻列表,按相似度排序 + """ try: # 参数验证 reference_title = validate_keyword(reference_title) @@ -718,6 +902,19 @@ limit: int = 20, include_url: bool = False ) -> Dict: + """ + 在 RSS 数据中搜索关键词 + + Args: + query: 搜索关键词 + start_date: 开始日期 + end_date: 结束日期 + limit: 返回条数限制 + include_url: 是否包含 URL + + Returns: + RSS 搜索结果字典 + """ all_rss_matches = [] query_lower = query.lower() current_date = start_date @@ -771,4 +968,4 @@ return { "items": all_rss_matches[:limit], "total": len(all_rss_matches) - }+ }
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 = None @dataclass class ParsedRSSItem: title: str url: str published_at: Optional[str] = None summary: Optional[str] = None author: Optional[str] = None guid: Optional[str] = None class RSSParser: def __init__(self, max_summary_length: int = 500): if not HAS_FEEDPARSER: raise ImportError("RSS 解析需要安装 feedparser: pip install feedparser") self.max_summary_length = max_summary_length def parse(self, content: str, feed_url: str = "") -> List[ParsedRSSItem]: # 先尝试检测 JSON Feed if self._is_json_feed(content): return self._parse_json_feed(content, feed_url) # 使用 feedparser 解析 RSS/Atom feed = feedparser.parse(content) if feed.bozo and not feed.entries: raise ValueError(f"RSS 解析失败 ({feed_url}): {feed.bozo_exception}") items = [] for entry in feed.entries: item = self._parse_entry(entry) if item: items.append(item) return items def _is_json_feed(self, content: str) -> bool: content = content.strip() if not content.startswith("{"): return False try: data = json.loads(content) version = data.get("version", "") return "jsonfeed.org" in version except (json.JSONDecodeError, TypeError): return False def _parse_json_feed(self, content: str, feed_url: str = "") -> List[ParsedRSSItem]: try: data = json.loads(content) except json.JSONDecodeError as e: raise ValueError(f"JSON Feed 解析失败 ({feed_url}): {e}") items_data = data.get("items", []) if not items_data: return [] items = [] for item_data in items_data: item = self._parse_json_feed_item(item_data) if item: items.append(item) return items def _parse_json_feed_item(self, item_data: Dict[str, Any]) -> Optional[ParsedRSSItem]: # 标题:优先 title,否则使用 content_text 的前 100 字符 title = item_data.get("title", "") if not title: content_text = item_data.get("content_text", "") if content_text: title = content_text[:100] + ("..." if len(content_text) > 100 else "") title = self._clean_text(title) if not title: return None # URL url = item_data.get("url", "") or item_data.get("external_url", "") # 发布时间(ISO 8601 格式) published_at = None date_str = item_data.get("date_published") or item_data.get("date_modified") if date_str: published_at = self._parse_iso_date(date_str) # 摘要:优先 summary,否则使用 content_text summary = item_data.get("summary", "") if not summary: content_text = item_data.get("content_text", "") content_html = item_data.get("content_html", "") summary = content_text or self._clean_text(content_html) if summary: summary = self._clean_text(summary) if len(summary) > self.max_summary_length: summary = summary[:self.max_summary_length] + "..." # 作者 author = None authors = item_data.get("authors", []) if authors: names = [a.get("name", "") for a in authors if isinstance(a, dict) and a.get("name")] if names: author = ", ".join(names) # GUID guid = item_data.get("id", "") or url return ParsedRSSItem( title=title, url=url, published_at=published_at, summary=summary or None, author=author, guid=guid, ) def _parse_iso_date(self, date_str: str) -> Optional[str]: if not date_str: return None try: # 处理常见的 ISO 8601 格式 # 替换 Z 为 +00:00 date_str = date_str.replace("Z", "+00:00") dt = datetime.fromisoformat(date_str) return dt.isoformat() except (ValueError, TypeError): pass return None def parse_url(self, url: str, timeout: int = 10) -> List[ParsedRSSItem]: import requests response = requests.get(url, timeout=timeout, headers={ "User-Agent": "TrendRadar/2.0 RSS Reader" }) response.raise_for_status() return self.parse(response.text, url) def _parse_entry(self, entry: Any) -> Optional[ParsedRSSItem]: title = self._clean_text(entry.get("title", "")) if not title: return None url = entry.get("link", "") if not url: # 尝试从 links 中获取 links = entry.get("links", []) for link in links: if link.get("rel") == "alternate" or link.get("type", "").startswith("text/html"): url = link.get("href", "") break if not url and links: url = links[0].get("href", "") published_at = self._parse_date(entry) summary = self._parse_summary(entry) author = self._parse_author(entry) guid = entry.get("id") or entry.get("guid", {}).get("value") or url return ParsedRSSItem( title=title, url=url, published_at=published_at, summary=summary, author=author, guid=guid, ) def _clean_text(self, text: str) -> str: if not text: return "" # 解码 HTML 实体 text = html.unescape(text) # 移除 HTML 标签 text = re.sub(r'<[^>]+>', '', text) # 移除多余空白 text = re.sub(r'\s+', ' ', text) return text.strip() def _parse_date(self, entry: Any) -> Optional[str]: # feedparser 会自动解析日期到 published_parsed date_struct = entry.get("published_parsed") or entry.get("updated_parsed") if date_struct: try: dt = datetime(*date_struct[:6]) return dt.isoformat() except (ValueError, TypeError): pass # 尝试手动解析 date_str = entry.get("published") or entry.get("updated") if date_str: try: dt = parsedate_to_datetime(date_str) return dt.isoformat() except (ValueError, TypeError): pass # 尝试 ISO 格式 try: dt = datetime.fromisoformat(date_str.replace("Z", "+00:00")) return dt.isoformat() except (ValueError, TypeError): pass return None def _parse_summary(self, entry: Any) -> Optional[str]: summary = entry.get("summary") or entry.get("description", "") if not summary: # 尝试从 content 获取 content = entry.get("content", []) if content and isinstance(content, list): summary = content[0].get("value", "") if not summary: return None summary = self._clean_text(summary) # 截断过长的摘要 if len(summary) > self.max_summary_length: summary = summary[:self.max_summary_length] + "..." return summary def _parse_author(self, entry: Any) -> Optional[str]: author = entry.get("author") if author: return self._clean_text(author) # 尝试从 dc:creator 获取 author = entry.get("dc_creator") if author: return self._clean_text(author) # 尝试从 authors 列表获取 authors = entry.get("authors", []) if authors: names = [a.get("name", "") for a in authors if a.get("name")] if names: return ", ".join(names) return None
--- +++ @@ -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: + """RSS 解析器""" def __init__(self, max_summary_length: int = 500): + """ + 初始化解析器 + + Args: + max_summary_length: 摘要最大长度 + """ if not HAS_FEEDPARSER: raise ImportError("RSS 解析需要安装 feedparser: pip install feedparser") self.max_summary_length = max_summary_length def parse(self, content: str, feed_url: str = "") -> List[ParsedRSSItem]: + """ + 解析 RSS/Atom/JSON Feed 内容 + + Args: + content: Feed 内容(XML 或 JSON) + feed_url: Feed URL(用于错误提示) + + Returns: + 解析后的条目列表 + """ # 先尝试检测 JSON Feed if self._is_json_feed(content): return self._parse_json_feed(content, feed_url) @@ -54,6 +77,11 @@ return items def _is_json_feed(self, content: str) -> bool: + """ + 检测内容是否为 JSON Feed 格式 + + JSON Feed 必须包含 version 字段,值为 https://jsonfeed.org/version/1 或 1.1 + """ content = content.strip() if not content.startswith("{"): return False @@ -66,6 +94,18 @@ return False def _parse_json_feed(self, content: str, feed_url: str = "") -> List[ParsedRSSItem]: + """ + 解析 JSON Feed 1.1 格式 + + JSON Feed 规范: https://www.jsonfeed.org/version/1.1/ + + Args: + content: JSON Feed 内容 + feed_url: Feed URL(用于错误提示) + + Returns: + 解析后的条目列表 + """ try: data = json.loads(content) except json.JSONDecodeError as e: @@ -84,6 +124,7 @@ return items def _parse_json_feed_item(self, item_data: Dict[str, Any]) -> Optional[ParsedRSSItem]: + """解析单个 JSON Feed 条目""" # 标题:优先 title,否则使用 content_text 的前 100 字符 title = item_data.get("title", "") if not title: @@ -137,6 +178,7 @@ ) def _parse_iso_date(self, date_str: str) -> Optional[str]: + """解析 ISO 8601 日期格式""" if not date_str: return None @@ -152,6 +194,16 @@ return None def parse_url(self, url: str, timeout: int = 10) -> List[ParsedRSSItem]: + """ + 从 URL 解析 RSS + + Args: + url: RSS URL + timeout: 超时时间(秒) + + Returns: + 解析后的条目列表 + """ import requests response = requests.get(url, timeout=timeout, headers={ @@ -162,6 +214,7 @@ return self.parse(response.text, url) def _parse_entry(self, entry: Any) -> Optional[ParsedRSSItem]: + """解析单个条目""" title = self._clean_text(entry.get("title", "")) if not title: return None @@ -192,6 +245,7 @@ ) def _clean_text(self, text: str) -> str: + """清理文本""" if not text: return "" @@ -207,6 +261,7 @@ return text.strip() def _parse_date(self, entry: Any) -> Optional[str]: + """解析发布日期""" # feedparser 会自动解析日期到 published_parsed date_struct = entry.get("published_parsed") or entry.get("updated_parsed") @@ -236,6 +291,7 @@ return None def _parse_summary(self, entry: Any) -> Optional[str]: + """解析摘要""" summary = entry.get("summary") or entry.get("description", "") if not summary: @@ -256,6 +312,7 @@ return summary def _parse_author(self, entry: Any) -> Optional[str]: + """解析作者""" author = entry.get("author") if author: return self._clean_text(author) @@ -272,4 +329,4 @@ if names: return ", ".join(names) - return None+ return None
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_service = DataService(project_root) if project_root: self.project_root = Path(project_root) else: # 获取项目根目录 current_file = Path(__file__) self.project_root = current_file.parent.parent.parent def get_system_status(self) -> Dict: try: # 获取系统状态 status = self.data_service.get_system_status() return { "success": True, "summary": { "description": "系统运行状态和健康检查信息" }, "data": status } except MCPError as e: return { "success": False, "error": e.to_dict() } except Exception as e: return { "success": False, "error": { "code": "INTERNAL_ERROR", "message": str(e) } } def trigger_crawl(self, platforms: Optional[List[str]] = None, save_to_local: bool = False, include_url: bool = False) -> Dict: try: import time import yaml from trendradar.crawler.fetcher import DataFetcher from trendradar.storage.local import LocalStorageBackend from trendradar.storage.base import convert_crawl_results_to_news_data from trendradar.utils.time import get_configured_time, format_date_folder, format_time_filename from ..services.cache_service import get_cache # 参数验证 platforms = validate_platforms(platforms) # 加载配置文件 config_path = self.project_root / "config" / "config.yaml" if not config_path.exists(): raise CrawlTaskError( "配置文件不存在", suggestion=f"请确保配置文件存在: {config_path}" ) # 读取配置 with open(config_path, "r", encoding="utf-8") as f: config_data = yaml.safe_load(f) # 获取平台配置(嵌套结构:{enabled: bool, sources: [...]}) platforms_config = config_data.get("platforms", {}) if not platforms_config.get("enabled", True): raise CrawlTaskError( "热榜平台已禁用", suggestion="请检查 config/config.yaml 中的 platforms.enabled 配置" ) all_platforms = platforms_config.get("sources", []) if not all_platforms: raise CrawlTaskError( "配置文件中没有平台配置", suggestion="请检查 config/config.yaml 中的 platforms.sources 配置" ) # 过滤平台 if platforms: target_platforms = [p for p in all_platforms if p["id"] in platforms] if not target_platforms: raise CrawlTaskError( f"指定的平台不存在: {platforms}", suggestion=f"可用平台: {[p['id'] for p in all_platforms]}" ) else: target_platforms = all_platforms # 构建平台ID列表 ids = [] for platform in target_platforms: if "name" in platform: ids.append((platform["id"], platform["name"])) else: ids.append(platform["id"]) print(f"开始临时爬取,平台: {[p.get('name', p['id']) for p in target_platforms]}") # 初始化数据获取器 advanced = config_data.get("advanced", {}) crawler_config = advanced.get("crawler", {}) proxy_url = None if crawler_config.get("use_proxy"): proxy_url = crawler_config.get("default_proxy") fetcher = DataFetcher(proxy_url=proxy_url) request_interval = crawler_config.get("request_interval", 100) # 执行爬取 results, id_to_name, failed_ids = fetcher.crawl_websites( ids_list=ids, request_interval=request_interval ) # 获取当前时间(统一使用 trendradar 的时间工具) # 从配置中读取时区,默认为 Asia/Shanghai timezone = config_data.get("app", {}).get("timezone", "Asia/Shanghai") current_time = get_configured_time(timezone) crawl_date = format_date_folder(None, timezone) crawl_time_str = format_time_filename(timezone) # 转换为标准数据模型 news_data = convert_crawl_results_to_news_data( results=results, id_to_name=id_to_name, failed_ids=failed_ids, crawl_time=crawl_time_str, crawl_date=crawl_date ) # 初始化存储后端 storage = LocalStorageBackend( data_dir=str(self.project_root / "output"), enable_txt=True, enable_html=True, timezone=timezone ) # 尝试持久化数据 save_success = False save_error_msg = "" saved_files = {} try: # 1. 保存到 SQLite (核心持久化) if storage.save_news_data(news_data): save_success = True # 2. 如果请求保存到本地,生成 TXT/HTML 快照 if save_to_local: # 保存 TXT txt_path = storage.save_txt_snapshot(news_data) if txt_path: saved_files["txt"] = txt_path # 保存 HTML (使用简化版生成器) html_content = self._generate_simple_html(results, id_to_name, failed_ids, current_time) html_filename = f"{crawl_time_str}.html" html_path = storage.save_html_report(html_content, html_filename) if html_path: saved_files["html"] = html_path except Exception as e: # 捕获所有保存错误(特别是 Docker 只读卷导致的 PermissionError) print(f"[System] 数据保存失败: {e}") save_success = False save_error_msg = str(e) # 3. 清除缓存,确保下次查询获取最新数据 # 即使保存失败,内存中的数据可能已经通过其他方式更新,或者是临时的 get_cache().clear() print("[System] 缓存已清除") # 构建返回结果 news_response_data = [] for platform_id, titles_data in results.items(): platform_name = id_to_name.get(platform_id, platform_id) for title, info in titles_data.items(): news_item = { "platform_id": platform_id, "platform_name": platform_name, "title": title, "ranks": info.get("ranks", []) } if include_url: news_item["url"] = info.get("url", "") news_item["mobile_url"] = info.get("mobileUrl", "") news_response_data.append(news_item) result = { "success": True, "summary": { "description": "爬取任务执行结果", "task_id": f"crawl_{int(time.time())}", "status": "completed", "crawl_time": current_time.strftime("%Y-%m-%d %H:%M:%S"), "total_news": len(news_response_data), "platforms": list(results.keys()), "failed_platforms": failed_ids, "saved_to_local": save_success and save_to_local }, "data": news_response_data } if save_success: if save_to_local: result["saved_files"] = saved_files result["note"] = "数据已保存到 SQLite 数据库及 output 文件夹" else: result["note"] = "数据已保存到 SQLite 数据库 (仅内存中返回结果,未生成TXT快照)" else: # 明确告知用户保存失败 result["saved_to_local"] = False result["save_error"] = save_error_msg if "Read-only file system" in save_error_msg or "Permission denied" in save_error_msg: result["note"] = "爬取成功,但无法写入数据库(Docker只读模式)。数据仅在本次返回中有效。" else: result["note"] = f"爬取成功但保存失败: {save_error_msg}" # 清理资源 storage.cleanup() return result except MCPError as e: return { "success": False, "error": e.to_dict() } except Exception as e: import traceback return { "success": False, "error": { "code": "INTERNAL_ERROR", "message": str(e), "traceback": traceback.format_exc() } } def _generate_simple_html(self, results: Dict, id_to_name: Dict, failed_ids: List, now) -> str: html = """<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>MCP 爬取结果</title> <style> body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; } .container { max-width: 900px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; } h1 { color: #333; border-bottom: 2px solid #4CAF50; padding-bottom: 10px; } .platform { margin-bottom: 30px; } .platform-name { background: #4CAF50; color: white; padding: 10px; border-radius: 5px; margin-bottom: 10px; } .news-item { padding: 8px; border-bottom: 1px solid #eee; } .rank { color: #666; font-weight: bold; margin-right: 10px; } .title { color: #333; } .link { color: #1976D2; text-decoration: none; margin-left: 10px; font-size: 0.9em; } .link:hover { text-decoration: underline; } .failed { background: #ffebee; padding: 10px; border-radius: 5px; margin-top: 20px; } .failed h3 { color: #c62828; margin-top: 0; } .timestamp { color: #666; font-size: 0.9em; text-align: right; margin-top: 20px; } </style> </head> <body> <div class="container"> <h1>MCP 爬取结果</h1> """ # 添加时间戳 html += f' <p class="timestamp">爬取时间: {now.strftime("%Y-%m-%d %H:%M:%S")}</p>\n\n' # 遍历每个平台 for platform_id, titles_data in results.items(): platform_name = id_to_name.get(platform_id, platform_id) html += f' <div class="platform">\n' html += f' <div class="platform-name">{platform_name}</div>\n' # 排序标题 sorted_items = [] for title, info in titles_data.items(): ranks = info.get("ranks", []) url = info.get("url", "") mobile_url = info.get("mobileUrl", "") rank = ranks[0] if ranks else 999 sorted_items.append((rank, title, url, mobile_url)) sorted_items.sort(key=lambda x: x[0]) # 显示新闻 for rank, title, url, mobile_url in sorted_items: html += f' <div class="news-item">\n' html += f' <span class="rank">{rank}.</span>\n' html += f' <span class="title">{self._html_escape(title)}</span>\n' if url: html += f' <a class="link" href="{self._html_escape(url)}" target="_blank">链接</a>\n' if mobile_url and mobile_url != url: html += f' <a class="link" href="{self._html_escape(mobile_url)}" target="_blank">移动版</a>\n' html += ' </div>\n' html += ' </div>\n\n' # 失败的平台 if failed_ids: html += ' <div class="failed">\n' html += ' <h3>请求失败的平台</h3>\n' html += ' <ul>\n' for platform_id in failed_ids: html += f' <li>{self._html_escape(platform_id)}</li>\n' html += ' </ul>\n' html += ' </div>\n' html += """ </div> </body> </html>""" return html def _html_escape(self, text: str) -> str: if not isinstance(text, str): text = str(text) return ( text.replace("&", "&amp;") .replace("<", "&lt;") .replace(">", "&gt;") .replace('"', "&quot;") .replace("'", "&#x27;") ) def check_version(self, proxy_url: Optional[str] = None) -> Dict: import yaml import requests def parse_version(version_str: str): try: parts = version_str.strip().split(".") if len(parts) != 3: raise ValueError("版本号格式不正确") return int(parts[0]), int(parts[1]), int(parts[2]) except: return 0, 0, 0 def check_single_version( name: str, local_version: str, remote_url: str, proxies: Optional[Dict], headers: Dict ) -> Dict: try: response = requests.get( remote_url, proxies=proxies, headers=headers, timeout=10 ) response.raise_for_status() remote_version = response.text.strip() local_tuple = parse_version(local_version) remote_tuple = parse_version(remote_version) need_update = local_tuple < remote_tuple if need_update: message = f"发现新版本 {remote_version},当前版本 {local_version},建议更新" elif local_tuple > remote_tuple: message = f"当前版本 {local_version} 高于远程版本 {remote_version}(可能是开发版本)" else: message = f"当前版本 {local_version} 已是最新版本" return { "success": True, "name": name, "current_version": local_version, "remote_version": remote_version, "need_update": need_update, "current_parsed": list(local_tuple), "remote_parsed": list(remote_tuple), "message": message } except requests.exceptions.Timeout: return { "success": False, "name": name, "current_version": local_version, "error": "获取远程版本超时" } except requests.exceptions.RequestException as e: return { "success": False, "name": name, "current_version": local_version, "error": f"网络请求失败: {str(e)}" } except Exception as e: return { "success": False, "name": name, "current_version": local_version, "error": str(e) } try: # 导入本地版本 from trendradar import __version__ as trendradar_version from mcp_server import __version__ as mcp_version # 从配置文件获取远程版本 URL config_path = self.project_root / "config" / "config.yaml" if not config_path.exists(): return { "success": False, "error": { "code": "CONFIG_NOT_FOUND", "message": f"配置文件不存在: {config_path}" } } with open(config_path, "r", encoding="utf-8") as f: config_data = yaml.safe_load(f) advanced_config = config_data.get("advanced", {}) trendradar_url = advanced_config.get( "version_check_url", "https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/version" ) mcp_url = advanced_config.get( "mcp_version_check_url", "https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/version_mcp" ) # 配置代理 proxies = None if proxy_url: proxies = {"http": proxy_url, "https": proxy_url} # 请求头 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", "Accept": "text/plain, */*", "Cache-Control": "no-cache", } # 检查两个版本 trendradar_result = check_single_version( "TrendRadar", trendradar_version, trendradar_url, proxies, headers ) mcp_result = check_single_version( "MCP Server", mcp_version, mcp_url, proxies, headers ) # 判断是否有任何更新 any_update = ( (trendradar_result.get("success") and trendradar_result.get("need_update", False)) or (mcp_result.get("success") and mcp_result.get("need_update", False)) ) return { "success": True, "summary": { "description": "版本检查结果(TrendRadar + MCP Server)", "any_update": any_update }, "data": { "trendradar": trendradar_result, "mcp": mcp_result, "any_update": any_update } } except ImportError as e: return { "success": False, "error": { "code": "IMPORT_ERROR", "message": f"无法导入版本信息: {str(e)}" } } except Exception as e: return { "success": False, "error": { "code": "INTERNAL_ERROR", "message": str(e) } }
--- +++ @@ -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: + project_root: 项目根目录 + """ self.data_service = DataService(project_root) if project_root: self.project_root = Path(project_root) @@ -19,6 +31,17 @@ self.project_root = current_file.parent.parent.parent def get_system_status(self) -> Dict: + """ + 获取系统运行状态和健康检查信息 + + Returns: + 系统状态字典 + + Example: + >>> tools = SystemManagementTools() + >>> result = tools.get_system_status() + >>> print(result['system']['version']) + """ try: # 获取系统状态 status = self.data_service.get_system_status() @@ -46,6 +69,26 @@ } def trigger_crawl(self, platforms: Optional[List[str]] = None, save_to_local: bool = False, include_url: bool = False) -> Dict: + """ + 手动触发一次临时爬取任务(可选持久化) + + Args: + platforms: 指定平台列表,为空则爬取所有平台 + save_to_local: 是否保存到本地 output 目录,默认 False + include_url: 是否包含URL链接,默认False(节省token) + + Returns: + 爬取结果字典,包含新闻数据和保存路径(如果保存) + + Example: + >>> tools = SystemManagementTools() + >>> # 临时爬取,不保存 + >>> result = tools.trigger_crawl(platforms=['zhihu', 'weibo']) + >>> print(result['data']) + >>> # 爬取并保存到本地 + >>> result = tools.trigger_crawl(platforms=['zhihu'], save_to_local=True) + >>> print(result['saved_files']) + """ try: import time import yaml @@ -248,6 +291,7 @@ } def _generate_simple_html(self, results: Dict, id_to_name: Dict, failed_ids: List, now) -> str: + """生成简化的 HTML 报告""" html = """<!DOCTYPE html> <html> <head> @@ -325,6 +369,7 @@ return html def _html_escape(self, text: str) -> str: + """HTML 转义""" if not isinstance(text, str): text = str(text) return ( @@ -336,10 +381,34 @@ ) def check_version(self, proxy_url: Optional[str] = None) -> Dict: + """ + 检查版本更新 + + 同时检查 TrendRadar 和 MCP Server 两个组件的版本更新。 + 远程版本 URL 从 config.yaml 获取: + - version_check_url: TrendRadar 版本 + - mcp_version_check_url: MCP Server 版本 + + Args: + proxy_url: 可选的代理URL,用于访问远程版本 + + Returns: + 版本检查结果字典,包含: + - success: 是否成功 + - trendradar: TrendRadar 版本检查结果 + - mcp: MCP Server 版本检查结果 + - any_update: 是否有任何组件需要更新 + + Example: + >>> tools = SystemManagementTools() + >>> result = tools.check_version() + >>> print(result['data']['any_update']) + """ import yaml import requests def parse_version(version_str: str): + """将版本号字符串解析为元组""" try: parts = version_str.strip().split(".") if len(parts) != 3: @@ -355,6 +424,7 @@ proxies: Optional[Dict], headers: Dict ) -> Dict: + """检查单个组件的版本""" try: response = requests.get( remote_url, proxies=proxies, headers=headers, timeout=10 @@ -488,4 +558,4 @@ "code": "INTERNAL_ERROR", "message": str(e) } - }+ }
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 @dataclass class RSSFeedConfig: id: str # 源 ID name: str # 显示名称 url: str # RSS URL max_items: int = 0 # 最大条目数(0=不限制) enabled: bool = True # 是否启用 max_age_days: Optional[int] = None # 文章最大年龄(天),覆盖全局设置;None=使用全局,0=禁用过滤 class RSSFetcher: def __init__( self, feeds: List[RSSFeedConfig], request_interval: int = 2000, timeout: int = 15, use_proxy: bool = False, proxy_url: str = "", timezone: str = DEFAULT_TIMEZONE, freshness_enabled: bool = True, default_max_age_days: int = 3, ): self.feeds = [f for f in feeds if f.enabled] self.request_interval = request_interval self.timeout = timeout self.use_proxy = use_proxy self.proxy_url = proxy_url self.timezone = timezone self.freshness_enabled = freshness_enabled self.default_max_age_days = default_max_age_days self.parser = RSSParser() self.session = self._create_session() def _create_session(self) -> requests.Session: session = requests.Session() session.headers.update({ "User-Agent": "TrendRadar/2.0 RSS Reader (https://github.com/trendradar)", "Accept": "application/feed+json, application/json, application/rss+xml, application/atom+xml, application/xml, text/xml, */*", "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", }) if self.use_proxy and self.proxy_url: session.proxies = { "http": self.proxy_url, "https": self.proxy_url, } return session def _filter_by_freshness( self, items: List[RSSItem], feed: RSSFeedConfig, ) -> Tuple[List[RSSItem], int]: # 如果全局禁用,直接返回 if not self.freshness_enabled: return items, 0 # 确定此 feed 的 max_age_days max_days = feed.max_age_days if max_days is None: max_days = self.default_max_age_days # 如果设为 0,禁用此 feed 的过滤 if max_days == 0: return items, 0 # 过滤逻辑:无发布时间的文章保留 filtered = [] for item in items: if not item.published_at: # 无发布时间,保留 filtered.append(item) elif is_within_days(item.published_at, max_days, self.timezone): # 在指定天数内,保留 filtered.append(item) # 否则过滤掉 filtered_count = len(items) - len(filtered) return filtered, filtered_count def fetch_feed(self, feed: RSSFeedConfig) -> Tuple[List[RSSItem], Optional[str]]: try: response = self.session.get(feed.url, timeout=self.timeout) response.raise_for_status() parsed_items = self.parser.parse(response.text, feed.url) # 限制条目数量(0=不限制) if feed.max_items > 0: parsed_items = parsed_items[:feed.max_items] # 转换为 RSSItem(使用配置的时区) now = get_configured_time(self.timezone) crawl_time = now.strftime("%H:%M") items = [] for parsed in parsed_items: item = RSSItem( title=parsed.title, feed_id=feed.id, feed_name=feed.name, url=parsed.url, published_at=parsed.published_at or "", summary=parsed.summary or "", author=parsed.author or "", crawl_time=crawl_time, first_time=crawl_time, last_time=crawl_time, count=1, ) items.append(item) # 注意:新鲜度过滤已移至推送阶段(_convert_rss_items_to_list) # 这样所有文章都会存入数据库,但旧文章不会推送 print(f"[RSS] {feed.name}: 获取 {len(items)} 条") return items, None except requests.Timeout: error = f"请求超时 ({self.timeout}s)" print(f"[RSS] {feed.name}: {error}") return [], error except requests.RequestException as e: error = f"请求失败: {e}" print(f"[RSS] {feed.name}: {error}") return [], error except ValueError as e: error = f"解析失败: {e}" print(f"[RSS] {feed.name}: {error}") return [], error except Exception as e: error = f"未知错误: {e}" print(f"[RSS] {feed.name}: {error}") return [], error def fetch_all(self) -> RSSData: all_items: Dict[str, List[RSSItem]] = {} id_to_name: Dict[str, str] = {} failed_ids: List[str] = [] # 使用配置的时区 now = get_configured_time(self.timezone) crawl_time = now.strftime("%H:%M") crawl_date = now.strftime("%Y-%m-%d") print(f"[RSS] 开始抓取 {len(self.feeds)} 个 RSS 源...") for i, feed in enumerate(self.feeds): # 请求间隔(带随机波动) if i > 0: interval = self.request_interval / 1000 jitter = random.uniform(-0.2, 0.2) * interval time.sleep(interval + jitter) items, error = self.fetch_feed(feed) id_to_name[feed.id] = feed.name if error: failed_ids.append(feed.id) else: all_items[feed.id] = items total_items = sum(len(items) for items in all_items.values()) print(f"[RSS] 抓取完成: {len(all_items)} 个源成功, {len(failed_ids)} 个失败, 共 {total_items} 条") return RSSData( date=crawl_date, crawl_time=crawl_time, items=all_items, id_to_name=id_to_name, failed_ids=failed_ids, ) @classmethod def from_config(cls, config: Dict) -> "RSSFetcher": # 读取新鲜度过滤配置 freshness_config = config.get("freshness_filter", {}) freshness_enabled = freshness_config.get("enabled", True) # 默认启用 default_max_age_days = freshness_config.get("max_age_days", 3) # 默认3天 feeds = [] for feed_config in config.get("feeds", []): # 读取并验证单个 feed 的 max_age_days(可选) max_age_days_raw = feed_config.get("max_age_days") max_age_days = None if max_age_days_raw is not None: try: max_age_days = int(max_age_days_raw) if max_age_days < 0: feed_id = feed_config.get("id", "unknown") print(f"[警告] RSS feed '{feed_id}' 的 max_age_days 为负数,将使用全局默认值") max_age_days = None except (ValueError, TypeError): feed_id = feed_config.get("id", "unknown") print(f"[警告] RSS feed '{feed_id}' 的 max_age_days 格式错误:{max_age_days_raw}") max_age_days = None feed = RSSFeedConfig( id=feed_config.get("id", ""), name=feed_config.get("name", ""), url=feed_config.get("url", ""), max_items=feed_config.get("max_items", 0), # 0=不限制 enabled=feed_config.get("enabled", True), max_age_days=max_age_days, # None=使用全局,0=禁用,>0=覆盖 ) if feed.id and feed.url: feeds.append(feed) return cls( feeds=feeds, request_interval=config.get("request_interval", 2000), timeout=config.get("timeout", 15), use_proxy=config.get("use_proxy", False), proxy_url=config.get("proxy_url", ""), timezone=config.get("timezone", DEFAULT_TIMEZONE), freshness_enabled=freshness_enabled, default_max_age_days=default_max_age_days, )
--- +++ @@ -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 +29,7 @@ class RSSFetcher: + """RSS 抓取器""" def __init__( self, @@ -35,6 +42,19 @@ freshness_enabled: bool = True, default_max_age_days: int = 3, ): + """ + 初始化抓取器 + + Args: + feeds: RSS 源配置列表 + request_interval: 请求间隔(毫秒) + timeout: 请求超时(秒) + use_proxy: 是否使用代理 + proxy_url: 代理 URL + timezone: 时区配置(如 'Asia/Shanghai') + freshness_enabled: 是否启用新鲜度过滤 + default_max_age_days: 默认最大文章年龄(天) + """ self.feeds = [f for f in feeds if f.enabled] self.request_interval = request_interval self.timeout = timeout @@ -48,6 +68,7 @@ self.session = self._create_session() def _create_session(self) -> requests.Session: + """创建请求会话""" session = requests.Session() session.headers.update({ "User-Agent": "TrendRadar/2.0 RSS Reader (https://github.com/trendradar)", @@ -68,6 +89,16 @@ items: List[RSSItem], feed: RSSFeedConfig, ) -> Tuple[List[RSSItem], int]: + """ + 根据新鲜度过滤文章 + + Args: + items: 待过滤的文章列表 + feed: RSS 源配置 + + Returns: + (过滤后的文章列表, 被过滤的文章数) + """ # 如果全局禁用,直接返回 if not self.freshness_enabled: return items, 0 @@ -96,6 +127,15 @@ return filtered, filtered_count def fetch_feed(self, feed: RSSFeedConfig) -> Tuple[List[RSSItem], Optional[str]]: + """ + 抓取单个 RSS 源 + + Args: + feed: RSS 源配置 + + Returns: + (条目列表, 错误信息) 元组 + """ try: response = self.session.get(feed.url, timeout=self.timeout) response.raise_for_status() @@ -153,6 +193,12 @@ return [], error def fetch_all(self) -> RSSData: + """ + 抓取所有 RSS 源 + + Returns: + RSSData 对象 + """ all_items: Dict[str, List[RSSItem]] = {} id_to_name: Dict[str, str] = {} failed_ids: List[str] = [] @@ -193,6 +239,26 @@ @classmethod def from_config(cls, config: Dict) -> "RSSFetcher": + """ + 从配置字典创建抓取器 + + Args: + config: 配置字典,格式如下: + { + "enabled": true, + "request_interval": 2000, + "freshness_filter": { + "enabled": true, + "max_age_days": 3 + }, + "feeds": [ + {"id": "hacker-news", "name": "Hacker News", "url": "...", "max_age_days": 1} + ] + } + + Returns: + RSSFetcher 实例 + """ # 读取新鲜度过滤配置 freshness_config = config.get("freshness_filter", {}) freshness_enabled = freshness_config.get("enabled", True) # 默认启用 @@ -235,4 +301,4 @@ timezone=config.get("timezone", DEFAULT_TIMEZONE), freshness_enabled=freshness_enabled, default_max_age_days=default_max_age_days, - )+ )
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 = value.strip() if not value: return [] # 尝试 JSON 解析: '["zhihu", "weibo"]' try: parsed = json.loads(value) if isinstance(parsed, list): return [str(item) for item in parsed] # 如果解析结果不是列表,继续尝试其他方式 except json.JSONDecodeError: pass # 尝试 Python 字面量解析: "['zhihu', 'weibo']" try: parsed = ast.literal_eval(value) if isinstance(parsed, list): return [str(item) for item in parsed] if isinstance(parsed, str): # 单个字符串,包装成列表 return [parsed] except (ValueError, SyntaxError): pass # 尝试逗号分隔: "zhihu, weibo" 或 "zhihu,weibo" if ',' in value: items = [item.strip() for item in value.split(',')] return [item for item in items if item] # 单个值 return [value] def _parse_string_to_int(value: str, param_name: str = "参数") -> int: value = value.strip() try: # 尝试直接转换 return int(value) except ValueError: pass # 尝试解析浮点数后取整 try: return int(float(value)) except ValueError: raise InvalidParameterError( f"{param_name} 必须是整数,无法解析: {value}", suggestion=f"请提供有效的整数值,如: 10, 50, 100" ) def _parse_string_to_float(value: str, param_name: str = "参数") -> float: value = value.strip() try: return float(value) except ValueError: raise InvalidParameterError( f"{param_name} 必须是数字,无法解析: {value}", suggestion=f"请提供有效的数字值,如: 0.6, 3.0" ) def _parse_string_to_bool(value: str) -> bool: value = value.strip().lower() if value in ('true', '1', 'yes', 'on'): return True elif value in ('false', '0', 'no', 'off', ''): return False else: # 默认非空字符串为 True return bool(value) # 平台列表 mtime 缓存(避免每次 MCP 调用都重新读取 config.yaml) _platforms_cache: Optional[List[str]] = None _platforms_config_mtime: float = 0.0 _platforms_config_path: Optional[str] = None def get_supported_platforms() -> List[str]: global _platforms_cache, _platforms_config_mtime, _platforms_config_path try: if _platforms_config_path is None: current_dir = os.path.dirname(os.path.abspath(__file__)) _platforms_config_path = os.path.normpath( os.path.join(current_dir, "..", "..", "config", "config.yaml") ) current_mtime = os.path.getmtime(_platforms_config_path) if _platforms_cache is not None and current_mtime == _platforms_config_mtime: return _platforms_cache with open(_platforms_config_path, 'r', encoding='utf-8') as f: config = yaml.safe_load(f) platforms_config = config.get('platforms', {}) sources = platforms_config.get('sources', []) _platforms_cache = [p['id'] for p in sources if 'id' in p] _platforms_config_mtime = current_mtime return _platforms_cache except Exception as e: print(f"警告:无法加载平台配置: {e}") return [] def validate_platforms(platforms: Optional[Union[List[str], str]]) -> List[str]: supported_platforms = get_supported_platforms() if platforms is None: # 返回配置文件中的平台列表(用户的默认配置) return supported_platforms if supported_platforms else [] # 支持字符串形式的列表输入(某些 MCP 客户端会将 JSON 数组序列化为字符串) if isinstance(platforms, str): platforms = _parse_string_to_list(platforms) if not platforms: # 空字符串或解析后为空,使用默认平台 return supported_platforms if supported_platforms else [] if not isinstance(platforms, list): raise InvalidParameterError("platforms 参数必须是列表类型") if not platforms: # 空列表时,返回配置文件中的平台列表 return supported_platforms if supported_platforms else [] # 如果配置加载失败(supported_platforms为空),允许所有平台通过 if not supported_platforms: print("警告:平台配置未加载,跳过平台验证") return platforms # 验证每个平台是否在配置中 invalid_platforms = [p for p in platforms if p not in supported_platforms] if invalid_platforms: raise InvalidParameterError( f"不支持的平台: {', '.join(invalid_platforms)}", suggestion=f"支持的平台(来自config.yaml): {', '.join(supported_platforms)}" ) return platforms def validate_limit(limit: Optional[Union[int, str]], default: int = 20, max_limit: int = 1000) -> int: if limit is None: return default # 支持字符串形式的整数(某些 MCP 客户端会将数字序列化为字符串) if isinstance(limit, str): limit = _parse_string_to_int(limit, "limit") if not isinstance(limit, int): raise InvalidParameterError("limit 参数必须是整数类型") if limit <= 0: raise InvalidParameterError("limit 必须大于0") if limit > max_limit: raise InvalidParameterError( f"limit 不能超过 {max_limit}", suggestion=f"请使用分页或降低limit值" ) return limit def validate_date(date_str: str) -> datetime: try: return datetime.strptime(date_str, "%Y-%m-%d") except ValueError: raise InvalidParameterError( f"日期格式错误: {date_str}", suggestion="请使用 YYYY-MM-DD 格式,例如: 2025-10-11" ) def normalize_date_range(date_range: Optional[Union[dict, str]]) -> Optional[Union[dict, str]]: if date_range is None: return None # 如果已经是 dict,直接返回 if isinstance(date_range, dict): return date_range # 如果是字符串,尝试解析为 JSON if isinstance(date_range, str): # 检查是否看起来像 JSON 对象 stripped = date_range.strip() if stripped.startswith('{') and stripped.endswith('}'): try: parsed = json.loads(stripped) if isinstance(parsed, dict): return parsed except json.JSONDecodeError: pass # 解析失败,当作普通字符串处理 return date_range def validate_date_range(date_range: Optional[Union[dict, str]]) -> Optional[tuple]: if date_range is None: return None # 支持字符串形式的输入 if isinstance(date_range, str): stripped = date_range.strip() # 1. 检查是否是 JSON 对象格式 if stripped.startswith('{') and stripped.endswith('}'): try: date_range = json.loads(stripped) except json.JSONDecodeError as e: raise InvalidParameterError( f"date_range JSON 解析失败: {e}", suggestion='请使用正确的JSON格式: {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}' ) # 2. 检查是否是单日字符串格式 YYYY-MM-DD elif len(stripped) == 10 and stripped[4] == '-' and stripped[7] == '-': try: single_date = datetime.strptime(stripped, "%Y-%m-%d") return (single_date, single_date) except ValueError: raise InvalidParameterError( f"日期格式错误: {stripped}", suggestion="请使用 YYYY-MM-DD 格式,例如: 2025-10-11" ) # 3. 尝试自然语言解析 else: try: result = DateParser.resolve_date_range_expression(stripped) if result.get("success"): dr = result["date_range"] start_date = datetime.strptime(dr["start"], "%Y-%m-%d") end_date = datetime.strptime(dr["end"], "%Y-%m-%d") return (start_date, end_date) else: raise InvalidParameterError( f"无法识别的日期表达式: {stripped}", suggestion="支持格式: YYYY-MM-DD, {\"start\": \"...\", \"end\": \"...\"}, 或自然语言(今天、本周、最近7天等)" ) except InvalidParameterError: raise except Exception: raise InvalidParameterError( f"日期解析失败: {stripped}", suggestion="支持格式: YYYY-MM-DD, {\"start\": \"...\", \"end\": \"...\"}, 或自然语言(今天、本周、最近7天等)" ) if not isinstance(date_range, dict): raise InvalidParameterError( "date_range 必须是字典类型、日期字符串或有效的JSON字符串", suggestion='例如: {"start": "2025-10-01", "end": "2025-10-11"} 或 "2025-10-01"' ) start_str = date_range.get("start") end_str = date_range.get("end") if not start_str or not end_str: raise InvalidParameterError( "date_range 必须包含 start 和 end 字段", suggestion='例如: {"start": "2025-10-01", "end": "2025-10-11"}' ) start_date = validate_date(start_str) end_date = validate_date(end_str) if start_date > end_date: raise InvalidParameterError( "开始日期不能晚于结束日期", suggestion=f"start: {start_str}, end: {end_str}" ) # 检查日期是否在未来 today = datetime.now().date() if start_date.date() > today or end_date.date() > today: # 获取可用日期范围提示 try: from ..services.data_service import DataService data_service = DataService() earliest, latest = data_service.get_available_date_range() if earliest and latest: available_range = f"{earliest.strftime('%Y-%m-%d')} 至 {latest.strftime('%Y-%m-%d')}" else: available_range = "无可用数据" except Exception: available_range = "未知(请检查 output 目录)" future_dates = [] if start_date.date() > today: future_dates.append(start_str) if end_date.date() > today and end_str != start_str: future_dates.append(end_str) raise InvalidParameterError( f"不允许查询未来日期: {', '.join(future_dates)}(当前日期: {today.strftime('%Y-%m-%d')})", suggestion=f"当前可用数据范围: {available_range}" ) return (start_date, end_date) def validate_keyword(keyword: str) -> str: if not keyword: raise InvalidParameterError("keyword 不能为空") if not isinstance(keyword, str): raise InvalidParameterError("keyword 必须是字符串类型") keyword = keyword.strip() if not keyword: raise InvalidParameterError("keyword 不能为空白字符") if len(keyword) > 100: raise InvalidParameterError( "keyword 长度不能超过100个字符", suggestion="请使用更简洁的关键词" ) return keyword def validate_top_n(top_n: Optional[Union[int, str]], default: int = 10) -> int: return validate_limit(top_n, default=default, max_limit=100) def validate_mode(mode: Optional[str], valid_modes: List[str], default: str) -> str: if mode is None: return default if not isinstance(mode, str): raise InvalidParameterError("mode 必须是字符串类型") if mode not in valid_modes: raise InvalidParameterError( f"无效的模式: {mode}", suggestion=f"支持的模式: {', '.join(valid_modes)}" ) return mode def validate_config_section(section: Optional[str]) -> str: valid_sections = ["all", "crawler", "push", "keywords", "weights"] return validate_mode(section, valid_sections, "all") def validate_threshold( threshold: Optional[Union[float, int, str]], default: float = 0.6, min_value: float = 0.0, max_value: float = 1.0, param_name: str = "threshold" ) -> float: if threshold is None: return default # 支持字符串形式的数字(某些 MCP 客户端会将数字序列化为字符串) if isinstance(threshold, str): threshold = _parse_string_to_float(threshold, param_name) # 整数转浮点数 if isinstance(threshold, int): threshold = float(threshold) if not isinstance(threshold, float): raise InvalidParameterError( f"{param_name} 必须是数字类型", suggestion=f"请提供 {min_value} 到 {max_value} 之间的数字" ) if threshold < min_value or threshold > max_value: raise InvalidParameterError( f"{param_name} 必须在 {min_value} 到 {max_value} 之间,当前值: {threshold}", suggestion=f"推荐值: {default}" ) return threshold def validate_date_query( date_query: str, allow_future: bool = False, max_days_ago: int = 365 ) -> datetime: if not date_query: raise InvalidParameterError( "日期查询字符串不能为空", suggestion="请提供日期查询,如:今天、昨天、2025-10-10" ) # 使用DateParser解析日期 parsed_date = DateParser.parse_date_query(date_query) # 验证日期不在未来 if not allow_future: DateParser.validate_date_not_future(parsed_date) # 验证日期不太久远 DateParser.validate_date_not_too_old(parsed_date, max_days=max_days_ago) return parsed_date
--- +++ @@ -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]: + """ + 将字符串解析为列表 + + 支持格式: + - JSON 数组: '["zhihu", "weibo"]' + - Python 列表字符串: "['zhihu', 'weibo']" + - 逗号分隔: "zhihu, weibo" 或 "zhihu,weibo" + + Args: + value: 字符串值 + + Returns: + 解析后的列表 + + Raises: + InvalidParameterError: 解析失败 + """ value = value.strip() if not value: @@ -48,6 +71,19 @@ def _parse_string_to_int(value: str, param_name: str = "参数") -> int: + """ + 将字符串解析为整数 + + Args: + value: 字符串值 + param_name: 参数名(用于错误消息) + + Returns: + 解析后的整数 + + Raises: + InvalidParameterError: 解析失败 + """ value = value.strip() try: @@ -67,6 +103,19 @@ def _parse_string_to_float(value: str, param_name: str = "参数") -> float: + """ + 将字符串解析为浮点数 + + Args: + value: 字符串值 + param_name: 参数名(用于错误消息) + + Returns: + 解析后的浮点数 + + Raises: + InvalidParameterError: 解析失败 + """ value = value.strip() try: @@ -79,6 +128,15 @@ def _parse_string_to_bool(value: str) -> bool: + """ + 将字符串解析为布尔值 + + Args: + value: 字符串值 + + Returns: + 解析后的布尔值 + """ value = value.strip().lower() if value in ('true', '1', 'yes', 'on'): @@ -97,6 +155,18 @@ def get_supported_platforms() -> List[str]: + """ + 从 config.yaml 动态获取支持的平台列表(带 mtime 缓存) + + 仅当 config.yaml 被修改时才重新读取,避免每次 MCP 调用的重复 IO。 + + Returns: + 平台ID列表 + + Note: + - 读取失败时返回空列表,允许所有平台通过(降级策略) + - 平台列表来自 config/config.yaml 中的 platforms 配置 + """ global _platforms_cache, _platforms_config_mtime, _platforms_config_path try: @@ -124,6 +194,30 @@ def validate_platforms(platforms: Optional[Union[List[str], str]]) -> List[str]: + """ + 验证平台列表 + + Args: + platforms: 平台ID列表或字符串,None表示使用 config.yaml 中配置的所有平台 + 支持多种格式: + - None: 使用默认平台 + - ["zhihu", "weibo"]: JSON 数组 + - '["zhihu", "weibo"]': JSON 数组字符串 + - "['zhihu', 'weibo']": Python 列表字符串 + - "zhihu, weibo": 逗号分隔字符串 + - "zhihu": 单个平台字符串 + + Returns: + 验证后的平台列表 + + Raises: + InvalidParameterError: 平台不支持 + + Note: + - platforms=None 时,返回 config.yaml 中配置的平台列表 + - 会验证平台ID是否在 config.yaml 的 platforms 配置中 + - 配置加载失败时,允许所有平台通过(降级策略) + """ supported_platforms = get_supported_platforms() if platforms is None: @@ -161,6 +255,20 @@ def validate_limit(limit: Optional[Union[int, str]], default: int = 20, max_limit: int = 1000) -> int: + """ + 验证数量限制参数 + + Args: + limit: 限制数量(整数或字符串) + default: 默认值 + max_limit: 最大限制 + + Returns: + 验证后的限制值 + + Raises: + InvalidParameterError: 参数无效 + """ if limit is None: return default @@ -184,6 +292,18 @@ def validate_date(date_str: str) -> datetime: + """ + 验证日期格式 + + Args: + date_str: 日期字符串 (YYYY-MM-DD) + + Returns: + datetime对象 + + Raises: + InvalidParameterError: 日期格式错误 + """ try: return datetime.strptime(date_str, "%Y-%m-%d") except ValueError: @@ -194,6 +314,30 @@ def normalize_date_range(date_range: Optional[Union[dict, str]]) -> Optional[Union[dict, str]]: + """ + 规范化 date_range 参数 + + 某些 MCP 客户端(特别是 HTTP 方式)会将 JSON 对象序列化为字符串传入。 + 此函数尝试将 JSON 字符串解析为 dict,如果不是 JSON 格式则保持原样。 + + Args: + date_range: 日期范围,可能是: + - dict: {"start": "2025-01-01", "end": "2025-01-07"} + - JSON 字符串: '{"start": "2025-01-01", "end": "2025-01-07"}' + - 普通字符串: "今天", "昨天", "2025-01-01" + - None + + Returns: + 规范化后的 date_range(dict 或普通字符串) + + Examples: + >>> normalize_date_range('{"start":"2025-01-01","end":"2025-01-07"}') + {"start": "2025-01-01", "end": "2025-01-07"} + >>> normalize_date_range("今天") + "今天" + >>> normalize_date_range({"start": "2025-01-01", "end": "2025-01-07"}) + {"start": "2025-01-01", "end": "2025-01-07"} + """ if date_range is None: return None @@ -217,6 +361,22 @@ def validate_date_range(date_range: Optional[Union[dict, str]]) -> Optional[tuple]: + """ + 验证日期范围 + + Args: + date_range: 日期范围,支持多种格式: + - dict: {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"} + - JSON 字符串: '{"start": "2025-01-01", "end": "2025-01-07"}' + - 单日字符串: "2025-01-01"(自动转为同一天的范围) + - 自然语言: "今天", "昨天", "本周", "最近7天" 等 + + Returns: + (start_date, end_date) 元组,或 None + + Raises: + InvalidParameterError: 日期范围无效 + """ if date_range is None: return None @@ -320,6 +480,18 @@ def validate_keyword(keyword: str) -> str: + """ + 验证关键词 + + Args: + keyword: 搜索关键词 + + Returns: + 处理后的关键词 + + Raises: + InvalidParameterError: 关键词无效 + """ if not keyword: raise InvalidParameterError("keyword 不能为空") @@ -341,10 +513,37 @@ def validate_top_n(top_n: Optional[Union[int, str]], default: int = 10) -> int: + """ + 验证TOP N参数 + + Args: + top_n: TOP N数量(整数或字符串) + default: 默认值 + + Returns: + 验证后的值 + + Raises: + InvalidParameterError: 参数无效 + """ return validate_limit(top_n, default=default, max_limit=100) def validate_mode(mode: Optional[str], valid_modes: List[str], default: str) -> str: + """ + 验证模式参数 + + Args: + mode: 模式字符串 + valid_modes: 有效模式列表 + default: 默认模式 + + Returns: + 验证后的模式 + + Raises: + InvalidParameterError: 模式无效 + """ if mode is None: return default @@ -361,6 +560,18 @@ def validate_config_section(section: Optional[str]) -> str: + """ + 验证配置节参数 + + Args: + section: 配置节名称 + + Returns: + 验证后的配置节 + + Raises: + InvalidParameterError: 配置节无效 + """ valid_sections = ["all", "crawler", "push", "keywords", "weights"] return validate_mode(section, valid_sections, "all") @@ -372,6 +583,22 @@ max_value: float = 1.0, param_name: str = "threshold" ) -> float: + """ + 验证阈值参数(浮点数) + + Args: + threshold: 阈值(浮点数、整数或字符串) + default: 默认值 + min_value: 最小值 + max_value: 最大值 + param_name: 参数名(用于错误消息) + + Returns: + 验证后的阈值 + + Raises: + InvalidParameterError: 参数无效 + """ if threshold is None: return default @@ -403,6 +630,26 @@ allow_future: bool = False, max_days_ago: int = 365 ) -> datetime: + """ + 验证并解析日期查询字符串 + + Args: + date_query: 日期查询字符串 + allow_future: 是否允许未来日期 + max_days_ago: 允许查询的最大天数 + + Returns: + 解析后的datetime对象 + + Raises: + InvalidParameterError: 日期查询无效 + + Examples: + >>> validate_date_query("昨天") + datetime(2025, 10, 10) + >>> validate_date_query("2025-10-10") + datetime(2025, 10, 10) + """ if not date_query: raise InvalidParameterError( "日期查询字符串不能为空", @@ -420,3 +667,4 @@ DateParser.validate_date_not_too_old(parsed_date, max_days=max_days_ago) return parsed_date +
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_root = Path(project_root) else: current_file = Path(__file__) self.project_root = current_file.parent.parent.parent self._config = None self._remote_backend = None def _load_config(self) -> dict: if self._config is None: config_path = self.project_root / "config" / "config.yaml" if config_path.exists(): with open(config_path, "r", encoding="utf-8") as f: self._config = yaml.safe_load(f) else: self._config = {} return self._config def _get_storage_config(self) -> dict: config = self._load_config() return config.get("storage", {}) def _get_remote_config(self) -> dict: storage_config = self._get_storage_config() remote_config = storage_config.get("remote", {}) return { "endpoint_url": remote_config.get("endpoint_url") or os.environ.get("S3_ENDPOINT_URL", ""), "bucket_name": remote_config.get("bucket_name") or os.environ.get("S3_BUCKET_NAME", ""), "access_key_id": remote_config.get("access_key_id") or os.environ.get("S3_ACCESS_KEY_ID", ""), "secret_access_key": remote_config.get("secret_access_key") or os.environ.get("S3_SECRET_ACCESS_KEY", ""), "region": remote_config.get("region") or os.environ.get("S3_REGION", ""), } def _has_remote_config(self) -> bool: config = self._get_remote_config() return bool( config.get("bucket_name") and config.get("access_key_id") and config.get("secret_access_key") and config.get("endpoint_url") ) def _get_remote_backend(self): if self._remote_backend is not None: return self._remote_backend if not self._has_remote_config(): return None try: from trendradar.storage.remote import RemoteStorageBackend remote_config = self._get_remote_config() config = self._load_config() timezone = config.get("app", {}).get("timezone", "Asia/Shanghai") self._remote_backend = RemoteStorageBackend( bucket_name=remote_config["bucket_name"], access_key_id=remote_config["access_key_id"], secret_access_key=remote_config["secret_access_key"], endpoint_url=remote_config["endpoint_url"], region=remote_config.get("region", ""), timezone=timezone, ) return self._remote_backend except ImportError: print("[存储同步] 远程存储后端需要安装 boto3: pip install boto3") return None except Exception as e: print(f"[存储同步] 创建远程后端失败: {e}") return None def _get_local_data_dir(self) -> Path: storage_config = self._get_storage_config() local_config = storage_config.get("local", {}) data_dir = local_config.get("data_dir", "output") return self.project_root / data_dir def _parse_date_folder_name(self, folder_name: str) -> Optional[datetime]: # 尝试 ISO 格式 iso_match = re.match(r'(\d{4})-(\d{2})-(\d{2})', folder_name) if iso_match: try: return datetime( int(iso_match.group(1)), int(iso_match.group(2)), int(iso_match.group(3)) ) except ValueError: pass # 尝试中文格式 chinese_match = re.match(r'(\d{4})年(\d{2})月(\d{2})日', folder_name) if chinese_match: try: return datetime( int(chinese_match.group(1)), int(chinese_match.group(2)), int(chinese_match.group(3)) ) except ValueError: pass return None def _get_local_dates(self, db_type: str = "news") -> List[str]: local_dir = self._get_local_data_dir() dates = set() if not local_dir.exists(): return [] # 扫描 output/{db_type}/{date}.db 文件 type_dir = local_dir / db_type if type_dir.exists(): for item in type_dir.iterdir(): if item.is_file() and item.suffix == ".db": # 从文件名解析日期 (2025-12-30.db -> 2025-12-30) date_str = item.stem # 去除 .db 后缀 folder_date = self._parse_date_folder_name(date_str) if folder_date: dates.add(folder_date.strftime("%Y-%m-%d")) return sorted(list(dates), reverse=True) def _get_all_local_dates(self) -> Dict[str, List[str]]: news_dates = set(self._get_local_dates("news")) rss_dates = set(self._get_local_dates("rss")) all_dates = news_dates | rss_dates return { "news": sorted(list(news_dates), reverse=True), "rss": sorted(list(rss_dates), reverse=True), "all": sorted(list(all_dates), reverse=True) } def _calculate_dir_size(self, path: Path) -> int: total_size = 0 if path.exists(): for item in path.rglob("*"): if item.is_file(): total_size += item.stat().st_size return total_size def sync_from_remote(self, days: int = 7) -> Dict: try: # 检查远程配置 if not self._has_remote_config(): return { "success": False, "error": { "code": "REMOTE_NOT_CONFIGURED", "message": "未配置远程存储", "suggestion": "请在 config/config.yaml 中配置 storage.remote 或设置环境变量" } } # 获取远程后端 remote_backend = self._get_remote_backend() if remote_backend is None: return { "success": False, "error": { "code": "REMOTE_BACKEND_FAILED", "message": "无法创建远程存储后端", "suggestion": "请检查远程存储配置和 boto3 是否已安装" } } # 获取本地数据目录 local_dir = self._get_local_data_dir() local_dir.mkdir(parents=True, exist_ok=True) # 获取远程可用日期 remote_dates = remote_backend.list_remote_dates() # 获取本地已有日期 local_dates = set(self._get_local_dates()) # 计算需要拉取的日期(最近 N 天) from trendradar.utils.time import get_configured_time config = self._load_config() timezone = config.get("app", {}).get("timezone", "Asia/Shanghai") now = get_configured_time(timezone) target_dates = [] for i in range(days): date = now - timedelta(days=i) date_str = date.strftime("%Y-%m-%d") if date_str in remote_dates: target_dates.append(date_str) # 执行拉取 synced_dates = [] skipped_dates = [] failed_dates = [] for date_str in target_dates: # 检查本地是否已存在 if date_str in local_dates: skipped_dates.append(date_str) continue # 拉取单个日期 try: local_date_dir = local_dir / date_str local_db_path = local_date_dir / "news.db" remote_key = f"news/{date_str}.db" local_date_dir.mkdir(parents=True, exist_ok=True) remote_backend.s3_client.download_file( remote_backend.bucket_name, remote_key, str(local_db_path) ) synced_dates.append(date_str) print(f"[存储同步] 已拉取: {date_str}") except Exception as e: failed_dates.append({"date": date_str, "error": str(e)}) print(f"[存储同步] 拉取失败 ({date_str}): {e}") return { "success": True, "summary": { "description": "远程存储同步结果", "synced_files": len(synced_dates), "skipped_count": len(skipped_dates), "failed_count": len(failed_dates) }, "data": { "synced_dates": synced_dates, "skipped_dates": skipped_dates, "failed_dates": failed_dates }, "message": f"成功同步 {len(synced_dates)} 天数据" + ( f",跳过 {len(skipped_dates)} 天(本地已存在)" if skipped_dates else "" ) + ( f",失败 {len(failed_dates)} 天" if failed_dates else "" ) } except MCPError as e: return { "success": False, "error": e.to_dict() } except Exception as e: return { "success": False, "error": { "code": "INTERNAL_ERROR", "message": str(e) } } def get_storage_status(self) -> Dict: try: storage_config = self._get_storage_config() config = self._load_config() # 本地存储状态 local_config = storage_config.get("local", {}) local_dir = self._get_local_data_dir() local_size = self._calculate_dir_size(local_dir) # 获取分类的日期列表 all_dates = self._get_all_local_dates() news_dates = all_dates["news"] rss_dates = all_dates["rss"] combined_dates = all_dates["all"] local_status = { "data_dir": local_config.get("data_dir", "output"), "retention_days": local_config.get("retention_days", 0), "total_size": f"{local_size / 1024 / 1024:.2f} MB", "total_size_bytes": local_size, "date_count": len(combined_dates), "earliest_date": combined_dates[-1] if combined_dates else None, "latest_date": combined_dates[0] if combined_dates else None, "news": { "date_count": len(news_dates), "dates": news_dates[:10], # 最近 10 天 }, "rss": { "date_count": len(rss_dates), "dates": rss_dates[:10], # 最近 10 天 }, } # 远程存储状态 remote_config = storage_config.get("remote", {}) has_remote = self._has_remote_config() remote_status = { "configured": has_remote, "retention_days": remote_config.get("retention_days", 0), } if has_remote: merged_config = self._get_remote_config() # 脱敏显示 endpoint = merged_config.get("endpoint_url", "") bucket = merged_config.get("bucket_name", "") remote_status["endpoint_url"] = endpoint remote_status["bucket_name"] = bucket # 尝试获取远程日期列表 remote_backend = self._get_remote_backend() if remote_backend: try: remote_dates = remote_backend.list_remote_dates() remote_status["date_count"] = len(remote_dates) remote_status["earliest_date"] = remote_dates[-1] if remote_dates else None remote_status["latest_date"] = remote_dates[0] if remote_dates else None except Exception as e: remote_status["error"] = str(e) # 拉取配置状态 pull_config = storage_config.get("pull", {}) pull_status = { "enabled": pull_config.get("enabled", False), "days": pull_config.get("days", 7), } return { "success": True, "summary": { "description": "存储配置和状态信息", "backend": storage_config.get("backend", "auto") }, "data": { "local": local_status, "remote": remote_status, "pull": pull_status } } except MCPError as e: return { "success": False, "error": e.to_dict() } except Exception as e: return { "success": False, "error": { "code": "INTERNAL_ERROR", "message": str(e) } } def list_available_dates(self, source: str = "both") -> Dict: try: data_result = {} summary_info = { "description": "可用日期列表", "source": source } # 本地日期 if source in ("local", "both"): all_dates = self._get_all_local_dates() news_dates = all_dates["news"] rss_dates = all_dates["rss"] combined_dates = all_dates["all"] data_result["local"] = { "dates": combined_dates, "count": len(combined_dates), "earliest": combined_dates[-1] if combined_dates else None, "latest": combined_dates[0] if combined_dates else None, "news": { "dates": news_dates, "count": len(news_dates), }, "rss": { "dates": rss_dates, "count": len(rss_dates), }, } # 远程日期 if source in ("remote", "both"): if not self._has_remote_config(): data_result["remote"] = { "configured": False, "dates": [], "count": 0, "earliest": None, "latest": None, "error": "未配置远程存储" } else: remote_backend = self._get_remote_backend() if remote_backend: try: remote_dates = remote_backend.list_remote_dates() data_result["remote"] = { "configured": True, "dates": remote_dates, "count": len(remote_dates), "earliest": remote_dates[-1] if remote_dates else None, "latest": remote_dates[0] if remote_dates else None, } except Exception as e: data_result["remote"] = { "configured": True, "dates": [], "count": 0, "earliest": None, "latest": None, "error": str(e) } else: data_result["remote"] = { "configured": True, "dates": [], "count": 0, "earliest": None, "latest": None, "error": "无法创建远程存储后端" } # 如果同时查询两者,计算差异 if source == "both" and "local" in data_result and "remote" in data_result: local_set = set(data_result["local"]["dates"]) remote_set = set(data_result["remote"].get("dates", [])) data_result["comparison"] = { "only_local": sorted(list(local_set - remote_set), reverse=True), "only_remote": sorted(list(remote_set - local_set), reverse=True), "both": sorted(list(local_set & remote_set), reverse=True), } return { "success": True, "summary": summary_info, "data": data_result } except MCPError as e: return { "success": False, "error": e.to_dict() } except Exception as e: return { "success": False, "error": { "code": "INTERNAL_ERROR", "message": str(e) } }
--- +++ @@ -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: 项目根目录 + """ if project_root: self.project_root = Path(project_root) else: @@ -24,6 +36,7 @@ self._remote_backend = None def _load_config(self) -> dict: + """加载配置文件""" if self._config is None: config_path = self.project_root / "config" / "config.yaml" if config_path.exists(): @@ -34,10 +47,14 @@ return self._config def _get_storage_config(self) -> dict: + """获取存储配置""" config = self._load_config() return config.get("storage", {}) def _get_remote_config(self) -> dict: + """ + 获取远程存储配置(合并配置文件和环境变量) + """ storage_config = self._get_storage_config() remote_config = storage_config.get("remote", {}) @@ -50,6 +67,7 @@ } def _has_remote_config(self) -> bool: + """检查是否有有效的远程存储配置""" config = self._get_remote_config() return bool( config.get("bucket_name") and @@ -59,6 +77,7 @@ ) def _get_remote_backend(self): + """获取远程存储后端实例""" if self._remote_backend is not None: return self._remote_backend @@ -89,12 +108,20 @@ return None def _get_local_data_dir(self) -> Path: + """获取本地数据目录""" storage_config = self._get_storage_config() local_config = storage_config.get("local", {}) data_dir = local_config.get("data_dir", "output") return self.project_root / data_dir def _parse_date_folder_name(self, folder_name: str) -> Optional[datetime]: + """ + 解析日期文件夹名称(兼容中文和 ISO 格式) + + 支持两种格式: + - 中文格式:YYYY年MM月DD日 + - ISO 格式:YYYY-MM-DD + """ # 尝试 ISO 格式 iso_match = re.match(r'(\d{4})-(\d{2})-(\d{2})', folder_name) if iso_match: @@ -122,6 +149,18 @@ return None def _get_local_dates(self, db_type: str = "news") -> List[str]: + """ + 获取本地可用的日期列表 + + 存储结构: output/{db_type}/{date}.db + 例如: output/news/2025-12-30.db, output/rss/2025-12-30.db + + Args: + db_type: 数据库类型 ("news" 或 "rss"),默认 "news" + + Returns: + 日期列表(按时间倒序) + """ local_dir = self._get_local_data_dir() dates = set() @@ -142,6 +181,16 @@ return sorted(list(dates), reverse=True) def _get_all_local_dates(self) -> Dict[str, List[str]]: + """ + 获取所有本地可用的日期列表(包括 news 和 rss) + + Returns: + { + "news": ["2025-12-30", ...], + "rss": ["2025-12-30", ...], + "all": ["2025-12-30", ...] # 合并去重 + } + """ news_dates = set(self._get_local_dates("news")) rss_dates = set(self._get_local_dates("rss")) all_dates = news_dates | rss_dates @@ -153,6 +202,7 @@ } def _calculate_dir_size(self, path: Path) -> int: + """计算目录大小(字节)""" total_size = 0 if path.exists(): for item in path.rglob("*"): @@ -161,6 +211,15 @@ return total_size def sync_from_remote(self, days: int = 7) -> Dict: + """ + 从远程存储拉取数据到本地 + + Args: + days: 拉取最近 N 天的数据,默认 7 天 + + Returns: + 同步结果字典 + """ try: # 检查远程配置 if not self._has_remote_config(): @@ -272,6 +331,12 @@ } def get_storage_status(self) -> Dict: + """ + 获取存储配置和状态 + + Returns: + 存储状态字典 + """ try: storage_config = self._get_storage_config() config = self._load_config() @@ -368,6 +433,18 @@ } def list_available_dates(self, source: str = "both") -> Dict: + """ + 列出可用的日期范围 + + Args: + source: 数据来源 + - "local": 仅本地 + - "remote": 仅远程 + - "both": 两者都列出(默认) + + Returns: + 日期列表字典 + """ try: data_result = {} summary_info = { @@ -468,4 +545,4 @@ "code": "INTERNAL_ERROR", "message": str(e) } - }+ }
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().lower() if not value: return None return value in ("true", "1") def _get_env_int(key: str, default: int = 0) -> int: value = os.environ.get(key, "").strip() if not value: return default try: return int(value) except ValueError: return default def _get_env_int_or_none(key: str) -> Optional[int]: value = os.environ.get(key, "").strip() if not value: return None try: return int(value) except ValueError: return None def _get_env_str(key: str, default: str = "") -> str: return os.environ.get(key, "").strip() or default def _load_app_config(config_data: Dict) -> Dict: app_config = config_data.get("app", {}) advanced = config_data.get("advanced", {}) return { "VERSION_CHECK_URL": advanced.get("version_check_url", ""), "CONFIGS_VERSION_CHECK_URL": advanced.get("configs_version_check_url", ""), "SHOW_VERSION_UPDATE": app_config.get("show_version_update", True), "TIMEZONE": _get_env_str("TIMEZONE") or app_config.get("timezone", DEFAULT_TIMEZONE), "DEBUG": _get_env_bool("DEBUG") if _get_env_bool("DEBUG") is not None else advanced.get("debug", False), } def _load_crawler_config(config_data: Dict) -> Dict: advanced = config_data.get("advanced", {}) crawler_config = advanced.get("crawler", {}) platforms_config = config_data.get("platforms", {}) return { "REQUEST_INTERVAL": crawler_config.get("request_interval", 100), "USE_PROXY": crawler_config.get("use_proxy", False), "DEFAULT_PROXY": crawler_config.get("default_proxy", ""), "ENABLE_CRAWLER": platforms_config.get("enabled", True), } def _load_report_config(config_data: Dict) -> Dict: report_config = config_data.get("report", {}) # 环境变量覆盖 sort_by_position_env = _get_env_bool("SORT_BY_POSITION_FIRST") max_news_env = _get_env_int("MAX_NEWS_PER_KEYWORD") return { "REPORT_MODE": report_config.get("mode", "daily"), "DISPLAY_MODE": report_config.get("display_mode", "keyword"), "RANK_THRESHOLD": report_config.get("rank_threshold", 10), "SORT_BY_POSITION_FIRST": sort_by_position_env if sort_by_position_env is not None else report_config.get("sort_by_position_first", False), "MAX_NEWS_PER_KEYWORD": max_news_env or report_config.get("max_news_per_keyword", 0), } def _load_notification_config(config_data: Dict) -> Dict: notification = config_data.get("notification", {}) advanced = config_data.get("advanced", {}) batch_size = advanced.get("batch_size", {}) return { "ENABLE_NOTIFICATION": notification.get("enabled", True), "MESSAGE_BATCH_SIZE": batch_size.get("default", 4000), "DINGTALK_BATCH_SIZE": batch_size.get("dingtalk", 20000), "FEISHU_BATCH_SIZE": batch_size.get("feishu", 29000), "BARK_BATCH_SIZE": batch_size.get("bark", 3600), "SLACK_BATCH_SIZE": batch_size.get("slack", 4000), "BATCH_SEND_INTERVAL": advanced.get("batch_send_interval", 1.0), "FEISHU_MESSAGE_SEPARATOR": advanced.get("feishu_message_separator", "---"), "MAX_ACCOUNTS_PER_CHANNEL": _get_env_int("MAX_ACCOUNTS_PER_CHANNEL") or advanced.get("max_accounts_per_channel", 3), } def _load_schedule_config(config_data: Dict) -> Dict: schedule = config_data.get("schedule", {}) # 环境变量覆盖 enabled_env = _get_env_bool("SCHEDULE_ENABLED") preset_env = _get_env_str("SCHEDULE_PRESET") enabled = enabled_env if enabled_env is not None else schedule.get("enabled", False) preset = preset_env or schedule.get("preset", "always_on") return { "enabled": enabled, "preset": preset, } def _load_timeline_data(config_dir: str = "config") -> Dict: timeline_path = Path(config_dir) / "timeline.yaml" if not timeline_path.exists(): print(f"[调度] timeline.yaml 未找到: {timeline_path},使用空模板") return { "presets": {}, "custom": { "default": { "collect": True, "analyze": False, "push": False, "report_mode": "current", "ai_mode": "follow_report", "once": {"analyze": False, "push": False}, }, "periods": {}, "day_plans": {"all_day": {"periods": []}}, "week_map": {i: "all_day" for i in range(1, 8)}, }, } with open(timeline_path, "r", encoding="utf-8") as f: data = yaml.safe_load(f) print(f"[调度] timeline.yaml 加载成功: {timeline_path}") return data or {} def _load_weight_config(config_data: Dict) -> Dict: advanced = config_data.get("advanced", {}) weight = advanced.get("weight", {}) return { "RANK_WEIGHT": weight.get("rank", 0.6), "FREQUENCY_WEIGHT": weight.get("frequency", 0.3), "HOTNESS_WEIGHT": weight.get("hotness", 0.1), } def _load_rss_config(config_data: Dict) -> Dict: rss = config_data.get("rss", {}) advanced = config_data.get("advanced", {}) advanced_rss = advanced.get("rss", {}) advanced_crawler = advanced.get("crawler", {}) # RSS 代理配置:优先使用 RSS 专属代理,否则复用 crawler 的 default_proxy rss_proxy_url = advanced_rss.get("proxy_url", "") or advanced_crawler.get("default_proxy", "") # 新鲜度过滤配置 freshness_filter = rss.get("freshness_filter", {}) # 验证并设置 max_age_days 默认值 raw_max_age = freshness_filter.get("max_age_days", 3) try: max_age_days = int(raw_max_age) if max_age_days < 0: print(f"[警告] RSS freshness_filter.max_age_days 为负数 ({max_age_days}),使用默认值 3") max_age_days = 3 except (ValueError, TypeError): print(f"[警告] RSS freshness_filter.max_age_days 格式错误 ({raw_max_age}),使用默认值 3") max_age_days = 3 # RSS 配置直接从 config.yaml 读取,不再支持环境变量 return { "ENABLED": rss.get("enabled", False), "REQUEST_INTERVAL": advanced_rss.get("request_interval", 2000), "TIMEOUT": advanced_rss.get("timeout", 15), "USE_PROXY": advanced_rss.get("use_proxy", False), "PROXY_URL": rss_proxy_url, "FEEDS": rss.get("feeds", []), "FRESHNESS_FILTER": { "ENABLED": freshness_filter.get("enabled", True), # 默认启用 "MAX_AGE_DAYS": max_age_days, }, } def _load_display_config(config_data: Dict) -> Dict: display = config_data.get("display", {}) regions = display.get("regions", {}) standalone = display.get("standalone", {}) # 默认区域顺序 default_region_order = ["hotlist", "rss", "new_items", "standalone", "ai_analysis"] region_order = display.get("region_order", default_region_order) # 验证 region_order 中的值是否合法 valid_regions = {"hotlist", "rss", "new_items", "standalone", "ai_analysis"} region_order = [r for r in region_order if r in valid_regions] # 如果过滤后为空,使用默认顺序 if not region_order: region_order = default_region_order return { # 区域显示顺序 "REGION_ORDER": region_order, # 区域开关 "REGIONS": { "HOTLIST": regions.get("hotlist", True), "NEW_ITEMS": regions.get("new_items", True), "RSS": regions.get("rss", True), "STANDALONE": regions.get("standalone", False), "AI_ANALYSIS": regions.get("ai_analysis", True), }, # 独立展示区配置 "STANDALONE": { "PLATFORMS": standalone.get("platforms", []), "RSS_FEEDS": standalone.get("rss_feeds", []), "MAX_ITEMS": standalone.get("max_items", 20), }, } def _load_ai_config(config_data: Dict) -> Dict: ai_config = config_data.get("ai", {}) timeout_env = _get_env_int_or_none("AI_TIMEOUT") return { # LiteLLM 核心配置 "MODEL": _get_env_str("AI_MODEL") or ai_config.get("model", ""), "API_KEY": _get_env_str("AI_API_KEY") or ai_config.get("api_key", ""), "API_BASE": _get_env_str("AI_API_BASE") or ai_config.get("api_base", ""), # 生成参数 "TIMEOUT": timeout_env if timeout_env is not None else ai_config.get("timeout", 120), "TEMPERATURE": ai_config.get("temperature", 1.0), "MAX_TOKENS": ai_config.get("max_tokens", 5000), # LiteLLM 高级选项 "NUM_RETRIES": ai_config.get("num_retries", 2), "FALLBACK_MODELS": ai_config.get("fallback_models", []), "EXTRA_PARAMS": ai_config.get("extra_params", {}), } def _load_ai_analysis_config(config_data: Dict) -> Dict: ai_config = config_data.get("ai_analysis", {}) enabled_env = _get_env_bool("AI_ANALYSIS_ENABLED") return { "ENABLED": enabled_env if enabled_env is not None else ai_config.get("enabled", False), "LANGUAGE": ai_config.get("language", "Chinese"), "PROMPT_FILE": ai_config.get("prompt_file", "ai_analysis_prompt.txt"), "MODE": ai_config.get("mode", "follow_report"), "MAX_NEWS_FOR_ANALYSIS": ai_config.get("max_news_for_analysis", 50), "INCLUDE_RSS": ai_config.get("include_rss", True), "INCLUDE_RANK_TIMELINE": ai_config.get("include_rank_timeline", False), "INCLUDE_STANDALONE": ai_config.get("include_standalone", False), } def _load_ai_translation_config(config_data: Dict) -> Dict: trans_config = config_data.get("ai_translation", {}) enabled_env = _get_env_bool("AI_TRANSLATION_ENABLED") scope = trans_config.get("scope", {}) return { "ENABLED": enabled_env if enabled_env is not None else trans_config.get("enabled", False), "LANGUAGE": _get_env_str("AI_TRANSLATION_LANGUAGE") or trans_config.get("language", "English"), "PROMPT_FILE": trans_config.get("prompt_file", "ai_translation_prompt.txt"), "SCOPE": { "HOTLIST": scope.get("hotlist", True), "RSS": scope.get("rss", True), "STANDALONE": scope.get("standalone", True), }, } def _load_ai_filter_config(config_data: Dict) -> Dict: ai_filter = config_data.get("ai_filter", {}) return { "BATCH_SIZE": ai_filter.get("batch_size", 200), "BATCH_INTERVAL": ai_filter.get("batch_interval", 5), "INTERESTS_FILE": ai_filter.get("interests_file"), # None = 使用默认 config/ai_interests.txt "PROMPT_FILE": ai_filter.get("prompt_file", "prompt.txt"), "EXTRACT_PROMPT_FILE": ai_filter.get("extract_prompt_file", "extract_prompt.txt"), "UPDATE_TAGS_PROMPT_FILE": ai_filter.get("update_tags_prompt_file", "update_tags_prompt.txt"), "RECLASSIFY_THRESHOLD": ai_filter.get("reclassify_threshold", 0.6), "MIN_SCORE": float(ai_filter.get("min_score", 0)), } def _load_filter_config(config_data: Dict) -> Dict: filter_cfg = config_data.get("filter", {}) # 环境变量兼容:AI_FILTER_ENABLED=true → method=ai env_ai_filter = _get_env_bool("AI_FILTER_ENABLED") method = filter_cfg.get("method", "keyword") if env_ai_filter is True: method = "ai" # 兼容旧配置:如果 ai_filter.enabled=true 且未显式设置 filter.method if method == "keyword" and not filter_cfg.get("method"): ai_filter = config_data.get("ai_filter", {}) if ai_filter.get("enabled", False): method = "ai" return { "METHOD": method, # "keyword" | "ai" "PRIORITY_SORT_ENABLED": filter_cfg.get("priority_sort_enabled", False), # AI 模式标签优先级排序开关 } def _load_storage_config(config_data: Dict) -> Dict: storage = config_data.get("storage", {}) formats = storage.get("formats", {}) local = storage.get("local", {}) remote = storage.get("remote", {}) pull = storage.get("pull", {}) txt_enabled_env = _get_env_bool("STORAGE_TXT_ENABLED") html_enabled_env = _get_env_bool("STORAGE_HTML_ENABLED") pull_enabled_env = _get_env_bool("PULL_ENABLED") return { "BACKEND": _get_env_str("STORAGE_BACKEND") or storage.get("backend", "auto"), "FORMATS": { "SQLITE": formats.get("sqlite", True), "TXT": txt_enabled_env if txt_enabled_env is not None else formats.get("txt", True), "HTML": html_enabled_env if html_enabled_env is not None else formats.get("html", True), }, "LOCAL": { "DATA_DIR": local.get("data_dir", "output"), "RETENTION_DAYS": _get_env_int("LOCAL_RETENTION_DAYS") or local.get("retention_days", 0), }, "REMOTE": { "ENDPOINT_URL": _get_env_str("S3_ENDPOINT_URL") or remote.get("endpoint_url", ""), "BUCKET_NAME": _get_env_str("S3_BUCKET_NAME") or remote.get("bucket_name", ""), "ACCESS_KEY_ID": _get_env_str("S3_ACCESS_KEY_ID") or remote.get("access_key_id", ""), "SECRET_ACCESS_KEY": _get_env_str("S3_SECRET_ACCESS_KEY") or remote.get("secret_access_key", ""), "REGION": _get_env_str("S3_REGION") or remote.get("region", ""), "RETENTION_DAYS": _get_env_int("REMOTE_RETENTION_DAYS") or remote.get("retention_days", 0), }, "PULL": { "ENABLED": pull_enabled_env if pull_enabled_env is not None else pull.get("enabled", False), "DAYS": _get_env_int("PULL_DAYS") or pull.get("days", 7), }, } def _load_webhook_config(config_data: Dict) -> Dict: notification = config_data.get("notification", {}) channels = notification.get("channels", {}) # 各渠道配置 feishu = channels.get("feishu", {}) dingtalk = channels.get("dingtalk", {}) wework = channels.get("wework", {}) telegram = channels.get("telegram", {}) email = channels.get("email", {}) ntfy = channels.get("ntfy", {}) bark = channels.get("bark", {}) slack = channels.get("slack", {}) generic = channels.get("generic_webhook", {}) return { # 飞书 "FEISHU_WEBHOOK_URL": _get_env_str("FEISHU_WEBHOOK_URL") or feishu.get("webhook_url", ""), # 钉钉 "DINGTALK_WEBHOOK_URL": _get_env_str("DINGTALK_WEBHOOK_URL") or dingtalk.get("webhook_url", ""), # 企业微信 "WEWORK_WEBHOOK_URL": _get_env_str("WEWORK_WEBHOOK_URL") or wework.get("webhook_url", ""), "WEWORK_MSG_TYPE": _get_env_str("WEWORK_MSG_TYPE") or wework.get("msg_type", "markdown"), # Telegram "TELEGRAM_BOT_TOKEN": _get_env_str("TELEGRAM_BOT_TOKEN") or telegram.get("bot_token", ""), "TELEGRAM_CHAT_ID": _get_env_str("TELEGRAM_CHAT_ID") or telegram.get("chat_id", ""), # 邮件 "EMAIL_FROM": _get_env_str("EMAIL_FROM") or email.get("from", ""), "EMAIL_PASSWORD": _get_env_str("EMAIL_PASSWORD") or email.get("password", ""), "EMAIL_TO": _get_env_str("EMAIL_TO") or email.get("to", ""), "EMAIL_SMTP_SERVER": _get_env_str("EMAIL_SMTP_SERVER") or email.get("smtp_server", ""), "EMAIL_SMTP_PORT": _get_env_str("EMAIL_SMTP_PORT") or email.get("smtp_port", ""), # ntfy "NTFY_SERVER_URL": _get_env_str("NTFY_SERVER_URL") or ntfy.get("server_url") or "https://ntfy.sh", "NTFY_TOPIC": _get_env_str("NTFY_TOPIC") or ntfy.get("topic", ""), "NTFY_TOKEN": _get_env_str("NTFY_TOKEN") or ntfy.get("token", ""), # Bark "BARK_URL": _get_env_str("BARK_URL") or bark.get("url", ""), # Slack "SLACK_WEBHOOK_URL": _get_env_str("SLACK_WEBHOOK_URL") or slack.get("webhook_url", ""), # 通用 Webhook "GENERIC_WEBHOOK_URL": _get_env_str("GENERIC_WEBHOOK_URL") or generic.get("webhook_url", ""), "GENERIC_WEBHOOK_TEMPLATE": _get_env_str("GENERIC_WEBHOOK_TEMPLATE") or generic.get("payload_template", ""), } def _print_notification_sources(config: Dict) -> None: notification_sources = [] max_accounts = config["MAX_ACCOUNTS_PER_CHANNEL"] if config["FEISHU_WEBHOOK_URL"]: accounts = parse_multi_account_config(config["FEISHU_WEBHOOK_URL"]) count = min(len(accounts), max_accounts) source = "环境变量" if os.environ.get("FEISHU_WEBHOOK_URL") else "配置文件" notification_sources.append(f"飞书({source}, {count}个账号)") if config["DINGTALK_WEBHOOK_URL"]: accounts = parse_multi_account_config(config["DINGTALK_WEBHOOK_URL"]) count = min(len(accounts), max_accounts) source = "环境变量" if os.environ.get("DINGTALK_WEBHOOK_URL") else "配置文件" notification_sources.append(f"钉钉({source}, {count}个账号)") if config["WEWORK_WEBHOOK_URL"]: accounts = parse_multi_account_config(config["WEWORK_WEBHOOK_URL"]) count = min(len(accounts), max_accounts) source = "环境变量" if os.environ.get("WEWORK_WEBHOOK_URL") else "配置文件" notification_sources.append(f"企业微信({source}, {count}个账号)") if config["TELEGRAM_BOT_TOKEN"] and config["TELEGRAM_CHAT_ID"]: tokens = parse_multi_account_config(config["TELEGRAM_BOT_TOKEN"]) chat_ids = parse_multi_account_config(config["TELEGRAM_CHAT_ID"]) valid, count = validate_paired_configs( {"bot_token": tokens, "chat_id": chat_ids}, "Telegram", required_keys=["bot_token", "chat_id"] ) if valid and count > 0: count = min(count, max_accounts) token_source = "环境变量" if os.environ.get("TELEGRAM_BOT_TOKEN") else "配置文件" notification_sources.append(f"Telegram({token_source}, {count}个账号)") if config["EMAIL_FROM"] and config["EMAIL_PASSWORD"] and config["EMAIL_TO"]: from_source = "环境变量" if os.environ.get("EMAIL_FROM") else "配置文件" notification_sources.append(f"邮件({from_source})") if config["NTFY_SERVER_URL"] and config["NTFY_TOPIC"]: topics = parse_multi_account_config(config["NTFY_TOPIC"]) tokens = parse_multi_account_config(config["NTFY_TOKEN"]) if tokens: valid, count = validate_paired_configs( {"topic": topics, "token": tokens}, "ntfy" ) if valid and count > 0: count = min(count, max_accounts) server_source = "环境变量" if os.environ.get("NTFY_SERVER_URL") else "配置文件" notification_sources.append(f"ntfy({server_source}, {count}个账号)") else: count = min(len(topics), max_accounts) server_source = "环境变量" if os.environ.get("NTFY_SERVER_URL") else "配置文件" notification_sources.append(f"ntfy({server_source}, {count}个账号)") if config["BARK_URL"]: accounts = parse_multi_account_config(config["BARK_URL"]) count = min(len(accounts), max_accounts) bark_source = "环境变量" if os.environ.get("BARK_URL") else "配置文件" notification_sources.append(f"Bark({bark_source}, {count}个账号)") if config["SLACK_WEBHOOK_URL"]: accounts = parse_multi_account_config(config["SLACK_WEBHOOK_URL"]) count = min(len(accounts), max_accounts) slack_source = "环境变量" if os.environ.get("SLACK_WEBHOOK_URL") else "配置文件" notification_sources.append(f"Slack({slack_source}, {count}个账号)") if config.get("GENERIC_WEBHOOK_URL"): accounts = parse_multi_account_config(config["GENERIC_WEBHOOK_URL"]) count = min(len(accounts), max_accounts) source = "环境变量" if os.environ.get("GENERIC_WEBHOOK_URL") else "配置文件" notification_sources.append(f"通用Webhook({source}, {count}个账号)") if notification_sources: print(f"通知渠道配置来源: {', '.join(notification_sources)}") print(f"每个渠道最大账号数: {max_accounts}") else: print("未配置任何通知渠道") def load_config(config_path: Optional[str] = None) -> Dict[str, Any]: if config_path is None: config_path = os.environ.get("CONFIG_PATH", "config/config.yaml") if not Path(config_path).exists(): raise FileNotFoundError(f"配置文件 {config_path} 不存在") with open(config_path, "r", encoding="utf-8") as f: config_data = yaml.safe_load(f) print(f"配置文件加载成功: {config_path}") # 合并所有配置 config = {} # 应用配置 config.update(_load_app_config(config_data)) # 爬虫配置 config.update(_load_crawler_config(config_data)) # 报告配置 config.update(_load_report_config(config_data)) # 通知配置 config.update(_load_notification_config(config_data)) # 统一调度配置 config["SCHEDULE"] = _load_schedule_config(config_data) config["_TIMELINE_DATA"] = _load_timeline_data( str(Path(config_path).parent) if config_path else "config" ) # 权重配置 config["WEIGHT_CONFIG"] = _load_weight_config(config_data) # 平台配置 platforms_config = config_data.get("platforms", {}) config["PLATFORMS"] = platforms_config.get("sources", []) # RSS 配置 config["RSS"] = _load_rss_config(config_data) # AI 模型共享配置 config["AI"] = _load_ai_config(config_data) # AI 分析配置 config["AI_ANALYSIS"] = _load_ai_analysis_config(config_data) # AI 翻译配置 config["AI_TRANSLATION"] = _load_ai_translation_config(config_data) # AI 智能筛选配置 config["AI_FILTER"] = _load_ai_filter_config(config_data) # 筛选策略配置 config["FILTER"] = _load_filter_config(config_data) # 推送内容显示配置 config["DISPLAY"] = _load_display_config(config_data) # 存储配置 config["STORAGE"] = _load_storage_config(config_data) # Webhook 配置 config.update(_load_webhook_config(config_data)) # 打印通知渠道配置来源 _print_notification_sources(config) return config
--- +++ @@ -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 @@ -18,6 +24,7 @@ def _get_env_int(key: str, default: int = 0) -> int: + """从环境变量获取整数值""" value = os.environ.get(key, "").strip() if not value: return default @@ -28,6 +35,7 @@ def _get_env_int_or_none(key: str) -> Optional[int]: + """从环境变量获取整数值,未设置时返回 None""" value = os.environ.get(key, "").strip() if not value: return None @@ -38,10 +46,12 @@ def _get_env_str(key: str, default: str = "") -> str: + """从环境变量获取字符串值""" return os.environ.get(key, "").strip() or default def _load_app_config(config_data: Dict) -> Dict: + """加载应用配置""" app_config = config_data.get("app", {}) advanced = config_data.get("advanced", {}) return { @@ -54,6 +64,7 @@ def _load_crawler_config(config_data: Dict) -> Dict: + """加载爬虫配置""" advanced = config_data.get("advanced", {}) crawler_config = advanced.get("crawler", {}) platforms_config = config_data.get("platforms", {}) @@ -66,6 +77,7 @@ def _load_report_config(config_data: Dict) -> Dict: + """加载报告配置""" report_config = config_data.get("report", {}) # 环境变量覆盖 @@ -82,6 +94,7 @@ def _load_notification_config(config_data: Dict) -> Dict: + """加载通知配置""" notification = config_data.get("notification", {}) advanced = config_data.get("advanced", {}) batch_size = advanced.get("batch_size", {}) @@ -100,6 +113,11 @@ def _load_schedule_config(config_data: Dict) -> Dict: + """ + 加载统一调度配置 + + 从 config.yaml 的 schedule 段读取,支持环境变量覆盖。 + """ schedule = config_data.get("schedule", {}) # 环境变量覆盖 @@ -116,6 +134,15 @@ def _load_timeline_data(config_dir: str = "config") -> Dict: + """ + 加载 timeline.yaml + + Args: + config_dir: 配置目录路径 + + Returns: + timeline.yaml 的完整数据,找不到时返回空模板 + """ timeline_path = Path(config_dir) / "timeline.yaml" if not timeline_path.exists(): print(f"[调度] timeline.yaml 未找到: {timeline_path},使用空模板") @@ -144,6 +171,7 @@ def _load_weight_config(config_data: Dict) -> Dict: + """加载权重配置""" advanced = config_data.get("advanced", {}) weight = advanced.get("weight", {}) return { @@ -154,6 +182,7 @@ def _load_rss_config(config_data: Dict) -> Dict: + """加载 RSS 配置""" rss = config_data.get("rss", {}) advanced = config_data.get("advanced", {}) advanced_rss = advanced.get("rss", {}) @@ -192,6 +221,7 @@ def _load_display_config(config_data: Dict) -> Dict: + """加载推送内容显示配置""" display = config_data.get("display", {}) regions = display.get("regions", {}) standalone = display.get("standalone", {}) @@ -229,6 +259,7 @@ def _load_ai_config(config_data: Dict) -> Dict: + """加载 AI 模型配置(LiteLLM 格式)""" ai_config = config_data.get("ai", {}) timeout_env = _get_env_int_or_none("AI_TIMEOUT") @@ -252,6 +283,7 @@ def _load_ai_analysis_config(config_data: Dict) -> Dict: + """加载 AI 分析配置(功能配置,模型配置见 _load_ai_config)""" ai_config = config_data.get("ai_analysis", {}) enabled_env = _get_env_bool("AI_ANALYSIS_ENABLED") @@ -269,6 +301,7 @@ def _load_ai_translation_config(config_data: Dict) -> Dict: + """加载 AI 翻译配置(功能配置,模型配置见 _load_ai_config)""" trans_config = config_data.get("ai_translation", {}) enabled_env = _get_env_bool("AI_TRANSLATION_ENABLED") @@ -288,6 +321,7 @@ def _load_ai_filter_config(config_data: Dict) -> Dict: + """加载 AI 智能筛选配置(由 filter.method 控制是否启用)""" ai_filter = config_data.get("ai_filter", {}) return { @@ -303,6 +337,7 @@ def _load_filter_config(config_data: Dict) -> Dict: + """加载筛选策略配置""" filter_cfg = config_data.get("filter", {}) # 环境变量兼容:AI_FILTER_ENABLED=true → method=ai @@ -325,6 +360,7 @@ def _load_storage_config(config_data: Dict) -> Dict: + """加载存储配置""" storage = config_data.get("storage", {}) formats = storage.get("formats", {}) local = storage.get("local", {}) @@ -362,6 +398,7 @@ def _load_webhook_config(config_data: Dict) -> Dict: + """加载 Webhook 配置""" notification = config_data.get("notification", {}) channels = notification.get("channels", {}) @@ -408,6 +445,7 @@ def _print_notification_sources(config: Dict) -> None: + """打印通知渠道配置来源信息""" notification_sources = [] max_accounts = config["MAX_ACCOUNTS_PER_CHANNEL"] @@ -489,6 +527,18 @@ def load_config(config_path: Optional[str] = None) -> Dict[str, Any]: + """ + 加载配置文件 + + Args: + config_path: 配置文件路径,默认从环境变量 CONFIG_PATH 获取或使用 config/config.yaml + + Returns: + 包含所有配置的字典 + + Raises: + FileNotFoundError: 配置文件不存在 + """ if config_path is None: config_path = os.environ.get("CONFIG_PATH", "config/config.yaml") @@ -558,4 +608,4 @@ # 打印通知渠道配置来源 _print_notification_sources(config) - return config+ return config
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 trendradar.core import load_config, parse_multi_account_config, validate_paired_configs from trendradar.core.analyzer import convert_keyword_stats_to_platform_stats from trendradar.crawler import DataFetcher from trendradar.storage import convert_crawl_results_to_news_data from trendradar.utils.time import DEFAULT_TIMEZONE, is_within_days, calculate_days_old from trendradar.ai import AIAnalyzer, AIAnalysisResult from trendradar.core.scheduler import ResolvedSchedule def _parse_version(version_str: str) -> Tuple[int, int, int]: try: parts = version_str.strip().split(".") if len(parts) >= 3: return int(parts[0]), int(parts[1]), int(parts[2]) return 0, 0, 0 except: return 0, 0, 0 def _compare_version(local: str, remote: str) -> str: local_tuple = _parse_version(local) remote_tuple = _parse_version(remote) if local_tuple < remote_tuple: return "⚠️ 需要更新" elif local_tuple > remote_tuple: return "🔮 超前版本" else: return "✅ 已是最新" def _fetch_remote_version(version_url: str, proxy_url: Optional[str] = None) -> Optional[str]: try: proxies = None if proxy_url: proxies = {"http": proxy_url, "https": proxy_url} headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", "Accept": "text/plain, */*", "Cache-Control": "no-cache", } response = requests.get(version_url, proxies=proxies, headers=headers, timeout=10) response.raise_for_status() return response.text.strip() except Exception as e: print(f"[版本检查] 获取远程版本失败: {e}") return None def _parse_config_versions(content: str) -> Dict[str, str]: versions = {} try: if not content: return versions for line in content.splitlines(): line = line.strip() if not line or "=" not in line: continue name, version = line.split("=", 1) versions[name.strip()] = version.strip() except Exception as e: print(f"[版本检查] 解析配置版本失败: {e}") return versions def check_all_versions( version_url: str, configs_version_url: Optional[str] = None, proxy_url: Optional[str] = None ) -> Tuple[bool, Optional[str]]: # 获取远程版本 remote_version = _fetch_remote_version(version_url, proxy_url) # 获取远程配置版本(如果有提供 URL) remote_config_versions = {} if configs_version_url: content = _fetch_remote_version(configs_version_url, proxy_url) if content: remote_config_versions = _parse_config_versions(content) print("=" * 60) print("版本检查") print("=" * 60) if remote_version: print(f"远程程序版本: {remote_version}") else: print("远程程序版本: 获取失败") if configs_version_url: if remote_config_versions: print(f"远程配置清单: 获取成功 ({len(remote_config_versions)} 个文件)") else: print("远程配置清单: 获取失败或为空") print("-" * 60) program_status = _compare_version(__version__, remote_version) if remote_version else "(无法比较)" print(f" 主程序版本: {__version__} {program_status}") config_files = [ Path("config/config.yaml"), Path("config/timeline.yaml"), Path("config/frequency_words.txt"), Path("config/ai_interests.txt"), Path("config/ai_analysis_prompt.txt"), Path("config/ai_translation_prompt.txt"), ] version_pattern = re.compile(r"Version:\s*(\d+\.\d+\.\d+)", re.IGNORECASE) for config_file in config_files: if not config_file.exists(): print(f" {config_file.name}: 文件不存在") continue try: with open(config_file, "r", encoding="utf-8") as f: local_version = None for i, line in enumerate(f): if i >= 20: break match = version_pattern.search(line) if match: local_version = match.group(1) break # 获取该文件的远程版本 target_remote_version = remote_config_versions.get(config_file.name) if local_version: if target_remote_version: status = _compare_version(local_version, target_remote_version) print(f" {config_file.name}: {local_version} {status}") else: print(f" {config_file.name}: {local_version} (未找到远程版本)") else: print(f" {config_file.name}: 未找到本地版本号") except Exception as e: print(f" {config_file.name}: 读取失败 - {e}") print("=" * 60) # 返回程序版本的更新状态 if remote_version: need_update = _parse_version(__version__) < _parse_version(remote_version) return need_update, remote_version if need_update else None return False, None # === 主分析器 === class NewsAnalyzer: # 模式策略定义 MODE_STRATEGIES = { "incremental": { "mode_name": "增量模式", "description": "增量模式(只关注新增新闻,无新增时不推送)", "report_type": "增量分析", "should_send_notification": True, }, "current": { "mode_name": "当前榜单模式", "description": "当前榜单模式(当前榜单匹配新闻 + 新增新闻区域 + 按时推送)", "report_type": "当前榜单", "should_send_notification": True, }, "daily": { "mode_name": "全天汇总模式", "description": "全天汇总模式(所有匹配新闻 + 新增新闻区域 + 按时推送)", "report_type": "全天汇总", "should_send_notification": True, }, } def __init__(self, config: Optional[Dict] = None): # 使用传入的配置或加载新配置 if config is None: print("正在加载配置...") config = load_config() print(f"TrendRadar v{__version__} 配置加载完成") print(f"监控平台数量: {len(config['PLATFORMS'])}") print(f"时区: {config.get('TIMEZONE', DEFAULT_TIMEZONE)}") # 创建应用上下文 self.ctx = AppContext(config) self.request_interval = self.ctx.config["REQUEST_INTERVAL"] self.report_mode = self.ctx.config["REPORT_MODE"] self.frequency_file = None self.filter_method = None # None=使用全局配置 ctx.filter_method self.interests_file = None # None=使用全局配置 ai_filter.interests_file self.rank_threshold = self.ctx.rank_threshold self.is_github_actions = os.environ.get("GITHUB_ACTIONS") == "true" self.is_docker_container = self._detect_docker_environment() self.update_info = None self.proxy_url = None self._setup_proxy() self.data_fetcher = DataFetcher(self.proxy_url) # 初始化存储管理器(使用 AppContext) self._init_storage_manager() # 注意:update_info 由 main() 函数设置,避免重复请求远程版本 def _init_storage_manager(self) -> None: # 获取数据保留天数(支持环境变量覆盖) env_retention = os.environ.get("STORAGE_RETENTION_DAYS", "").strip() if env_retention: # 环境变量覆盖配置 self.ctx.config["STORAGE"]["RETENTION_DAYS"] = int(env_retention) self.storage_manager = self.ctx.get_storage_manager() print(f"存储后端: {self.storage_manager.backend_name}") retention_days = self.ctx.config.get("STORAGE", {}).get("RETENTION_DAYS", 0) if retention_days > 0: print(f"数据保留天数: {retention_days} 天") def _detect_docker_environment(self) -> bool: try: if os.environ.get("DOCKER_CONTAINER") == "true": return True if os.path.exists("/.dockerenv"): return True return False except Exception: return False def _should_open_browser(self) -> bool: return not self.is_github_actions and not self.is_docker_container def _setup_proxy(self) -> None: if not self.is_github_actions and self.ctx.config["USE_PROXY"]: self.proxy_url = self.ctx.config["DEFAULT_PROXY"] print("本地环境,使用代理") elif not self.is_github_actions and not self.ctx.config["USE_PROXY"]: print("本地环境,未启用代理") else: print("GitHub Actions环境,不使用代理") def _set_update_info_from_config(self) -> None: try: version_url = self.ctx.config.get("VERSION_CHECK_URL", "") if not version_url: return remote_version = _fetch_remote_version(version_url, self.proxy_url) if remote_version: need_update = _parse_version(__version__) < _parse_version(remote_version) if need_update: self.update_info = { "current_version": __version__, "remote_version": remote_version, } except Exception as e: print(f"版本检查出错: {e}") def _get_mode_strategy(self) -> Dict: return self.MODE_STRATEGIES.get(self.report_mode, self.MODE_STRATEGIES["daily"]) def _has_notification_configured(self) -> bool: cfg = self.ctx.config return any( [ cfg["FEISHU_WEBHOOK_URL"], cfg["DINGTALK_WEBHOOK_URL"], cfg["WEWORK_WEBHOOK_URL"], (cfg["TELEGRAM_BOT_TOKEN"] and cfg["TELEGRAM_CHAT_ID"]), ( cfg["EMAIL_FROM"] and cfg["EMAIL_PASSWORD"] and cfg["EMAIL_TO"] ), (cfg["NTFY_SERVER_URL"] and cfg["NTFY_TOPIC"]), cfg["BARK_URL"], cfg["SLACK_WEBHOOK_URL"], cfg["GENERIC_WEBHOOK_URL"], ] ) def _has_valid_content( self, stats: List[Dict], new_titles: Optional[Dict] = None ) -> bool: if self.report_mode == "incremental": # 增量模式:只要有匹配的新闻就推送 # count_word_frequency 已经确保只处理新增的新闻(包括当天第一次爬取的情况) has_matched_news = any(stat["count"] > 0 for stat in stats) return has_matched_news elif self.report_mode == "current": # current模式:只要stats有内容就说明有匹配的新闻 return any(stat["count"] > 0 for stat in stats) else: # 当日汇总模式下,检查是否有匹配的频率词新闻或新增新闻 has_matched_news = any(stat["count"] > 0 for stat in stats) has_new_news = bool( new_titles and any(len(titles) > 0 for titles in new_titles.values()) ) return has_matched_news or has_new_news def _prepare_ai_analysis_data( self, ai_mode: str, current_results: Optional[Dict] = None, current_id_to_name: Optional[Dict] = None, ) -> Tuple[List[Dict], Optional[Dict]]: try: word_groups, filter_words, global_filters = self.ctx.load_frequency_words(self.frequency_file) if ai_mode == "incremental": # incremental 模式:使用当前抓取的数据 if not current_results or not current_id_to_name: print("[AI] incremental 模式需要当前抓取数据,但未提供") return [], None # 准备当前时间信息 time_info = self.ctx.format_time() title_info = self._prepare_current_title_info(current_results, time_info) # 检测新增标题 new_titles = self.ctx.detect_new_titles(list(current_results.keys())) # 统计计算 stats, _ = self.ctx.count_frequency( current_results, word_groups, filter_words, current_id_to_name, title_info, new_titles, mode="incremental", global_filters=global_filters, quiet=True, ) # 如果是 platform 模式,转换数据结构 if self.ctx.display_mode == "platform" and stats: stats = convert_keyword_stats_to_platform_stats( stats, self.ctx.weight_config, self.ctx.rank_threshold, ) return stats, current_id_to_name elif ai_mode in ["daily", "current"]: # 加载历史数据 analysis_data = self._load_analysis_data(quiet=True) if not analysis_data: print(f"[AI] 无法加载历史数据用于 {ai_mode} 模式分析") return [], None ( all_results, id_to_name, title_info, new_titles, _, _, _, ) = analysis_data # 统计计算 stats, _ = self.ctx.count_frequency( all_results, word_groups, filter_words, id_to_name, title_info, new_titles, mode=ai_mode, global_filters=global_filters, quiet=True, ) # 如果是 platform 模式,转换数据结构 if self.ctx.display_mode == "platform" and stats: stats = convert_keyword_stats_to_platform_stats( stats, self.ctx.weight_config, self.ctx.rank_threshold, ) return stats, id_to_name else: print(f"[AI] 未知的 AI 模式: {ai_mode}") return [], None except Exception as e: print(f"[AI] 准备 {ai_mode} 模式数据时出错: {e}") if self.ctx.config.get("DEBUG", False): import traceback traceback.print_exc() return [], None def _run_ai_analysis( self, stats: List[Dict], rss_items: Optional[List[Dict]], mode: str, report_type: str, id_to_name: Optional[Dict], current_results: Optional[Dict] = None, schedule: ResolvedSchedule = None, standalone_data: Optional[Dict] = None, ) -> Optional[AIAnalysisResult]: analysis_config = self.ctx.config.get("AI_ANALYSIS", {}) if not analysis_config.get("ENABLED", False): return None # 调度系统决策 if not schedule.analyze: print("[AI] 调度器: 当前时间段不执行 AI 分析") return None if schedule.once_analyze and schedule.period_key: scheduler = self.ctx.create_scheduler() date_str = self.ctx.format_date() if scheduler.already_executed(schedule.period_key, "analyze", date_str): print(f"[AI] 调度器: 时间段 {schedule.period_name or schedule.period_key} 今天已分析过,跳过") return None else: print(f"[AI] 调度器: 时间段 {schedule.period_name or schedule.period_key} 今天首次分析") print("[AI] 正在进行 AI 分析...") try: ai_config = self.ctx.config.get("AI", {}) debug_mode = self.ctx.config.get("DEBUG", False) analyzer = AIAnalyzer(ai_config, analysis_config, self.ctx.get_time, debug=debug_mode) # 确定 AI 分析使用的模式 ai_mode_config = analysis_config.get("MODE", "follow_report") if ai_mode_config == "follow_report": # 跟随推送报告模式 ai_mode = mode ai_stats = stats ai_id_to_name = id_to_name elif ai_mode_config in ["daily", "current", "incremental"]: # 使用独立配置的模式,需要重新准备数据 ai_mode = ai_mode_config if ai_mode != mode: print(f"[AI] 使用独立分析模式: {ai_mode} (推送模式: {mode})") print(f"[AI] 正在准备 {ai_mode} 模式的数据...") # 根据 AI 模式重新准备数据 ai_stats, ai_id_to_name = self._prepare_ai_analysis_data( ai_mode, current_results, id_to_name ) if not ai_stats: print(f"[AI] 警告: 无法准备 {ai_mode} 模式的数据,回退到推送模式数据") ai_stats = stats ai_id_to_name = id_to_name ai_mode = mode else: ai_stats = stats ai_id_to_name = id_to_name else: # 配置错误,回退到跟随模式 print(f"[AI] 警告: 无效的 ai_analysis.mode 配置 '{ai_mode_config}',使用推送模式 '{mode}'") ai_mode = mode ai_stats = stats ai_id_to_name = id_to_name # 提取平台列表 platforms = list(ai_id_to_name.values()) if ai_id_to_name else [] # 提取关键词列表 keywords = [s.get("word", "") for s in ai_stats if s.get("word")] if ai_stats else [] # 确定报告类型 if ai_mode != mode: # 根据 AI 模式确定报告类型 ai_report_type = { "daily": "当日汇总", "current": "当前榜单", "incremental": "增量更新" }.get(ai_mode, report_type) else: ai_report_type = report_type result = analyzer.analyze( stats=ai_stats, rss_stats=rss_items, report_mode=ai_mode, report_type=ai_report_type, platforms=platforms, keywords=keywords, standalone_data=standalone_data, ) # 设置 AI 分析使用的模式 if result.success: result.ai_mode = ai_mode if result.error: # 成功但有警告(如 JSON 解析问题但使用了原始文本) print(f"[AI] 分析完成(有警告: {result.error})") else: print("[AI] 分析完成") # 记录 AI 分析 if schedule.once_analyze and schedule.period_key: scheduler = self.ctx.create_scheduler() date_str = self.ctx.format_date() scheduler.record_execution(schedule.period_key, "analyze", date_str) else: print(f"[AI] 分析失败: {result.error}") return result except Exception as e: import traceback error_type = type(e).__name__ error_msg = str(e) # 截断过长的错误消息 if len(error_msg) > 200: error_msg = error_msg[:200] + "..." print(f"[AI] 分析出错 ({error_type}): {error_msg}") # 详细错误日志到 stderr import sys print(f"[AI] 详细错误堆栈:", file=sys.stderr) traceback.print_exc(file=sys.stderr) return AIAnalysisResult(success=False, error=f"{error_type}: {error_msg}") def _load_analysis_data( self, quiet: bool = False, ) -> Optional[Tuple[Dict, Dict, Dict, Dict, List, List]]: try: # 获取当前配置的监控平台ID列表 current_platform_ids = self.ctx.platform_ids if not quiet: print(f"当前监控平台: {current_platform_ids}") all_results, id_to_name, title_info = self.ctx.read_today_titles( current_platform_ids, quiet=quiet ) if not all_results: print("没有找到当天的数据") return None total_titles = sum(len(titles) for titles in all_results.values()) if not quiet: print(f"读取到 {total_titles} 个标题(已按当前监控平台过滤)") new_titles = self.ctx.detect_new_titles(current_platform_ids, quiet=quiet) word_groups, filter_words, global_filters = self.ctx.load_frequency_words(self.frequency_file) return ( all_results, id_to_name, title_info, new_titles, word_groups, filter_words, global_filters, ) except Exception as e: print(f"数据加载失败: {e}") return None def _prepare_current_title_info(self, results: Dict, time_info: str) -> Dict: title_info = {} for source_id, titles_data in results.items(): title_info[source_id] = {} for title, title_data in titles_data.items(): ranks = title_data.get("ranks", []) url = title_data.get("url", "") mobile_url = title_data.get("mobileUrl", "") title_info[source_id][title] = { "first_time": time_info, "last_time": time_info, "count": 1, "ranks": ranks, "url": url, "mobileUrl": mobile_url, } return title_info def _prepare_standalone_data( self, results: Dict, id_to_name: Dict, title_info: Optional[Dict] = None, rss_items: Optional[List[Dict]] = None, ) -> Optional[Dict]: display_config = self.ctx.config.get("DISPLAY", {}) standalone_config = display_config.get("STANDALONE", {}) platform_ids = standalone_config.get("PLATFORMS", []) rss_feed_ids = standalone_config.get("RSS_FEEDS", []) max_items = standalone_config.get("MAX_ITEMS", 20) if not platform_ids and not rss_feed_ids: return None standalone_data = { "platforms": [], "rss_feeds": [], } # 找出最新批次时间(类似 current 模式的过滤逻辑) latest_time = None if title_info: for source_titles in title_info.values(): for title_data in source_titles.values(): last_time = title_data.get("last_time", "") if last_time: if latest_time is None or last_time > latest_time: latest_time = last_time # 提取热榜平台数据 for platform_id in platform_ids: if platform_id not in results: continue platform_name = id_to_name.get(platform_id, platform_id) platform_titles = results[platform_id] items = [] for title, title_data in platform_titles.items(): # 获取元信息(如果有 title_info) meta = {} if title_info and platform_id in title_info and title in title_info[platform_id]: meta = title_info[platform_id][title] # 只保留当前在榜的话题(last_time 等于最新时间) if latest_time and meta: if meta.get("last_time") != latest_time: continue # 使用当前热榜的排名数据(title_data)进行排序 # title_data 包含的是爬虫返回的当前排名,用于保证独立展示区的顺序与热榜一致 current_ranks = title_data.get("ranks", []) current_rank = current_ranks[-1] if current_ranks else 0 # 用于显示的排名范围:合并历史排名和当前排名 historical_ranks = meta.get("ranks", []) if meta else [] # 合并去重,保持顺序 all_ranks = historical_ranks.copy() for rank in current_ranks: if rank not in all_ranks: all_ranks.append(rank) display_ranks = all_ranks if all_ranks else current_ranks item = { "title": title, "url": title_data.get("url", ""), "mobileUrl": title_data.get("mobileUrl", ""), "rank": current_rank, # 用于排序的当前排名 "ranks": display_ranks, # 用于显示的排名范围(历史+当前) "first_time": meta.get("first_time", ""), "last_time": meta.get("last_time", ""), "count": meta.get("count", 1), "rank_timeline": meta.get("rank_timeline", []), } items.append(item) # 按当前排名排序 items.sort(key=lambda x: x["rank"] if x["rank"] > 0 else 9999) # 限制条数 if max_items > 0: items = items[:max_items] if items: standalone_data["platforms"].append({ "id": platform_id, "name": platform_name, "items": items, }) # 提取 RSS 数据 if rss_items and rss_feed_ids: # 按 feed_id 分组 feed_items_map = {} for item in rss_items: feed_id = item.get("feed_id", "") if feed_id in rss_feed_ids: if feed_id not in feed_items_map: feed_items_map[feed_id] = { "name": item.get("feed_name", feed_id), "items": [], } feed_items_map[feed_id]["items"].append({ "title": item.get("title", ""), "url": item.get("url", ""), "published_at": item.get("published_at", ""), "author": item.get("author", ""), }) # 限制条数并添加到结果 for feed_id in rss_feed_ids: if feed_id in feed_items_map: feed_data = feed_items_map[feed_id] items = feed_data["items"] if max_items > 0: items = items[:max_items] if items: standalone_data["rss_feeds"].append({ "id": feed_id, "name": feed_data["name"], "items": items, }) # 如果没有任何数据,返回 None if not standalone_data["platforms"] and not standalone_data["rss_feeds"]: return None return standalone_data def _run_analysis_pipeline( self, data_source: Dict, mode: str, title_info: Dict, new_titles: Dict, word_groups: List[Dict], filter_words: List[str], id_to_name: Dict, failed_ids: Optional[List] = None, global_filters: Optional[List[str]] = None, quiet: bool = False, rss_items: Optional[List[Dict]] = None, rss_new_items: Optional[List[Dict]] = None, standalone_data: Optional[Dict] = None, schedule: ResolvedSchedule = None, rss_new_urls: Optional[set] = None, ) -> Tuple[List[Dict], Optional[str], Optional[AIAnalysisResult], Optional[List[Dict]]]: # 根据筛选策略选择数据处理方式 if self.filter_method == "ai": # === AI 筛选策略 === print("[筛选] 使用 AI 智能筛选策略") ai_filter_result = self.ctx.run_ai_filter(interests_file=self.interests_file) if ai_filter_result and ai_filter_result.success: print(f"[筛选] AI 筛选完成: {ai_filter_result.total_matched} 条匹配, {len(ai_filter_result.tags)} 个标签") # 转换为与关键词匹配相同的数据结构 stats, ai_rss_stats = self.ctx.convert_ai_filter_to_report_data( ai_filter_result, mode=mode, new_titles=new_titles, rss_new_urls=rss_new_urls, ) total_titles = sum(len(titles) for titles in data_source.values()) # AI 筛选的 RSS 结果替换关键词匹配的 RSS 结果 if ai_rss_stats: rss_items = ai_rss_stats else: # AI 筛选失败,回退到关键词匹配 error_msg = ai_filter_result.error if ai_filter_result else "未知错误" print(f"[筛选] AI 筛选失败: {error_msg},回退到关键词匹配") stats, total_titles = self.ctx.count_frequency( data_source, word_groups, filter_words, id_to_name, title_info, new_titles, mode=mode, global_filters=global_filters, quiet=quiet, ) else: # === 关键词匹配策略(默认)=== stats, total_titles = self.ctx.count_frequency( data_source, word_groups, filter_words, id_to_name, title_info, new_titles, mode=mode, global_filters=global_filters, quiet=quiet, ) # 如果是 platform 模式,转换数据结构 if self.ctx.display_mode == "platform" and stats: stats = convert_keyword_stats_to_platform_stats( stats, self.ctx.weight_config, self.ctx.rank_threshold, ) # AI 分析(如果启用,用于 HTML 报告) ai_result = None ai_config = self.ctx.config.get("AI_ANALYSIS", {}) if ai_config.get("ENABLED", False) and stats: # 获取模式策略来确定报告类型 mode_strategy = self._get_mode_strategy() report_type = mode_strategy["report_type"] ai_result = self._run_ai_analysis( stats, rss_items, mode, report_type, id_to_name, current_results=data_source, schedule=schedule, standalone_data=standalone_data ) # HTML生成(如果启用) html_file = None if self.ctx.config["STORAGE"]["FORMATS"]["HTML"]: html_file = self.ctx.generate_html( stats, total_titles, failed_ids=failed_ids, new_titles=new_titles, id_to_name=id_to_name, mode=mode, update_info=self.update_info if self.ctx.config["SHOW_VERSION_UPDATE"] else None, rss_items=rss_items, rss_new_items=rss_new_items, ai_analysis=ai_result, standalone_data=standalone_data, frequency_file=self.frequency_file, ) return stats, html_file, ai_result, rss_items def _send_notification_if_needed( self, stats: List[Dict], report_type: str, mode: str, failed_ids: Optional[List] = None, new_titles: Optional[Dict] = None, id_to_name: Optional[Dict] = None, html_file_path: Optional[str] = None, rss_items: Optional[List[Dict]] = None, rss_new_items: Optional[List[Dict]] = None, standalone_data: Optional[Dict] = None, ai_result: Optional[AIAnalysisResult] = None, current_results: Optional[Dict] = None, schedule: ResolvedSchedule = None, ) -> bool: has_notification = self._has_notification_configured() cfg = self.ctx.config # 检查是否有有效内容(热榜或RSS) has_news_content = self._has_valid_content(stats, new_titles) has_rss_content = bool(rss_items and len(rss_items) > 0) has_any_content = has_news_content or has_rss_content # 计算热榜匹配条数 news_count = sum(len(stat.get("titles", [])) for stat in stats) if stats else 0 rss_count = sum(stat.get("count", 0) for stat in rss_items) if rss_items else 0 if ( cfg["ENABLE_NOTIFICATION"] and has_notification and has_any_content ): # 输出推送内容统计 content_parts = [] if news_count > 0: content_parts.append(f"热榜 {news_count} 条") if rss_count > 0: content_parts.append(f"RSS {rss_count} 条") total_count = news_count + rss_count print(f"[推送] 准备发送:{' + '.join(content_parts)},合计 {total_count} 条") # 调度系统决策 if not schedule.push: print("[推送] 调度器: 当前时间段不执行推送") return False if schedule.once_push and schedule.period_key: scheduler = self.ctx.create_scheduler() date_str = self.ctx.format_date() if scheduler.already_executed(schedule.period_key, "push", date_str): print(f"[推送] 调度器: 时间段 {schedule.period_name or schedule.period_key} 今天已推送过,跳过") return False else: print(f"[推送] 调度器: 时间段 {schedule.period_name or schedule.period_key} 今天首次推送") # AI 分析:优先使用传入的结果,避免重复分析 if ai_result is None: ai_config = cfg.get("AI_ANALYSIS", {}) if ai_config.get("ENABLED", False): ai_result = self._run_ai_analysis( stats, rss_items, mode, report_type, id_to_name, current_results=current_results, schedule=schedule ) # 准备报告数据 report_data = self.ctx.prepare_report(stats, failed_ids, new_titles, id_to_name, mode, frequency_file=self.frequency_file) # 是否发送版本更新信息 update_info_to_send = self.update_info if cfg["SHOW_VERSION_UPDATE"] else None # 使用 NotificationDispatcher 发送到所有渠道 dispatcher = self.ctx.create_notification_dispatcher() results = dispatcher.dispatch_all( report_data=report_data, report_type=report_type, update_info=update_info_to_send, proxy_url=self.proxy_url, mode=mode, html_file_path=html_file_path, rss_items=rss_items, rss_new_items=rss_new_items, ai_analysis=ai_result, standalone_data=standalone_data, ) if not results: print("未配置任何通知渠道,跳过通知发送") return False # 记录推送成功 if any(results.values()): if schedule.once_push and schedule.period_key: scheduler = self.ctx.create_scheduler() date_str = self.ctx.format_date() scheduler.record_execution(schedule.period_key, "push", date_str) return True elif cfg["ENABLE_NOTIFICATION"] and not has_notification: print("⚠️ 警告:通知功能已启用但未配置任何通知渠道,将跳过通知发送") elif not cfg["ENABLE_NOTIFICATION"]: print(f"跳过{report_type}通知:通知功能已禁用") elif ( cfg["ENABLE_NOTIFICATION"] and has_notification and not has_any_content ): mode_strategy = self._get_mode_strategy() if self.report_mode == "incremental": if not has_rss_content: print("跳过通知:增量模式下未检测到匹配的新闻和RSS") else: print("跳过通知:增量模式下新闻未匹配到关键词") else: print( f"跳过通知:{mode_strategy['mode_name']}下未检测到匹配的新闻" ) return False def _initialize_and_check_config(self) -> None: now = self.ctx.get_time() print(f"当前北京时间: {now.strftime('%Y-%m-%d %H:%M:%S')}") if not self.ctx.config["ENABLE_CRAWLER"]: print("爬虫功能已禁用(ENABLE_CRAWLER=False),程序退出") return has_notification = self._has_notification_configured() if not self.ctx.config["ENABLE_NOTIFICATION"]: print("通知功能已禁用(ENABLE_NOTIFICATION=False),将只进行数据抓取") elif not has_notification: print("未配置任何通知渠道,将只进行数据抓取,不发送通知") else: print("通知功能已启用,将发送通知") mode_strategy = self._get_mode_strategy() print(f"报告模式: {self.report_mode}") print(f"运行模式: {mode_strategy['description']}") def _crawl_data(self) -> Tuple[Dict, Dict, List]: ids = [] for platform in self.ctx.platforms: if "name" in platform: ids.append((platform["id"], platform["name"])) else: ids.append(platform["id"]) print( f"配置的监控平台: {[p.get('name', p['id']) for p in self.ctx.platforms]}" ) print(f"开始爬取数据,请求间隔 {self.request_interval} 毫秒") Path("output").mkdir(parents=True, exist_ok=True) results, id_to_name, failed_ids = self.data_fetcher.crawl_websites( ids, self.request_interval ) # 转换为 NewsData 格式并保存到存储后端 crawl_time = self.ctx.format_time() crawl_date = self.ctx.format_date() news_data = convert_crawl_results_to_news_data( results, id_to_name, failed_ids, crawl_time, crawl_date ) # 保存到存储后端(SQLite) if self.storage_manager.save_news_data(news_data): print(f"数据已保存到存储后端: {self.storage_manager.backend_name}") # 保存 TXT 快照(如果启用) txt_file = self.storage_manager.save_txt_snapshot(news_data) if txt_file: print(f"TXT 快照已保存: {txt_file}") return results, id_to_name, failed_ids def _crawl_rss_data(self) -> Tuple[Optional[List[Dict]], Optional[List[Dict]], Optional[List[Dict]], set]: if not self.ctx.rss_enabled: return None, None, None, set() rss_feeds = self.ctx.rss_feeds if not rss_feeds: print("[RSS] 未配置任何 RSS 源") return None, None, None, set() try: from trendradar.crawler.rss import RSSFetcher, RSSFeedConfig # 构建 RSS 源配置 feeds = [] for feed_config in rss_feeds: # 读取并验证单个 feed 的 max_age_days(可选) max_age_days_raw = feed_config.get("max_age_days") max_age_days = None if max_age_days_raw is not None: try: max_age_days = int(max_age_days_raw) if max_age_days < 0: feed_id = feed_config.get("id", "unknown") print(f"[警告] RSS feed '{feed_id}' 的 max_age_days 为负数,将使用全局默认值") max_age_days = None except (ValueError, TypeError): feed_id = feed_config.get("id", "unknown") print(f"[警告] RSS feed '{feed_id}' 的 max_age_days 格式错误:{max_age_days_raw}") max_age_days = None feed = RSSFeedConfig( id=feed_config.get("id", ""), name=feed_config.get("name", ""), url=feed_config.get("url", ""), max_items=feed_config.get("max_items", 50), enabled=feed_config.get("enabled", True), max_age_days=max_age_days, # None=使用全局,0=禁用,>0=覆盖 ) if feed.id and feed.url and feed.enabled: feeds.append(feed) if not feeds: print("[RSS] 没有启用的 RSS 源") return None, None, None, set() # 创建抓取器 rss_config = self.ctx.rss_config # RSS 代理:优先使用 RSS 专属代理,否则使用爬虫默认代理 rss_proxy_url = rss_config.get("PROXY_URL", "") or self.proxy_url or "" # 获取配置的时区 timezone = self.ctx.config.get("TIMEZONE", DEFAULT_TIMEZONE) # 获取新鲜度过滤配置 freshness_config = rss_config.get("FRESHNESS_FILTER", {}) freshness_enabled = freshness_config.get("ENABLED", True) default_max_age_days = freshness_config.get("MAX_AGE_DAYS", 3) fetcher = RSSFetcher( feeds=feeds, request_interval=rss_config.get("REQUEST_INTERVAL", 2000), timeout=rss_config.get("TIMEOUT", 15), use_proxy=rss_config.get("USE_PROXY", False), proxy_url=rss_proxy_url, timezone=timezone, freshness_enabled=freshness_enabled, default_max_age_days=default_max_age_days, ) # 抓取数据 rss_data = fetcher.fetch_all() # 保存到存储后端 if self.storage_manager.save_rss_data(rss_data): print(f"[RSS] 数据已保存到存储后端") # 处理 RSS 数据(按模式过滤)并返回用于合并推送 return self._process_rss_data_by_mode(rss_data) else: print(f"[RSS] 数据保存失败") return None, None, None, set() except ImportError as e: print(f"[RSS] 缺少依赖: {e}") print("[RSS] 请安装 feedparser: pip install feedparser") return None, None, None, set() except Exception as e: print(f"[RSS] 抓取失败: {e}") return None, None, None, set() def _process_rss_data_by_mode(self, rss_data) -> Tuple[Optional[List[Dict]], Optional[List[Dict]], Optional[List[Dict]], set]: from trendradar.core.analyzer import count_rss_frequency # 从 display.regions.rss 统一控制 RSS 分析和展示 rss_display_enabled = self.ctx.config.get("DISPLAY", {}).get("REGIONS", {}).get("RSS", True) # 加载关键词配置 try: word_groups, filter_words, global_filters = self.ctx.load_frequency_words(self.frequency_file) except FileNotFoundError: word_groups, filter_words, global_filters = [], [], [] timezone = self.ctx.timezone max_news_per_keyword = self.ctx.config.get("MAX_NEWS_PER_KEYWORD", 0) sort_by_position_first = self.ctx.config.get("SORT_BY_POSITION_FIRST", False) rss_stats = None rss_new_stats = None raw_rss_items = None # 原始 RSS 条目列表(用于独立展示区) rss_new_urls = set() # 原始新增 RSS URLs(未经关键词过滤) # 1. 首先获取原始条目(用于独立展示区,不受 display.regions.rss 影响) # 根据模式获取原始条目 if self.report_mode == "incremental": new_items_dict = self.storage_manager.detect_new_rss_items(rss_data) if new_items_dict: raw_rss_items = self._convert_rss_items_to_list(new_items_dict, rss_data.id_to_name) elif self.report_mode == "current": latest_data = self.storage_manager.get_latest_rss_data(rss_data.date) if latest_data: raw_rss_items = self._convert_rss_items_to_list(latest_data.items, latest_data.id_to_name) else: # daily all_data = self.storage_manager.get_rss_data(rss_data.date) if all_data: raw_rss_items = self._convert_rss_items_to_list(all_data.items, all_data.id_to_name) # 如果 RSS 展示未启用,跳过关键词分析,只返回原始条目用于独立展示区 if not rss_display_enabled: return None, None, raw_rss_items, rss_new_urls # 2. 获取新增条目(用于统计) new_items_dict = self.storage_manager.detect_new_rss_items(rss_data) new_items_list = None if new_items_dict: new_items_list = self._convert_rss_items_to_list(new_items_dict, rss_data.id_to_name) if new_items_list: print(f"[RSS] 检测到 {len(new_items_list)} 条新增") # 收集原始新增 URLs(未经关键词过滤,用于 AI 模式 is_new 检测) rss_new_urls = {item["url"] for item in new_items_list if item.get("url")} # 3. 根据模式获取统计条目 if self.report_mode == "incremental": # 增量模式:统计条目就是新增条目 if not new_items_list: print("[RSS] 增量模式:没有新增 RSS 条目") return None, None, raw_rss_items, rss_new_urls rss_stats, total = count_rss_frequency( rss_items=new_items_list, word_groups=word_groups, filter_words=filter_words, global_filters=global_filters, new_items=new_items_list, # 增量模式所有都是新增 max_news_per_keyword=max_news_per_keyword, sort_by_position_first=sort_by_position_first, timezone=timezone, rank_threshold=self.rank_threshold, quiet=False, ) if not rss_stats: print("[RSS] 增量模式:关键词匹配后没有内容") # 即使关键词匹配为空,也返回原始条目用于独立展示区 return None, None, raw_rss_items, rss_new_urls elif self.report_mode == "current": # 当前榜单模式:统计=当前榜单所有条目 # raw_rss_items 已在前面获取 if not raw_rss_items: print("[RSS] 当前榜单模式:没有 RSS 数据") return None, None, None, rss_new_urls rss_stats, total = count_rss_frequency( rss_items=raw_rss_items, word_groups=word_groups, filter_words=filter_words, global_filters=global_filters, new_items=new_items_list, # 标记新增 max_news_per_keyword=max_news_per_keyword, sort_by_position_first=sort_by_position_first, timezone=timezone, rank_threshold=self.rank_threshold, quiet=False, ) if not rss_stats: print("[RSS] 当前榜单模式:关键词匹配后没有内容") # 即使关键词匹配为空,也返回原始条目用于独立展示区 return None, None, raw_rss_items, rss_new_urls # 生成新增统计 if new_items_list: rss_new_stats, _ = count_rss_frequency( rss_items=new_items_list, word_groups=word_groups, filter_words=filter_words, global_filters=global_filters, new_items=new_items_list, max_news_per_keyword=max_news_per_keyword, sort_by_position_first=sort_by_position_first, timezone=timezone, rank_threshold=self.rank_threshold, quiet=True, ) else: # daily 模式:统计=当天所有条目 # raw_rss_items 已在前面获取 if not raw_rss_items: print("[RSS] 当日汇总模式:没有 RSS 数据") return None, None, None, rss_new_urls rss_stats, total = count_rss_frequency( rss_items=raw_rss_items, word_groups=word_groups, filter_words=filter_words, global_filters=global_filters, new_items=new_items_list, # 标记新增 max_news_per_keyword=max_news_per_keyword, sort_by_position_first=sort_by_position_first, timezone=timezone, rank_threshold=self.rank_threshold, quiet=False, ) if not rss_stats: print("[RSS] 当日汇总模式:关键词匹配后没有内容") # 即使关键词匹配为空,也返回原始条目用于独立展示区 return None, None, raw_rss_items, rss_new_urls # 生成新增统计 if new_items_list: rss_new_stats, _ = count_rss_frequency( rss_items=new_items_list, word_groups=word_groups, filter_words=filter_words, global_filters=global_filters, new_items=new_items_list, max_news_per_keyword=max_news_per_keyword, sort_by_position_first=sort_by_position_first, timezone=timezone, rank_threshold=self.rank_threshold, quiet=True, ) return rss_stats, rss_new_stats, raw_rss_items, rss_new_urls def _convert_rss_items_to_list(self, items_dict: Dict, id_to_name: Dict) -> List[Dict]: rss_items = [] filtered_count = 0 filtered_details = [] # 用于 DEBUG 模式下的详细日志 # 获取新鲜度过滤配置 rss_config = self.ctx.rss_config freshness_config = rss_config.get("FRESHNESS_FILTER", {}) freshness_enabled = freshness_config.get("ENABLED", True) default_max_age_days = freshness_config.get("MAX_AGE_DAYS", 3) timezone = self.ctx.config.get("TIMEZONE", DEFAULT_TIMEZONE) debug_mode = self.ctx.config.get("DEBUG", False) # 构建 feed_id -> max_age_days 的映射 feed_max_age_map = {} for feed_cfg in self.ctx.rss_feeds: feed_id = feed_cfg.get("id", "") max_age = feed_cfg.get("max_age_days") if max_age is not None: try: feed_max_age_map[feed_id] = int(max_age) except (ValueError, TypeError): pass for feed_id, items in items_dict.items(): # 确定此 feed 的 max_age_days max_days = feed_max_age_map.get(feed_id) if max_days is None: max_days = default_max_age_days for item in items: # 应用新鲜度过滤(仅在启用时) if freshness_enabled and max_days > 0: if item.published_at and not is_within_days(item.published_at, max_days, timezone): filtered_count += 1 # 记录详细信息用于 DEBUG 模式 if debug_mode: days_old = calculate_days_old(item.published_at, timezone) feed_name = id_to_name.get(feed_id, feed_id) filtered_details.append({ "title": item.title[:50] + "..." if len(item.title) > 50 else item.title, "feed": feed_name, "days_old": days_old, "max_days": max_days, }) continue # 跳过超过指定天数的文章 rss_items.append({ "title": item.title, "feed_id": feed_id, "feed_name": id_to_name.get(feed_id, feed_id), "url": item.url, "published_at": item.published_at, "summary": item.summary, "author": item.author, }) # 输出过滤统计 if filtered_count > 0: print(f"[RSS] 新鲜度过滤:跳过 {filtered_count} 篇超过指定天数的旧文章(仍保留在数据库中)") # DEBUG 模式下显示详细信息 if debug_mode and filtered_details: print(f"[RSS] 被过滤的文章详情(共 {len(filtered_details)} 篇):") for detail in filtered_details[:10]: # 最多显示 10 条 days_str = f"{detail['days_old']:.1f}" if detail['days_old'] else "未知" print(f" - [{days_str}天前] [{detail['feed']}] {detail['title']} (限制: {detail['max_days']}天)") if len(filtered_details) > 10: print(f" ... 还有 {len(filtered_details) - 10} 篇被过滤") return rss_items def _filter_rss_by_keywords(self, rss_items: List[Dict]) -> List[Dict]: try: word_groups, filter_words, global_filters = self.ctx.load_frequency_words(self.frequency_file) if word_groups or filter_words or global_filters: from trendradar.core.frequency import matches_word_groups filtered_items = [] for item in rss_items: title = item.get("title", "") if matches_word_groups(title, word_groups, filter_words, global_filters): filtered_items.append(item) original_count = len(rss_items) rss_items = filtered_items print(f"[RSS] 关键词过滤后剩余 {len(rss_items)}/{original_count} 条") if not rss_items: print("[RSS] 关键词过滤后没有匹配内容") return [] except FileNotFoundError: # 关键词文件不存在时跳过过滤 pass return rss_items def _generate_rss_html_report(self, rss_items: list, feeds_info: dict) -> str: try: from trendradar.report.rss_html import render_rss_html_content from pathlib import Path html_content = render_rss_html_content( rss_items=rss_items, total_count=len(rss_items), feeds_info=feeds_info, get_time_func=self.ctx.get_time, ) # 保存 HTML 文件(扁平化结构:output/html/日期/) date_folder = self.ctx.format_date() time_filename = self.ctx.format_time() output_dir = Path("output") / "html" / date_folder output_dir.mkdir(parents=True, exist_ok=True) file_path = output_dir / f"rss_{time_filename}.html" with open(file_path, "w", encoding="utf-8") as f: f.write(html_content) print(f"[RSS] HTML 报告已生成: {file_path}") return str(file_path) except Exception as e: print(f"[RSS] 生成 HTML 报告失败: {e}") return None def _execute_mode_strategy( self, mode_strategy: Dict, results: Dict, id_to_name: Dict, failed_ids: List, rss_items: Optional[List[Dict]] = None, rss_new_items: Optional[List[Dict]] = None, raw_rss_items: Optional[List[Dict]] = None, rss_new_urls: Optional[set] = None, ) -> Optional[str]: # 调度系统 scheduler = self.ctx.create_scheduler() schedule = scheduler.resolve() # 使用 schedule 决定的 report_mode 覆盖全局配置 effective_mode = schedule.report_mode if effective_mode != self.report_mode: print(f"[调度] 报告模式覆盖: {self.report_mode} -> {effective_mode}") self.report_mode = effective_mode # 重新获取 mode_strategy,确保 report_type 与覆盖后的 report_mode 一致 mode_strategy = self._get_mode_strategy() # 使用 schedule 决定的 frequency_file 覆盖默认值 self.frequency_file = schedule.frequency_file # 使用 schedule 决定的筛选策略覆盖默认值 self.filter_method = schedule.filter_method or self.ctx.filter_method # 使用 schedule 决定的 AI 筛选兴趣文件覆盖默认值 self.interests_file = schedule.interests_file # 如果调度器说不采集,则直接跳过 if not schedule.collect: print("[调度] 当前时间段不执行数据采集,跳过分析流水线") return None # 获取当前监控平台ID列表 current_platform_ids = self.ctx.platform_ids new_titles = self.ctx.detect_new_titles(current_platform_ids) time_info = self.ctx.format_time() word_groups, filter_words, global_filters = self.ctx.load_frequency_words(self.frequency_file) html_file = None stats = [] ai_result = None title_info = None # current 模式需要使用完整的历史数据 if self.report_mode == "current": analysis_data = self._load_analysis_data() if analysis_data: ( all_results, historical_id_to_name, historical_title_info, historical_new_titles, _, _, _, ) = analysis_data print( f"current模式:使用过滤后的历史数据,包含平台:{list(all_results.keys())}" ) # 使用历史数据准备独立展示区数据(包含完整的 title_info) standalone_data = self._prepare_standalone_data( all_results, historical_id_to_name, historical_title_info, raw_rss_items ) stats, html_file, ai_result, rss_items = self._run_analysis_pipeline( all_results, self.report_mode, historical_title_info, historical_new_titles, word_groups, filter_words, historical_id_to_name, failed_ids=failed_ids, global_filters=global_filters, rss_items=rss_items, rss_new_items=rss_new_items, standalone_data=standalone_data, schedule=schedule, rss_new_urls=rss_new_urls, ) combined_id_to_name = {**historical_id_to_name, **id_to_name} new_titles = historical_new_titles id_to_name = combined_id_to_name title_info = historical_title_info results = all_results else: print("❌ 严重错误:无法读取刚保存的数据文件") raise RuntimeError("数据一致性检查失败:保存后立即读取失败") elif self.report_mode == "daily": # daily 模式:使用全天累计数据 analysis_data = self._load_analysis_data() if analysis_data: ( all_results, historical_id_to_name, historical_title_info, historical_new_titles, _, _, _, ) = analysis_data # 使用历史数据准备独立展示区数据(包含完整的 title_info) standalone_data = self._prepare_standalone_data( all_results, historical_id_to_name, historical_title_info, raw_rss_items ) stats, html_file, ai_result, rss_items = self._run_analysis_pipeline( all_results, self.report_mode, historical_title_info, historical_new_titles, word_groups, filter_words, historical_id_to_name, failed_ids=failed_ids, global_filters=global_filters, rss_items=rss_items, rss_new_items=rss_new_items, standalone_data=standalone_data, schedule=schedule, rss_new_urls=rss_new_urls, ) combined_id_to_name = {**historical_id_to_name, **id_to_name} new_titles = historical_new_titles id_to_name = combined_id_to_name title_info = historical_title_info results = all_results else: # 没有历史数据时使用当前数据 title_info = self._prepare_current_title_info(results, time_info) standalone_data = self._prepare_standalone_data( results, id_to_name, title_info, raw_rss_items ) stats, html_file, ai_result, rss_items = self._run_analysis_pipeline( results, self.report_mode, title_info, new_titles, word_groups, filter_words, id_to_name, failed_ids=failed_ids, global_filters=global_filters, rss_items=rss_items, rss_new_items=rss_new_items, standalone_data=standalone_data, schedule=schedule, rss_new_urls=rss_new_urls, ) else: # incremental 模式:只使用当前抓取的数据 title_info = self._prepare_current_title_info(results, time_info) standalone_data = self._prepare_standalone_data( results, id_to_name, title_info, raw_rss_items ) stats, html_file, ai_result, rss_items = self._run_analysis_pipeline( results, self.report_mode, title_info, new_titles, word_groups, filter_words, id_to_name, failed_ids=failed_ids, global_filters=global_filters, rss_items=rss_items, rss_new_items=rss_new_items, standalone_data=standalone_data, schedule=schedule, rss_new_urls=rss_new_urls, ) if html_file: print(f"HTML报告已生成: {html_file}") print(f"最新报告已更新: output/html/latest/{self.report_mode}.html") # 发送通知 if mode_strategy["should_send_notification"]: standalone_data = self._prepare_standalone_data( results, id_to_name, title_info, raw_rss_items ) self._send_notification_if_needed( stats, mode_strategy["report_type"], self.report_mode, failed_ids=failed_ids, new_titles=new_titles, id_to_name=id_to_name, html_file_path=html_file, rss_items=rss_items, rss_new_items=rss_new_items, standalone_data=standalone_data, ai_result=ai_result, current_results=results, schedule=schedule, ) # 打开浏览器(仅在非容器环境) if self._should_open_browser() and html_file: file_url = "file://" + str(Path(html_file).resolve()) print(f"正在打开HTML报告: {file_url}") webbrowser.open(file_url) elif self.is_docker_container and html_file: print(f"HTML报告已生成(Docker环境): {html_file}") return html_file def run(self) -> None: try: self._initialize_and_check_config() mode_strategy = self._get_mode_strategy() # 抓取热榜数据 results, id_to_name, failed_ids = self._crawl_data() # 抓取 RSS 数据(如果启用),返回统计条目、新增条目和原始条目 rss_items, rss_new_items, raw_rss_items, rss_new_urls = self._crawl_rss_data() # 执行模式策略,传递 RSS 数据用于合并推送 self._execute_mode_strategy( mode_strategy, results, id_to_name, failed_ids, rss_items=rss_items, rss_new_items=rss_new_items, raw_rss_items=raw_rss_items, rss_new_urls=rss_new_urls ) except Exception as e: print(f"分析流程执行出错: {e}") if self.ctx.config.get("DEBUG", False): raise finally: # 清理资源(包括过期数据清理和数据库连接关闭) self.ctx.cleanup() def _record_doctor_result(results: List[Tuple[str, str, str]], status: str, item: str, detail: str) -> None: icon_map = { "pass": "✅", "warn": "⚠️", "fail": "❌", } icon = icon_map.get(status, "•") results.append((status, item, detail)) print(f"{icon} {item}: {detail}") def _save_doctor_report( results: List[Tuple[str, str, str]], pass_count: int, warn_count: int, fail_count: int, config_path: Optional[str], ) -> None: report = { "version": __version__, "generated_at": datetime.now(timezone.utc).isoformat(), "config_path": config_path or os.environ.get("CONFIG_PATH", "config/config.yaml"), "summary": { "pass": pass_count, "warn": warn_count, "fail": fail_count, "ok": fail_count == 0, }, "checks": [ {"status": status, "item": item, "detail": detail} for status, item, detail in results ], } try: output_dir = Path("output") / "meta" output_dir.mkdir(parents=True, exist_ok=True) output_path = output_dir / "doctor_report.json" output_path.write_text( json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8", ) print(f"体检报告已保存: {output_path}") except Exception as e: print(f"⚠️ 体检报告保存失败: {e}") def _run_doctor(config_path: Optional[str] = None) -> bool: print("=" * 60) print(f"TrendRadar v{__version__} 环境体检") print("=" * 60) results: List[Tuple[str, str, str]] = [] config = None # 1) Python 版本检查 py_ok = sys.version_info >= (3, 10) py_version = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}" if py_ok: _record_doctor_result(results, "pass", "Python版本", f"{py_version} (满足 >= 3.10)") else: _record_doctor_result(results, "fail", "Python版本", f"{py_version} (不满足 >= 3.10)") # 2) 关键文件检查 if config_path is None: config_path = os.environ.get("CONFIG_PATH", "config/config.yaml") required_files = [ (config_path, "主配置文件"), ("config/frequency_words.txt", "关键词文件"), ] optional_files = [ ("config/timeline.yaml", "调度文件"), ] for path_str, desc in required_files: if Path(path_str).exists(): _record_doctor_result(results, "pass", desc, f"已找到: {path_str}") else: _record_doctor_result(results, "fail", desc, f"缺失: {path_str}") for path_str, desc in optional_files: if Path(path_str).exists(): _record_doctor_result(results, "pass", desc, f"已找到: {path_str}") else: _record_doctor_result(results, "warn", desc, f"未找到: {path_str}(将使用默认调度模板)") # 3) 配置加载检查 try: config = load_config(config_path) _record_doctor_result(results, "pass", "配置加载", f"加载成功: {config_path}") except Exception as e: _record_doctor_result(results, "fail", "配置加载", f"加载失败: {e}") # 后续检查依赖配置对象 if config: # 4) 调度配置检查 try: ctx = AppContext(config) schedule = ctx.create_scheduler().resolve() detail = f"调度解析成功(report_mode={schedule.report_mode}, ai_mode={schedule.ai_mode})" _record_doctor_result(results, "pass", "调度配置", detail) except Exception as e: _record_doctor_result(results, "fail", "调度配置", f"解析失败: {e}") # 5) AI 配置检查(按功能场景区分严重级别) ai_analysis_enabled = config.get("AI_ANALYSIS", {}).get("ENABLED", False) ai_translation_enabled = config.get("AI_TRANSLATION", {}).get("ENABLED", False) ai_filter_enabled = config.get("FILTER", {}).get("METHOD", "keyword") == "ai" ai_enabled = ai_analysis_enabled or ai_translation_enabled or ai_filter_enabled if ai_enabled: try: from trendradar.ai.client import AIClient valid, message = AIClient(config.get("AI", {})).validate_config() if valid: _record_doctor_result(results, "pass", "AI配置", f"模型: {config.get('AI', {}).get('MODEL', '')}") else: # AI 分析/翻译是硬依赖;AI 筛选缺失时会自动回退关键词匹配 if ai_analysis_enabled or ai_translation_enabled: _record_doctor_result(results, "fail", "AI配置", message) else: _record_doctor_result(results, "warn", "AI配置", f"{message}(AI 筛选将回退关键词模式)") except Exception as e: _record_doctor_result(results, "fail", "AI配置", f"校验异常: {e}") else: _record_doctor_result(results, "warn", "AI配置", "未启用 AI 功能,跳过校验") # 6) 存储配置检查 try: storage_cfg = config.get("STORAGE", {}) backend = storage_cfg.get("BACKEND", "auto") remote = storage_cfg.get("REMOTE", {}) missing_remote_keys = [ k for k in ("BUCKET_NAME", "ACCESS_KEY_ID", "SECRET_ACCESS_KEY", "ENDPOINT_URL") if not remote.get(k) ] if backend == "remote" and missing_remote_keys: _record_doctor_result( results, "fail", "存储配置", f"remote 模式缺少配置: {', '.join(missing_remote_keys)}" ) elif backend == "auto" and os.environ.get("GITHUB_ACTIONS") == "true" and missing_remote_keys: _record_doctor_result( results, "warn", "存储配置", "GitHub Actions + auto 模式未完整配置远程存储,可能导致数据丢失" ) else: sm = AppContext(config).get_storage_manager() _record_doctor_result(results, "pass", "存储配置", f"当前后端: {sm.backend_name}") except Exception as e: _record_doctor_result(results, "fail", "存储配置", f"检查失败: {e}") # 7) 通知渠道配置检查 channel_details = [] channel_issues = [] max_accounts = config.get("MAX_ACCOUNTS_PER_CHANNEL", 3) # 普通单值/多值渠道 for key, name in [ ("FEISHU_WEBHOOK_URL", "飞书"), ("DINGTALK_WEBHOOK_URL", "钉钉"), ("WEWORK_WEBHOOK_URL", "企业微信"), ("BARK_URL", "Bark"), ("SLACK_WEBHOOK_URL", "Slack"), ("GENERIC_WEBHOOK_URL", "通用Webhook"), ]: values = parse_multi_account_config(config.get(key, "")) if values: channel_details.append(f"{name}({min(len(values), max_accounts)}个)") # Telegram 配对校验 tg_tokens = parse_multi_account_config(config.get("TELEGRAM_BOT_TOKEN", "")) tg_chats = parse_multi_account_config(config.get("TELEGRAM_CHAT_ID", "")) if tg_tokens or tg_chats: valid, count = validate_paired_configs( {"bot_token": tg_tokens, "chat_id": tg_chats}, "Telegram", required_keys=["bot_token", "chat_id"], ) if valid and count > 0: channel_details.append(f"Telegram({min(count, max_accounts)}个)") else: channel_issues.append("Telegram bot_token/chat_id 配置不完整或数量不一致") # ntfy 配对校验(token 可选) ntfy_server = config.get("NTFY_SERVER_URL", "") ntfy_topics = parse_multi_account_config(config.get("NTFY_TOPIC", "")) ntfy_tokens = parse_multi_account_config(config.get("NTFY_TOKEN", "")) if ntfy_server and ntfy_topics: if ntfy_tokens: valid, count = validate_paired_configs( {"topic": ntfy_topics, "token": ntfy_tokens}, "ntfy", ) if valid and count > 0: channel_details.append(f"ntfy({min(count, max_accounts)}个)") else: channel_issues.append("ntfy topic/token 数量不一致") else: channel_details.append(f"ntfy({min(len(ntfy_topics), max_accounts)}个)") # 邮件配置完整性 email_ready = all( [ config.get("EMAIL_FROM"), config.get("EMAIL_PASSWORD"), config.get("EMAIL_TO"), ] ) if email_ready: channel_details.append("邮件") elif any([config.get("EMAIL_FROM"), config.get("EMAIL_PASSWORD"), config.get("EMAIL_TO")]): channel_issues.append("邮件配置不完整(需要 from/password/to 同时配置)") if channel_issues and not channel_details: _record_doctor_result(results, "fail", "通知配置", ";".join(channel_issues)) elif channel_issues and channel_details: detail = f"可用渠道: {', '.join(channel_details)};问题: {';'.join(channel_issues)}" _record_doctor_result(results, "warn", "通知配置", detail) elif channel_details: _record_doctor_result(results, "pass", "通知配置", f"可用渠道: {', '.join(channel_details)}") else: _record_doctor_result(results, "warn", "通知配置", "未配置任何通知渠道") # 8) 输出目录可写检查 try: output_dir = Path("output") output_dir.mkdir(parents=True, exist_ok=True) probe_file = output_dir / ".doctor_write_probe" probe_file.write_text("ok", encoding="utf-8") probe_file.unlink(missing_ok=True) _record_doctor_result(results, "pass", "输出目录", f"可写: {output_dir}") except Exception as e: _record_doctor_result(results, "fail", "输出目录", f"不可写: {e}") pass_count = sum(1 for status, _, _ in results if status == "pass") warn_count = sum(1 for status, _, _ in results if status == "warn") fail_count = sum(1 for status, _, _ in results if status == "fail") _save_doctor_report(results, pass_count, warn_count, fail_count, config_path) print("-" * 60) print(f"体检结果: ✅ {pass_count} 项通过 ⚠️ {warn_count} 项警告 ❌ {fail_count} 项失败") print("=" * 60) if fail_count == 0: print("体检通过。") return True print("体检未通过,请先修复失败项。") return False def _build_test_report_data(ctx: AppContext) -> Dict: now = ctx.get_time() time_display = now.strftime("%H:%M") title = f"TrendRadar 通知测试消息({now.strftime('%Y-%m-%d %H:%M:%S')})" return { "stats": [ { "word": "连通性测试", "count": 1, "titles": [ { "title": title, "source_name": "TrendRadar", "url": "https://github.com/sansan0/TrendRadar", "mobile_url": "", "ranks": [1], "rank_threshold": ctx.rank_threshold, "count": 1, "is_new": True, "time_display": time_display, "matched_keyword": "连通性测试", } ], } ], "failed_ids": [], "new_titles": [], "id_to_name": {}, } def _create_test_html_file(ctx: AppContext) -> Optional[str]: try: now = ctx.get_time() output_dir = Path("output") / "html" / ctx.format_date() output_dir.mkdir(parents=True, exist_ok=True) html_path = output_dir / f"notification_test_{ctx.format_time()}.html" html_content = f"""<!DOCTYPE html> <html lang="zh-CN"> <head><meta charset="UTF-8"><title>TrendRadar 通知测试</title></head> <body> <h2>TrendRadar 通知连通性测试</h2> <p>测试时间:{now.strftime('%Y-%m-%d %H:%M:%S')} ({ctx.timezone})</p> <p>这是一条测试消息,用于验证邮件渠道是否可达。</p> </body> </html>""" html_path.write_text(html_content, encoding="utf-8") return str(html_path) except Exception as e: print(f"[测试通知] 创建测试 HTML 失败: {e}") return None def _run_test_notification(config: Dict) -> bool: from trendradar.notification import NotificationDispatcher ctx = AppContext(config) try: # 检查是否配置了通知渠道 has_notification = any( [ config.get("FEISHU_WEBHOOK_URL"), config.get("DINGTALK_WEBHOOK_URL"), config.get("WEWORK_WEBHOOK_URL"), (config.get("TELEGRAM_BOT_TOKEN") and config.get("TELEGRAM_CHAT_ID")), (config.get("EMAIL_FROM") and config.get("EMAIL_PASSWORD") and config.get("EMAIL_TO")), (config.get("NTFY_SERVER_URL") and config.get("NTFY_TOPIC")), config.get("BARK_URL"), config.get("SLACK_WEBHOOK_URL"), config.get("GENERIC_WEBHOOK_URL"), ] ) if not has_notification: print("未检测到可用通知渠道,请先在 config.yaml 或环境变量中配置。") return False # 测试时固定展示区域,避免用户关闭 HOTLIST 导致测试内容为空 test_config = copy.deepcopy(config) test_display = test_config.setdefault("DISPLAY", {}) test_regions = test_display.setdefault("REGIONS", {}) test_regions.update( { "HOTLIST": True, "NEW_ITEMS": False, "RSS": False, "STANDALONE": False, "AI_ANALYSIS": False, } ) # 测试时禁用翻译,避免触发额外 AI 调用 if "AI_TRANSLATION" in test_config: test_config["AI_TRANSLATION"]["ENABLED"] = False proxy_url = test_config.get("DEFAULT_PROXY", "") if test_config.get("USE_PROXY") else None if proxy_url: print("[测试通知] 检测到代理配置,将使用代理发送") dispatcher = NotificationDispatcher( config=test_config, get_time_func=ctx.get_time, split_content_func=ctx.split_content, translator=None, ) report_data = _build_test_report_data(ctx) html_file_path = _create_test_html_file(ctx) print("=" * 60) print("通知连通性测试") print("=" * 60) results = dispatcher.dispatch_all( report_data=report_data, report_type="通知连通性测试", proxy_url=proxy_url, mode="daily", html_file_path=html_file_path, ) if not results: print("没有可测试的有效通知渠道(可能配置不完整)。") return False print("-" * 60) success_count = 0 for channel, ok in results.items(): if ok: success_count += 1 print(f"✅ {channel}: 测试成功") else: print(f"❌ {channel}: 测试失败") print("-" * 60) print(f"测试结果: {success_count}/{len(results)} 个渠道成功") return success_count > 0 finally: ctx.cleanup() def main(): # 解析命令行参数 parser = argparse.ArgumentParser( description="TrendRadar - 热点新闻聚合与分析工具", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" 调度状态命令: --show-schedule 显示当前调度状态(时间段、行为开关) 诊断命令: --doctor 运行环境与配置体检 --test-notification 发送测试通知到已配置渠道 示例: python -m trendradar # 正常运行 python -m trendradar --show-schedule # 查看当前调度状态 python -m trendradar --doctor # 运行一键体检 python -m trendradar --test-notification # 测试通知渠道连通性 """ ) parser.add_argument( "--show-schedule", action="store_true", help="显示当前调度状态" ) parser.add_argument( "--doctor", action="store_true", help="运行环境与配置体检" ) parser.add_argument( "--test-notification", action="store_true", help="发送测试通知到已配置渠道" ) args = parser.parse_args() debug_mode = False try: # 处理 doctor 命令(不依赖完整运行流程) if args.doctor: ok = _run_doctor() if not ok: raise SystemExit(1) return # 先加载配置 config = load_config() # 处理状态查看命令 if args.show_schedule: _handle_status_commands(config) return # 处理通知测试命令 if args.test_notification: ok = _run_test_notification(config) if not ok: raise SystemExit(1) return version_url = config.get("VERSION_CHECK_URL", "") configs_version_url = config.get("CONFIGS_VERSION_CHECK_URL", "") # 统一版本检查(程序版本 + 配置文件版本,只请求一次远程) need_update = False remote_version = None if version_url: need_update, remote_version = check_all_versions(version_url, configs_version_url) # 复用已加载的配置,避免重复加载 analyzer = NewsAnalyzer(config=config) # 设置更新信息(复用已获取的远程版本,不再重复请求) if analyzer.is_github_actions and need_update and remote_version: analyzer.update_info = { "current_version": __version__, "remote_version": remote_version, } # 获取 debug 配置 debug_mode = analyzer.ctx.config.get("DEBUG", False) analyzer.run() except FileNotFoundError as e: print(f"❌ 配置文件错误: {e}") print("\n请确保以下文件存在:") print(" • config/config.yaml") print(" • config/frequency_words.txt") print("\n参考项目文档进行正确配置") except Exception as e: print(f"❌ 程序运行错误: {e}") if debug_mode: raise def _handle_status_commands(config: Dict) -> None: from trendradar.context import AppContext ctx = AppContext(config) print("=" * 60) print(f"TrendRadar v{__version__} 调度状态") print("=" * 60) try: scheduler = ctx.create_scheduler() schedule = scheduler.resolve() now = ctx.get_time() date_str = ctx.format_date() print(f"\n⏰ 当前时间: {now.strftime('%Y-%m-%d %H:%M:%S')} ({ctx.timezone})") print(f"📅 当前日期: {date_str}") print(f"\n📋 调度信息:") print(f" 日计划: {schedule.day_plan}") if schedule.period_key: print(f" 当前时间段: {schedule.period_name or schedule.period_key} ({schedule.period_key})") else: print(f" 当前时间段: 无(使用默认配置)") print(f"\n🔧 行为开关:") print(f" 采集数据: {'✅ 是' if schedule.collect else '❌ 否'}") print(f" AI 分析: {'✅ 是' if schedule.analyze else '❌ 否'}") print(f" 推送通知: {'✅ 是' if schedule.push else '❌ 否'}") print(f" 报告模式: {schedule.report_mode}") print(f" AI 模式: {schedule.ai_mode}") if schedule.period_key: print(f"\n🔁 一次性控制:") if schedule.once_analyze: already_analyzed = scheduler.already_executed(schedule.period_key, "analyze", date_str) print(f" AI 分析: 仅一次 {'(今日已执行 ⚠️)' if already_analyzed else '(今日未执行 ✅)'}") else: print(f" AI 分析: 不限次数") if schedule.once_push: already_pushed = scheduler.already_executed(schedule.period_key, "push", date_str) print(f" 推送通知: 仅一次 {'(今日已执行 ⚠️)' if already_pushed else '(今日未执行 ✅)'}") else: print(f" 推送通知: 不限次数") except Exception as e: print(f"\n❌ 获取调度状态失败: {e}") print("\n" + "=" * 60) # 清理资源 ctx.cleanup() if __name__ == "__main__": main()
--- +++ @@ -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(parts) >= 3: @@ -35,6 +42,7 @@ def _compare_version(local: str, remote: str) -> str: + """比较版本号,返回状态文字""" local_tuple = _parse_version(local) remote_tuple = _parse_version(remote) @@ -47,6 +55,7 @@ def _fetch_remote_version(version_url: str, proxy_url: Optional[str] = None) -> Optional[str]: + """获取远程版本号""" try: proxies = None if proxy_url: @@ -67,6 +76,7 @@ def _parse_config_versions(content: str) -> Dict[str, str]: + """解析配置文件版本内容为字典""" versions = {} try: if not content: @@ -87,6 +97,17 @@ configs_version_url: Optional[str] = None, proxy_url: Optional[str] = None ) -> Tuple[bool, Optional[str]]: + """ + 统一版本检查:程序版本 + 配置文件版本 + + Args: + version_url: 远程程序版本检查 URL + configs_version_url: 远程配置文件版本检查 URL (返回格式: filename=version) + proxy_url: 代理 URL + + Returns: + (need_update, remote_version): 程序是否需要更新及远程版本号 + """ # 获取远程版本 remote_version = _fetch_remote_version(version_url, proxy_url) @@ -169,6 +190,7 @@ # === 主分析器 === class NewsAnalyzer: + """新闻分析器""" # 模式策略定义 MODE_STRATEGIES = { @@ -222,6 +244,7 @@ # 注意:update_info 由 main() 函数设置,避免重复请求远程版本 def _init_storage_manager(self) -> None: + """初始化存储管理器(使用 AppContext)""" # 获取数据保留天数(支持环境变量覆盖) env_retention = os.environ.get("STORAGE_RETENTION_DAYS", "").strip() if env_retention: @@ -236,6 +259,7 @@ print(f"数据保留天数: {retention_days} 天") def _detect_docker_environment(self) -> bool: + """检测是否运行在 Docker 容器中""" try: if os.environ.get("DOCKER_CONTAINER") == "true": return True @@ -248,9 +272,11 @@ return False def _should_open_browser(self) -> bool: + """判断是否应该打开浏览器""" return not self.is_github_actions and not self.is_docker_container def _setup_proxy(self) -> None: + """设置代理配置""" if not self.is_github_actions and self.ctx.config["USE_PROXY"]: self.proxy_url = self.ctx.config["DEFAULT_PROXY"] print("本地环境,使用代理") @@ -260,6 +286,7 @@ print("GitHub Actions环境,不使用代理") def _set_update_info_from_config(self) -> None: + """从已缓存的远程版本设置更新信息(不再重复请求)""" try: version_url = self.ctx.config.get("VERSION_CHECK_URL", "") if not version_url: @@ -277,9 +304,11 @@ print(f"版本检查出错: {e}") def _get_mode_strategy(self) -> Dict: + """获取当前模式的策略配置""" return self.MODE_STRATEGIES.get(self.report_mode, self.MODE_STRATEGIES["daily"]) def _has_notification_configured(self) -> bool: + """检查是否配置了任何通知渠道""" cfg = self.ctx.config return any( [ @@ -302,6 +331,7 @@ def _has_valid_content( self, stats: List[Dict], new_titles: Optional[Dict] = None ) -> bool: + """检查是否有有效的新闻内容""" if self.report_mode == "incremental": # 增量模式:只要有匹配的新闻就推送 # count_word_frequency 已经确保只处理新增的新闻(包括当天第一次爬取的情况) @@ -324,6 +354,17 @@ current_results: Optional[Dict] = None, current_id_to_name: Optional[Dict] = None, ) -> Tuple[List[Dict], Optional[Dict]]: + """ + 为 AI 分析准备指定模式的数据 + + Args: + ai_mode: AI 分析模式 (daily/current/incremental) + current_results: 当前抓取的结果(用于 incremental 模式) + current_id_to_name: 当前的平台映射(用于 incremental 模式) + + Returns: + Tuple[stats, id_to_name]: 统计数据和平台映射 + """ try: word_groups, filter_words, global_filters = self.ctx.load_frequency_words(self.frequency_file) @@ -424,6 +465,7 @@ schedule: ResolvedSchedule = None, standalone_data: Optional[Dict] = None, ) -> Optional[AIAnalysisResult]: + """执行 AI 分析""" analysis_config = self.ctx.config.get("AI_ANALYSIS", {}) if not analysis_config.get("ENABLED", False): return None @@ -544,6 +586,7 @@ self, quiet: bool = False, ) -> Optional[Tuple[Dict, Dict, Dict, Dict, List, List]]: + """统一的数据加载和预处理,使用当前监控平台列表过滤历史数据""" try: # 获取当前配置的监控平台ID列表 current_platform_ids = self.ctx.platform_ids @@ -579,6 +622,7 @@ return None def _prepare_current_title_info(self, results: Dict, time_info: str) -> Dict: + """从当前抓取结果构建标题信息""" title_info = {} for source_id, titles_data in results.items(): title_info[source_id] = {} @@ -604,6 +648,24 @@ title_info: Optional[Dict] = None, rss_items: Optional[List[Dict]] = None, ) -> Optional[Dict]: + """ + 从原始数据中提取独立展示区数据 + + 纯数据准备方法,不检查 display.regions.standalone 开关。 + 各消费者自行决定是否使用: + - AI 分析:由 ai.include_standalone 控制 + - 通知推送:由 display.regions.standalone 控制(在 dispatcher 层门控) + - HTML 报告:始终包含(如果有数据) + + Args: + results: 原始爬取结果 {platform_id: {title: title_data}} + id_to_name: 平台 ID 到名称的映射 + title_info: 标题元信息(含排名历史、时间等) + rss_items: RSS 条目列表 + + Returns: + 独立展示数据字典,如果未配置数据源返回 None + """ display_config = self.ctx.config.get("DISPLAY", {}) standalone_config = display_config.get("STANDALONE", {}) @@ -747,6 +809,7 @@ schedule: ResolvedSchedule = None, rss_new_urls: Optional[set] = None, ) -> Tuple[List[Dict], Optional[str], Optional[AIAnalysisResult], Optional[List[Dict]]]: + """统一的分析流水线:数据处理 → 统计计算(关键词/AI筛选)→ AI分析 → HTML生成""" # 根据筛选策略选择数据处理方式 if self.filter_method == "ai": @@ -840,6 +903,7 @@ current_results: Optional[Dict] = None, schedule: ResolvedSchedule = None, ) -> bool: + """统一的通知发送逻辑,包含所有判断条件,支持热榜+RSS合并推送+AI分析+独立展示区""" has_notification = self._has_notification_configured() cfg = self.ctx.config @@ -946,6 +1010,7 @@ return False def _initialize_and_check_config(self) -> None: + """通用初始化和配置检查""" now = self.ctx.get_time() print(f"当前北京时间: {now.strftime('%Y-%m-%d %H:%M:%S')}") @@ -966,6 +1031,7 @@ print(f"运行模式: {mode_strategy['description']}") def _crawl_data(self) -> Tuple[Dict, Dict, List]: + """执行数据爬取""" ids = [] for platform in self.ctx.platforms: if "name" in platform: @@ -1002,6 +1068,17 @@ return results, id_to_name, failed_ids def _crawl_rss_data(self) -> Tuple[Optional[List[Dict]], Optional[List[Dict]], Optional[List[Dict]], set]: + """ + 执行 RSS 数据抓取 + + Returns: + (rss_items, rss_new_items, raw_rss_items, rss_new_urls) 元组: + - rss_items: 统计条目列表(按模式处理,用于统计区块) + - rss_new_items: 新增条目列表(用于新增区块) + - raw_rss_items: 原始 RSS 条目列表(用于独立展示区) + - rss_new_urls: 原始新增 RSS 条目的 URL 集合(用于 AI 模式 is_new 检测) + 如果未启用或失败返回 (None, None, None, set()) + """ if not self.ctx.rss_enabled: return None, None, None, set() @@ -1090,6 +1167,24 @@ return None, None, None, set() def _process_rss_data_by_mode(self, rss_data) -> Tuple[Optional[List[Dict]], Optional[List[Dict]], Optional[List[Dict]], set]: + """ + 按报告模式处理 RSS 数据,返回与热榜相同格式的统计结构 + + 三种模式: + - daily: 当日汇总,统计=当天所有条目,新增=本次新增条目 + - current: 当前榜单,统计=当前榜单条目,新增=本次新增条目 + - incremental: 增量模式,统计=新增条目,新增=无 + + Args: + rss_data: 当前抓取的 RSSData 对象 + + Returns: + (rss_stats, rss_new_stats, raw_rss_items, rss_new_urls) 元组: + - rss_stats: RSS 关键词统计列表(与热榜 stats 格式一致) + - rss_new_stats: RSS 新增关键词统计列表(与热榜 stats 格式一致) + - raw_rss_items: 原始 RSS 条目列表(用于独立展示区) + - rss_new_urls: 原始新增 RSS 条目的 URL 集合(未经关键词过滤,用于 AI 模式 is_new 检测) + """ from trendradar.core.analyzer import count_rss_frequency # 从 display.regions.rss 统一控制 RSS 分析和展示 @@ -1244,6 +1339,7 @@ return rss_stats, rss_new_stats, raw_rss_items, rss_new_urls def _convert_rss_items_to_list(self, items_dict: Dict, id_to_name: Dict) -> List[Dict]: + """将 RSS 条目字典转换为列表格式,并应用新鲜度过滤(用于推送)""" rss_items = [] filtered_count = 0 filtered_details = [] # 用于 DEBUG 模式下的详细日志 @@ -1315,6 +1411,7 @@ return rss_items def _filter_rss_by_keywords(self, rss_items: List[Dict]) -> List[Dict]: + """使用关键词文件过滤 RSS 条目""" try: word_groups, filter_words, global_filters = self.ctx.load_frequency_words(self.frequency_file) if word_groups or filter_words or global_filters: @@ -1338,6 +1435,7 @@ return rss_items def _generate_rss_html_report(self, rss_items: list, feeds_info: dict) -> str: + """生成 RSS HTML 报告""" try: from trendradar.report.rss_html import render_rss_html_content from pathlib import Path @@ -1373,6 +1471,12 @@ raw_rss_items: Optional[List[Dict]] = None, rss_new_urls: Optional[set] = None, ) -> Optional[str]: + """执行模式特定逻辑,支持热榜+RSS合并推送 + + 简化后的逻辑: + - 每次运行都生成 HTML 报告(时间戳快照 + latest/{mode}.html + index.html) + - 根据模式发送通知 + """ # 调度系统 scheduler = self.ctx.create_scheduler() schedule = scheduler.resolve() @@ -1581,6 +1685,7 @@ return html_file def run(self) -> None: + """执行分析流程""" try: self._initialize_and_check_config() @@ -1609,6 +1714,7 @@ def _record_doctor_result(results: List[Tuple[str, str, str]], status: str, item: str, detail: str) -> None: + """记录并打印 doctor 检查结果""" icon_map = { "pass": "✅", "warn": "⚠️", @@ -1626,6 +1732,7 @@ fail_count: int, config_path: Optional[str], ) -> None: + """保存 doctor 体检报告到 JSON 文件""" report = { "version": __version__, "generated_at": datetime.now(timezone.utc).isoformat(), @@ -1656,6 +1763,7 @@ def _run_doctor(config_path: Optional[str] = None) -> bool: + """运行环境体检""" print("=" * 60) print(f"TrendRadar v{__version__} 环境体检") print("=" * 60) @@ -1864,6 +1972,7 @@ def _build_test_report_data(ctx: AppContext) -> Dict: + """构造通知测试用报告数据""" now = ctx.get_time() time_display = now.strftime("%H:%M") title = f"TrendRadar 通知测试消息({now.strftime('%Y-%m-%d %H:%M:%S')})" @@ -1896,6 +2005,7 @@ def _create_test_html_file(ctx: AppContext) -> Optional[str]: + """创建邮件测试用 HTML 文件""" try: now = ctx.get_time() output_dir = Path("output") / "html" / ctx.format_date() @@ -1918,6 +2028,7 @@ def _run_test_notification(config: Dict) -> bool: + """发送测试通知到已配置渠道""" from trendradar.notification import NotificationDispatcher ctx = AppContext(config) @@ -2006,6 +2117,7 @@ def main(): + """主程序入口""" # 解析命令行参数 parser = argparse.ArgumentParser( description="TrendRadar - 热点新闻聚合与分析工具", @@ -2101,6 +2213,7 @@ def _handle_status_commands(config: Dict) -> None: + """处理状态查看命令 - 显示当前调度状态""" from trendradar.context import AppContext ctx = AppContext(config) @@ -2156,4 +2269,4 @@ if __name__ == "__main__": - main()+ main()
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 Management"] = len(ANALYST_ORDER) # Add Risk Management at the end return sorted(signals, key=lambda x: analyst_order.get(x[0], 999)) def print_trading_output(result: dict) -> None: decisions = result.get("decisions") if not decisions: print(f"{Fore.RED}No trading decisions available{Style.RESET_ALL}") return # Print decisions for each ticker for ticker, decision in decisions.items(): print(f"\n{Fore.WHITE}{Style.BRIGHT}Analysis for {Fore.CYAN}{ticker}{Style.RESET_ALL}") print(f"{Fore.WHITE}{Style.BRIGHT}{'=' * 50}{Style.RESET_ALL}") # Prepare analyst signals table for this ticker table_data = [] for agent, signals in result.get("analyst_signals", {}).items(): if ticker not in signals: continue # Skip Risk Management agent in the signals section if agent == "risk_management_agent": continue signal = signals[ticker] agent_name = agent.replace("_agent", "").replace("_", " ").title() signal_type = signal.get("signal", "").upper() confidence = signal.get("confidence", 0) signal_color = { "BULLISH": Fore.GREEN, "BEARISH": Fore.RED, "NEUTRAL": Fore.YELLOW, }.get(signal_type, Fore.WHITE) # Get reasoning if available reasoning_str = "" if "reasoning" in signal and signal["reasoning"]: reasoning = signal["reasoning"] # Handle different types of reasoning (string, dict, etc.) if isinstance(reasoning, str): reasoning_str = reasoning elif isinstance(reasoning, dict): # Convert dict to string representation reasoning_str = json.dumps(reasoning, indent=2) else: # Convert any other type to string reasoning_str = str(reasoning) # Wrap long reasoning text to make it more readable wrapped_reasoning = "" current_line = "" # Use a fixed width of 60 characters to match the table column width max_line_length = 60 for word in reasoning_str.split(): if len(current_line) + len(word) + 1 > max_line_length: wrapped_reasoning += current_line + "\n" current_line = word else: if current_line: current_line += " " + word else: current_line = word if current_line: wrapped_reasoning += current_line reasoning_str = wrapped_reasoning table_data.append( [ f"{Fore.CYAN}{agent_name}{Style.RESET_ALL}", f"{signal_color}{signal_type}{Style.RESET_ALL}", f"{Fore.WHITE}{confidence}%{Style.RESET_ALL}", f"{Fore.WHITE}{reasoning_str}{Style.RESET_ALL}", ] ) # Sort the signals according to the predefined order table_data = sort_agent_signals(table_data) print(f"\n{Fore.WHITE}{Style.BRIGHT}AGENT ANALYSIS:{Style.RESET_ALL} [{Fore.CYAN}{ticker}{Style.RESET_ALL}]") print( tabulate( table_data, headers=[f"{Fore.WHITE}Agent", "Signal", "Confidence", "Reasoning"], tablefmt="grid", colalign=("left", "center", "right", "left"), ) ) # Print Trading Decision Table action = decision.get("action", "").upper() action_color = { "BUY": Fore.GREEN, "SELL": Fore.RED, "HOLD": Fore.YELLOW, "COVER": Fore.GREEN, "SHORT": Fore.RED, }.get(action, Fore.WHITE) # Get reasoning and format it reasoning = decision.get("reasoning", "") # Wrap long reasoning text to make it more readable wrapped_reasoning = "" if reasoning: current_line = "" # Use a fixed width of 60 characters to match the table column width max_line_length = 60 for word in reasoning.split(): if len(current_line) + len(word) + 1 > max_line_length: wrapped_reasoning += current_line + "\n" current_line = word else: if current_line: current_line += " " + word else: current_line = word if current_line: wrapped_reasoning += current_line decision_data = [ ["Action", f"{action_color}{action}{Style.RESET_ALL}"], ["Quantity", f"{action_color}{decision.get('quantity')}{Style.RESET_ALL}"], [ "Confidence", f"{Fore.WHITE}{decision.get('confidence'):.1f}%{Style.RESET_ALL}", ], ["Reasoning", f"{Fore.WHITE}{wrapped_reasoning}{Style.RESET_ALL}"], ] print(f"\n{Fore.WHITE}{Style.BRIGHT}TRADING DECISION:{Style.RESET_ALL} [{Fore.CYAN}{ticker}{Style.RESET_ALL}]") print(tabulate(decision_data, tablefmt="grid", colalign=("left", "left"))) # Print Portfolio Summary print(f"\n{Fore.WHITE}{Style.BRIGHT}PORTFOLIO SUMMARY:{Style.RESET_ALL}") portfolio_data = [] # Extract portfolio manager reasoning (common for all tickers) portfolio_manager_reasoning = None for ticker, decision in decisions.items(): if decision.get("reasoning"): portfolio_manager_reasoning = decision.get("reasoning") break analyst_signals = result.get("analyst_signals", {}) for ticker, decision in decisions.items(): action = decision.get("action", "").upper() action_color = { "BUY": Fore.GREEN, "SELL": Fore.RED, "HOLD": Fore.YELLOW, "COVER": Fore.GREEN, "SHORT": Fore.RED, }.get(action, Fore.WHITE) # Calculate analyst signal counts bullish_count = 0 bearish_count = 0 neutral_count = 0 if analyst_signals: for agent, signals in analyst_signals.items(): if ticker in signals: signal = signals[ticker].get("signal", "").upper() if signal == "BULLISH": bullish_count += 1 elif signal == "BEARISH": bearish_count += 1 elif signal == "NEUTRAL": neutral_count += 1 portfolio_data.append( [ f"{Fore.CYAN}{ticker}{Style.RESET_ALL}", f"{action_color}{action}{Style.RESET_ALL}", f"{action_color}{decision.get('quantity')}{Style.RESET_ALL}", f"{Fore.WHITE}{decision.get('confidence'):.1f}%{Style.RESET_ALL}", f"{Fore.GREEN}{bullish_count}{Style.RESET_ALL}", f"{Fore.RED}{bearish_count}{Style.RESET_ALL}", f"{Fore.YELLOW}{neutral_count}{Style.RESET_ALL}", ] ) headers = [ f"{Fore.WHITE}Ticker", f"{Fore.WHITE}Action", f"{Fore.WHITE}Quantity", f"{Fore.WHITE}Confidence", f"{Fore.WHITE}Bullish", f"{Fore.WHITE}Bearish", f"{Fore.WHITE}Neutral", ] # Print the portfolio summary table print( tabulate( portfolio_data, headers=headers, tablefmt="grid", colalign=("left", "center", "right", "right", "center", "center", "center"), ) ) # Print Portfolio Manager's reasoning if available if portfolio_manager_reasoning: # Handle different types of reasoning (string, dict, etc.) reasoning_str = "" if isinstance(portfolio_manager_reasoning, str): reasoning_str = portfolio_manager_reasoning elif isinstance(portfolio_manager_reasoning, dict): # Convert dict to string representation reasoning_str = json.dumps(portfolio_manager_reasoning, indent=2) else: # Convert any other type to string reasoning_str = str(portfolio_manager_reasoning) # Wrap long reasoning text to make it more readable wrapped_reasoning = "" current_line = "" # Use a fixed width of 60 characters to match the table column width max_line_length = 60 for word in reasoning_str.split(): if len(current_line) + len(word) + 1 > max_line_length: wrapped_reasoning += current_line + "\n" current_line = word else: if current_line: current_line += " " + word else: current_line = word if current_line: wrapped_reasoning += current_line print(f"\n{Fore.WHITE}{Style.BRIGHT}Portfolio Strategy:{Style.RESET_ALL}") print(f"{Fore.CYAN}{wrapped_reasoning}{Style.RESET_ALL}") def print_backtest_results(table_rows: list) -> None: # Clear the screen os.system("cls" if os.name == "nt" else "clear") # Split rows into ticker rows and summary rows ticker_rows = [] summary_rows = [] for row in table_rows: if isinstance(row[1], str) and "PORTFOLIO SUMMARY" in row[1]: summary_rows.append(row) else: ticker_rows.append(row) # Display latest portfolio summary if summary_rows: # Pick the most recent summary by date (YYYY-MM-DD) latest_summary = max(summary_rows, key=lambda r: r[0]) print(f"\n{Fore.WHITE}{Style.BRIGHT}PORTFOLIO SUMMARY:{Style.RESET_ALL}") # Adjusted indexes after adding Long/Short Shares position_str = latest_summary[7].split("$")[1].split(Style.RESET_ALL)[0].replace(",", "") cash_str = latest_summary[8].split("$")[1].split(Style.RESET_ALL)[0].replace(",", "") total_str = latest_summary[9].split("$")[1].split(Style.RESET_ALL)[0].replace(",", "") print(f"Cash Balance: {Fore.CYAN}${float(cash_str):,.2f}{Style.RESET_ALL}") print(f"Total Position Value: {Fore.YELLOW}${float(position_str):,.2f}{Style.RESET_ALL}") print(f"Total Value: {Fore.WHITE}${float(total_str):,.2f}{Style.RESET_ALL}") print(f"Portfolio Return: {latest_summary[10]}") if len(latest_summary) > 14 and latest_summary[14]: print(f"Benchmark Return: {latest_summary[14]}") # Display performance metrics if available if latest_summary[11]: # Sharpe ratio print(f"Sharpe Ratio: {latest_summary[11]}") if latest_summary[12]: # Sortino ratio print(f"Sortino Ratio: {latest_summary[12]}") if latest_summary[13]: # Max drawdown print(f"Max Drawdown: {latest_summary[13]}") # Add vertical spacing print("\n" * 2) # Print the table with just ticker rows print( tabulate( ticker_rows, headers=[ "Date", "Ticker", "Action", "Quantity", "Price", "Long Shares", "Short Shares", "Position Value", ], tablefmt="grid", colalign=( "left", # Date "left", # Ticker "center", # Action "right", # Quantity "right", # Price "right", # Long Shares "right", # Short Shares "right", # Position Value ), ) ) # Add vertical spacing print("\n" * 4) def format_backtest_row( date: str, ticker: str, action: str, quantity: float, price: float, long_shares: float = 0, short_shares: float = 0, position_value: float = 0, is_summary: bool = False, total_value: float = None, return_pct: float = None, cash_balance: float = None, total_position_value: float = None, sharpe_ratio: float = None, sortino_ratio: float = None, max_drawdown: float = None, benchmark_return_pct: float | None = None, ) -> list[any]: # Color the action action_color = { "BUY": Fore.GREEN, "COVER": Fore.GREEN, "SELL": Fore.RED, "SHORT": Fore.RED, "HOLD": Fore.WHITE, }.get(action.upper(), Fore.WHITE) if is_summary: return_color = Fore.GREEN if return_pct >= 0 else Fore.RED benchmark_str = "" if benchmark_return_pct is not None: bench_color = Fore.GREEN if benchmark_return_pct >= 0 else Fore.RED benchmark_str = f"{bench_color}{benchmark_return_pct:+.2f}%{Style.RESET_ALL}" return [ date, f"{Fore.WHITE}{Style.BRIGHT}PORTFOLIO SUMMARY{Style.RESET_ALL}", "", # Action "", # Quantity "", # Price "", # Long Shares "", # Short Shares f"{Fore.YELLOW}${total_position_value:,.2f}{Style.RESET_ALL}", # Total Position Value f"{Fore.CYAN}${cash_balance:,.2f}{Style.RESET_ALL}", # Cash Balance f"{Fore.WHITE}${total_value:,.2f}{Style.RESET_ALL}", # Total Value f"{return_color}{return_pct:+.2f}%{Style.RESET_ALL}", # Return f"{Fore.YELLOW}{sharpe_ratio:.2f}{Style.RESET_ALL}" if sharpe_ratio is not None else "", # Sharpe Ratio f"{Fore.YELLOW}{sortino_ratio:.2f}{Style.RESET_ALL}" if sortino_ratio is not None else "", # Sortino Ratio f"{Fore.RED}{max_drawdown:.2f}%{Style.RESET_ALL}" if max_drawdown is not None else "", # Max Drawdown (signed) benchmark_str, # Benchmark (S&P 500) ] else: return [ date, f"{Fore.CYAN}{ticker}{Style.RESET_ALL}", f"{action_color}{action.upper()}{Style.RESET_ALL}", f"{action_color}{quantity:,.0f}{Style.RESET_ALL}", f"{Fore.WHITE}{price:,.2f}{Style.RESET_ALL}", f"{Fore.GREEN}{long_shares:,.0f}{Style.RESET_ALL}", # Long Shares f"{Fore.RED}{short_shares:,.0f}{Style.RESET_ALL}", # Short Shares f"{Fore.YELLOW}{position_value:,.2f}{Style.RESET_ALL}", ]
--- +++ @@ -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 Management at the end @@ -14,6 +15,12 @@ def print_trading_output(result: dict) -> None: + """ + Print formatted trading results with colored tables for multiple tickers. + + Args: + result (dict): Dictionary containing decisions and analyst signals for multiple tickers + """ decisions = result.get("decisions") if not decisions: print(f"{Fore.RED}No trading decisions available{Style.RESET_ALL}") @@ -248,6 +255,7 @@ def print_backtest_results(table_rows: list) -> None: + """Print the backtest results in a nicely formatted table""" # Clear the screen os.system("cls" if os.name == "nt" else "clear") @@ -341,6 +349,7 @@ max_drawdown: float = None, benchmark_return_pct: float | None = None, ) -> list[any]: + """Format a row for the backtest results table""" # Color the action action_color = { "BUY": Fore.GREEN, @@ -383,4 +392,4 @@ f"{Fore.GREEN}{long_shares:,.0f}{Style.RESET_ALL}", # Long Shares f"{Fore.RED}{short_shares:,.0f}{Style.RESET_ALL}", # Short Shares f"{Fore.YELLOW}{position_value:,.2f}{Style.RESET_ALL}", - ]+ ]
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)] # 过滤掉全部为空的情况 if all(not acc for acc in accounts): return [] return accounts def validate_paired_configs( configs: Dict[str, List[str]], channel_name: str, required_keys: Optional[List[str]] = None ) -> Tuple[bool, int]: # 过滤掉空列表 non_empty_configs = {k: v for k, v in configs.items() if v} if not non_empty_configs: return True, 0 # 检查必须项 if required_keys: for key in required_keys: if key not in non_empty_configs or not non_empty_configs[key]: return True, 0 # 必须项为空,视为未配置 # 获取所有非空配置的长度 lengths = {k: len(v) for k, v in non_empty_configs.items()} unique_lengths = set(lengths.values()) if len(unique_lengths) > 1: print(f"❌ {channel_name} 配置错误:配对配置数量不一致,将跳过该渠道推送") for key, length in lengths.items(): print(f" - {key}: {length} 个") return False, 0 return True, list(unique_lengths)[0] if unique_lengths else 0 def limit_accounts( accounts: List[str], max_count: int, channel_name: str ) -> List[str]: if len(accounts) > max_count: print(f"⚠️ {channel_name} 配置了 {len(accounts)} 个账号,超过最大限制 {max_count},只使用前 {max_count} 个") print(f" ⚠️ 警告:如果你是 fork 用户,过多账号可能导致 GitHub Actions 运行时间过长,存在账号风险") return accounts[:max_count] return accounts def get_account_at_index(accounts: List[str], index: int, default: str = "") -> str: if index < len(accounts): return accounts[index] if accounts[index] else default return default
--- +++ @@ -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: 配置值字符串,多个账号用分隔符分隔 + separator: 分隔符,默认为 ; + + Returns: + 账号列表,空字符串会被保留(用于占位) + + Examples: + >>> parse_multi_account_config("url1;url2;url3") + ['url1', 'url2', 'url3'] + >>> parse_multi_account_config(";token2") # 第一个账号无token + ['', 'token2'] + >>> parse_multi_account_config("") + [] + """ if not config_value: return [] # 保留空字符串用于占位(如 ";token2" 表示第一个账号无token) @@ -19,6 +42,33 @@ channel_name: str, required_keys: Optional[List[str]] = None ) -> Tuple[bool, int]: + """ + 验证配对配置的数量是否一致 + + 对于需要多个配置项配对的渠道(如 Telegram 的 token 和 chat_id), + 验证所有配置项的账号数量是否一致。 + + Args: + configs: 配置字典,key 为配置名,value 为账号列表 + channel_name: 渠道名称,用于日志输出 + required_keys: 必须有值的配置项列表 + + Returns: + (是否验证通过, 账号数量) + + Examples: + >>> validate_paired_configs({ + ... "token": ["t1", "t2"], + ... "chat_id": ["c1", "c2"] + ... }, "Telegram", ["token", "chat_id"]) + (True, 2) + + >>> validate_paired_configs({ + ... "token": ["t1", "t2"], + ... "chat_id": ["c1"] # 数量不匹配 + ... }, "Telegram", ["token", "chat_id"]) + (False, 0) + """ # 过滤掉空列表 non_empty_configs = {k: v for k, v in configs.items() if v} @@ -49,6 +99,25 @@ max_count: int, channel_name: str ) -> List[str]: + """ + 限制账号数量 + + 当配置的账号数量超过最大限制时,只使用前 N 个账号, + 并输出警告信息。 + + Args: + accounts: 账号列表 + max_count: 最大账号数量 + channel_name: 渠道名称,用于日志输出 + + Returns: + 限制后的账号列表 + + Examples: + >>> limit_accounts(["a1", "a2", "a3"], 2, "飞书") + ⚠️ 飞书 配置了 3 个账号,超过最大限制 2,只使用前 2 个 + ['a1', 'a2'] + """ if len(accounts) > max_count: print(f"⚠️ {channel_name} 配置了 {len(accounts)} 个账号,超过最大限制 {max_count},只使用前 {max_count} 个") print(f" ⚠️ 警告:如果你是 fork 用户,过多账号可能导致 GitHub Actions 运行时间过长,存在账号风险") @@ -57,6 +126,27 @@ def get_account_at_index(accounts: List[str], index: int, default: str = "") -> str: + """ + 安全获取指定索引的账号值 + + 当索引超出范围或账号值为空时,返回默认值。 + + Args: + accounts: 账号列表 + index: 索引 + default: 默认值 + + Returns: + 账号值或默认值 + + Examples: + >>> get_account_at_index(["a", "b", "c"], 1) + 'b' + >>> get_account_at_index(["a", "", "c"], 1, "default") + 'default' + >>> get_account_at_index(["a"], 5, "default") + 'default' + """ if index < len(accounts): return accounts[index] if accounts[index] else default - return default+ return default
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[[], datetime]] = None, ) -> str: html = """ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>RSS 订阅内容</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js" integrity="sha512-BNaRQnYJYiPSqHHDb58B0yaPfCu+Wgds8Gp/gU33kqBtgNS4tSPHuGibyoeqMV/TJlSKda6FXzoEyYGjTe+vXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <style> * { box-sizing: border-box; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif; margin: 0; padding: 16px; background: #fafafa; color: #333; line-height: 1.5; } .container { max-width: 700px; margin: 0 auto; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 16px rgba(0,0,0,0.06); } .header { background: linear-gradient(135deg, #059669 0%, #10b981 100%); color: white; padding: 32px 24px; text-align: center; position: relative; } .save-buttons { position: absolute; top: 16px; right: 16px; display: flex; gap: 8px; } .save-btn { background: rgba(255, 255, 255, 0.2); border: 1px solid rgba(255, 255, 255, 0.3); color: white; padding: 8px 16px; border-radius: 6px; cursor: pointer; font-size: 13px; font-weight: 500; transition: all 0.2s ease; backdrop-filter: blur(10px); white-space: nowrap; } .save-btn:hover { background: rgba(255, 255, 255, 0.3); border-color: rgba(255, 255, 255, 0.5); transform: translateY(-1px); } .save-btn:active { transform: translateY(0); } .save-btn:disabled { opacity: 0.6; cursor: not-allowed; } .header-title { font-size: 22px; font-weight: 700; margin: 0 0 20px 0; } .header-info { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; font-size: 14px; opacity: 0.95; } .info-item { text-align: center; } .info-label { display: block; font-size: 12px; opacity: 0.8; margin-bottom: 4px; } .info-value { font-weight: 600; font-size: 16px; } .content { padding: 24px; } .feed-group { margin-bottom: 32px; } .feed-group:last-child { margin-bottom: 0; } .feed-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; padding-bottom: 8px; border-bottom: 2px solid #10b981; } .feed-name { font-size: 16px; font-weight: 600; color: #059669; } .feed-count { color: #666; font-size: 13px; font-weight: 500; } .rss-item { margin-bottom: 16px; padding: 16px; background: #f9fafb; border-radius: 8px; border-left: 3px solid #10b981; } .rss-item:last-child { margin-bottom: 0; } .rss-meta { display: flex; align-items: center; gap: 12px; margin-bottom: 8px; flex-wrap: wrap; } .rss-time { color: #6b7280; font-size: 12px; } .rss-author { color: #059669; font-size: 12px; font-weight: 500; } .rss-title { font-size: 15px; line-height: 1.5; color: #1a1a1a; margin: 0 0 8px 0; font-weight: 500; } .rss-link { color: #2563eb; text-decoration: none; } .rss-link:hover { text-decoration: underline; } .rss-link:visited { color: #7c3aed; } .rss-summary { font-size: 13px; color: #6b7280; line-height: 1.6; margin: 0; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; } .footer { margin-top: 32px; padding: 20px 24px; background: #f8f9fa; border-top: 1px solid #e5e7eb; text-align: center; } .footer-content { font-size: 13px; color: #6b7280; line-height: 1.6; } .footer-link { color: #059669; text-decoration: none; font-weight: 500; transition: color 0.2s ease; } .footer-link:hover { color: #10b981; text-decoration: underline; } .project-name { font-weight: 600; color: #374151; } @media (max-width: 480px) { body { padding: 12px; } .header { padding: 24px 20px; } .content { padding: 20px; } .footer { padding: 16px 20px; } .header-info { grid-template-columns: 1fr; gap: 12px; } .rss-meta { gap: 8px; } .rss-item { padding: 12px; } .save-buttons { position: static; margin-bottom: 16px; display: flex; gap: 8px; justify-content: center; flex-direction: column; width: 100%; } .save-btn { width: 100%; } } </style> </head> <body> <div class="container"> <div class="header"> <div class="save-buttons"> <button class="save-btn" onclick="saveAsImage()">保存为图片</button> </div> <div class="header-title">RSS 订阅内容</div> <div class="header-info"> <div class="info-item"> <span class="info-label">订阅条目</span> <span class="info-value">""" html += f"{total_count} 条" html += """</span> </div> <div class="info-item"> <span class="info-label">生成时间</span> <span class="info-value">""" # 使用提供的时间函数或默认 datetime.now if get_time_func: now = get_time_func() else: now = datetime.now() html += now.strftime("%m-%d %H:%M") html += """</span> </div> </div> </div> <div class="content">""" # 按 feed_id 分组 feeds_map: Dict[str, List[Dict]] = {} for item in rss_items: feed_id = item.get("feed_id", "unknown") if feed_id not in feeds_map: feeds_map[feed_id] = [] feeds_map[feed_id].append(item) # 渲染每个 RSS 源的内容 for feed_id, items in feeds_map.items(): feed_name = items[0].get("feed_name", feed_id) if items else feed_id if feeds_info and feed_id in feeds_info: feed_name = feeds_info[feed_id] escaped_feed_name = html_escape(feed_name) html += f""" <div class="feed-group"> <div class="feed-header"> <div class="feed-name">{escaped_feed_name}</div> <div class="feed-count">{len(items)} 条</div> </div>""" for item in items: escaped_title = html_escape(item.get("title", "")) url = item.get("url", "") published_at = item.get("published_at", "") author = item.get("author", "") summary = item.get("summary", "") html += """ <div class="rss-item"> <div class="rss-meta">""" if published_at: html += f'<span class="rss-time">{html_escape(published_at)}</span>' if author: html += f'<span class="rss-author">by {html_escape(author)}</span>' html += """ </div> <div class="rss-title">""" if url: escaped_url = html_escape(url) html += f'<a href="{escaped_url}" target="_blank" class="rss-link">{escaped_title}</a>' else: html += escaped_title html += """ </div>""" if summary: escaped_summary = html_escape(summary) html += f""" <p class="rss-summary">{escaped_summary}</p>""" html += """ </div>""" html += """ </div>""" html += """ </div> <div class="footer"> <div class="footer-content"> 由 <span class="project-name">TrendRadar</span> 生成 · <a href="https://github.com/sansan0/TrendRadar" target="_blank" class="footer-link"> GitHub 开源项目 </a> </div> </div> </div> <script> async function saveAsImage() { const button = event.target; const originalText = button.textContent; try { button.textContent = '生成中...'; button.disabled = true; window.scrollTo(0, 0); await new Promise(resolve => setTimeout(resolve, 200)); const buttons = document.querySelector('.save-buttons'); buttons.style.visibility = 'hidden'; await new Promise(resolve => setTimeout(resolve, 100)); const container = document.querySelector('.container'); const canvas = await html2canvas(container, { backgroundColor: '#ffffff', scale: 1.5, useCORS: true, allowTaint: false, imageTimeout: 10000, removeContainer: false, foreignObjectRendering: false, logging: false, width: container.offsetWidth, height: container.offsetHeight, x: 0, y: 0, scrollX: 0, scrollY: 0, windowWidth: window.innerWidth, windowHeight: window.innerHeight }); buttons.style.visibility = 'visible'; const link = document.createElement('a'); const now = new Date(); const filename = `TrendRadar_RSS订阅_${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}_${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}.png`; link.download = filename; link.href = canvas.toDataURL('image/png', 1.0); document.body.appendChild(link); link.click(); document.body.removeChild(link); button.textContent = '保存成功!'; setTimeout(() => { button.textContent = originalText; button.disabled = false; }, 2000); } catch (error) { const buttons = document.querySelector('.save-buttons'); buttons.style.visibility = 'visible'; button.textContent = '保存失败'; setTimeout(() => { button.textContent = originalText; button.disabled = false; }, 2000); } } document.addEventListener('DOMContentLoaded', function() { window.scrollTo(0, 0); }); </script> </body> </html> """ return html
--- +++ @@ -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: + rss_items: RSS 条目列表,每个条目包含: + - title: 标题 + - feed_id: RSS 源 ID + - feed_name: RSS 源名称 + - url: 链接 + - published_at: 发布时间 + - summary: 摘要(可选) + - author: 作者(可选) + total_count: 条目总数 + feeds_info: RSS 源 ID 到名称的映射 + get_time_func: 获取当前时间的函数(可选,默认使用 datetime.now) + + Returns: + 渲染后的 HTML 字符串 + """ html = """ <!DOCTYPE html> <html> @@ -453,4 +476,4 @@ </html> """ - return html+ return html
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; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36", "Accept": "application/json, text/plain, */*", "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", "Connection": "keep-alive", "Cache-Control": "no-cache", } def __init__( self, proxy_url: Optional[str] = None, api_url: Optional[str] = None, ): self.proxy_url = proxy_url self.api_url = api_url or self.DEFAULT_API_URL def fetch_data( self, id_info: Union[str, Tuple[str, str]], max_retries: int = 2, min_retry_wait: int = 3, max_retry_wait: int = 5, ) -> Tuple[Optional[str], str, str]: if isinstance(id_info, tuple): id_value, alias = id_info else: id_value = id_info alias = id_value url = f"{self.api_url}?id={id_value}&latest" proxies = None if self.proxy_url: proxies = {"http": self.proxy_url, "https": self.proxy_url} retries = 0 while retries <= max_retries: try: response = requests.get( url, proxies=proxies, headers=self.DEFAULT_HEADERS, timeout=10, ) response.raise_for_status() data_text = response.text data_json = json.loads(data_text) status = data_json.get("status", "未知") if status not in ["success", "cache"]: raise ValueError(f"响应状态异常: {status}") status_info = "最新数据" if status == "success" else "缓存数据" print(f"获取 {id_value} 成功({status_info})") return data_text, id_value, alias except Exception as e: retries += 1 if retries <= max_retries: base_wait = random.uniform(min_retry_wait, max_retry_wait) additional_wait = (retries - 1) * random.uniform(1, 2) wait_time = base_wait + additional_wait print(f"请求 {id_value} 失败: {e}. {wait_time:.2f}秒后重试...") time.sleep(wait_time) else: print(f"请求 {id_value} 失败: {e}") return None, id_value, alias return None, id_value, alias def crawl_websites( self, ids_list: List[Union[str, Tuple[str, str]]], request_interval: int = 100, ) -> Tuple[Dict, Dict, List]: results = {} id_to_name = {} failed_ids = [] for i, id_info in enumerate(ids_list): if isinstance(id_info, tuple): id_value, name = id_info else: id_value = id_info name = id_value id_to_name[id_value] = name response, _, _ = self.fetch_data(id_info) if response: try: data = json.loads(response) results[id_value] = {} for index, item in enumerate(data.get("items", []), 1): title = item.get("title") # 跳过无效标题(None、float、空字符串) if title is None or isinstance(title, float) or not str(title).strip(): continue title = str(title).strip() url = item.get("url", "") mobile_url = item.get("mobileUrl", "") if title in results[id_value]: results[id_value][title]["ranks"].append(index) else: results[id_value][title] = { "ranks": [index], "url": url, "mobileUrl": mobile_url, } except json.JSONDecodeError: print(f"解析 {id_value} 响应失败") failed_ids.append(id_value) except Exception as e: print(f"处理 {id_value} 数据出错: {e}") failed_ids.append(id_value) else: failed_ids.append(id_value) # 请求间隔(除了最后一个) if i < len(ids_list) - 1: actual_interval = request_interval + random.randint(-10, 20) actual_interval = max(50, actual_interval) time.sleep(actual_interval / 1000) print(f"成功: {list(results.keys())}, 失败: {failed_ids}") return results, id_to_name, failed_ids
--- +++ @@ -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 @@ proxy_url: Optional[str] = None, api_url: Optional[str] = None, ): + """ + 初始化数据获取器 + + Args: + proxy_url: 代理服务器 URL(可选) + api_url: API 基础 URL(可选,默认使用 DEFAULT_API_URL) + """ self.proxy_url = proxy_url self.api_url = api_url or self.DEFAULT_API_URL @@ -37,6 +54,18 @@ min_retry_wait: int = 3, max_retry_wait: int = 5, ) -> Tuple[Optional[str], str, str]: + """ + 获取指定ID数据,支持重试 + + Args: + id_info: 平台ID 或 (平台ID, 别名) 元组 + max_retries: 最大重试次数 + min_retry_wait: 最小重试等待时间(秒) + max_retry_wait: 最大重试等待时间(秒) + + Returns: + (响应文本, 平台ID, 别名) 元组,失败时响应文本为 None + """ if isinstance(id_info, tuple): id_value, alias = id_info else: @@ -90,6 +119,16 @@ ids_list: List[Union[str, Tuple[str, str]]], request_interval: int = 100, ) -> Tuple[Dict, Dict, List]: + """ + 爬取多个网站数据 + + Args: + ids_list: 平台ID列表,每个元素可以是字符串或 (平台ID, 别名) 元组 + request_interval: 请求间隔(毫秒) + + Returns: + (结果字典, ID到名称的映射, 失败ID列表) 元组 + """ results = {} id_to_name = {} failed_ids = [] @@ -142,4 +181,4 @@ time.sleep(actual_interval / 1000) print(f"成功: {list(results.keys())}, 失败: {failed_ids}") - return results, id_to_name, failed_ids+ return results, id_to_name, failed_ids
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" elif format_type in ("wework_text", "bark"): # 企业微信文本模式和 Bark 使用纯文本格式 return f"[第 {batch_num}/{total_batches} 批次]\n\n" else: # 飞书、钉钉、ntfy、企业微信 markdown 模式 return f"**[第 {batch_num}/{total_batches} 批次]**\n\n" def get_max_batch_header_size(format_type: str) -> int: # 生成最坏情况的头部(99/99 批次) max_header = get_batch_header(format_type, 99, 99) return len(max_header.encode("utf-8")) def truncate_to_bytes(text: str, max_bytes: int) -> str: text_bytes = text.encode("utf-8") if len(text_bytes) <= max_bytes: return text # 截断到指定字节数 truncated = text_bytes[:max_bytes] # 处理可能的不完整 UTF-8 字符 for i in range(min(4, len(truncated))): try: return truncated[: len(truncated) - i].decode("utf-8") except UnicodeDecodeError: continue # 极端情况:返回空字符串 return "" def add_batch_headers( batches: List[str], format_type: str, max_bytes: int ) -> List[str]: if len(batches) <= 1: return batches total = len(batches) result = [] for i, content in enumerate(batches, 1): # 生成批次头部 header = get_batch_header(format_type, i, total) header_size = len(header.encode("utf-8")) # 动态计算允许的最大内容大小 max_content_size = max_bytes - header_size content_size = len(content.encode("utf-8")) # 如果超出,截断到安全大小 if content_size > max_content_size: print( f"警告:{format_type} 第 {i}/{total} 批次内容({content_size}字节) + 头部({header_size}字节) 超出限制({max_bytes}字节),截断到 {max_content_size} 字节" ) content = truncate_to_bytes(content, max_content_size) result.append(header + content) return result
--- +++ @@ -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, ntfy, wework) + batch_num: 当前批次编号 + total_batches: 总批次数 + + Returns: + 格式化的批次头部字符串 + """ if format_type == "telegram": return f"<b>[第 {batch_num}/{total_batches} 批次]</b>\n\n" elif format_type == "slack": @@ -17,12 +32,31 @@ def get_max_batch_header_size(format_type: str) -> int: + """估算批次头部的最大字节数(假设最多 99 批次) + + 用于在分批时预留空间,避免事后截断破坏内容完整性。 + + Args: + format_type: 推送类型 + + Returns: + 最大头部字节数 + """ # 生成最坏情况的头部(99/99 批次) max_header = get_batch_header(format_type, 99, 99) return len(max_header.encode("utf-8")) def truncate_to_bytes(text: str, max_bytes: int) -> str: + """安全截断字符串到指定字节数,避免截断多字节字符 + + Args: + text: 要截断的文本 + max_bytes: 最大字节数 + + Returns: + 截断后的文本 + """ text_bytes = text.encode("utf-8") if len(text_bytes) <= max_bytes: return text @@ -44,6 +78,16 @@ def add_batch_headers( batches: List[str], format_type: str, max_bytes: int ) -> List[str]: + """为批次添加头部,动态计算确保总大小不超过限制 + + Args: + batches: 原始批次列表 + format_type: 推送类型(bark, telegram, feishu 等) + max_bytes: 该推送类型的最大字节限制 + + Returns: + 添加头部后的批次列表 + """ if len(batches) <= 1: return batches @@ -68,4 +112,4 @@ result.append(header + content) - return result+ return result
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 trendradar.utils.time import ( DEFAULT_TIMEZONE, get_configured_time, format_date_folder, format_time_filename, ) class LocalStorageBackend(SQLiteStorageMixin, StorageBackend): def __init__( self, data_dir: str = "output", enable_txt: bool = True, enable_html: bool = True, timezone: str = DEFAULT_TIMEZONE, ): self.data_dir = Path(data_dir) self.enable_txt = enable_txt self.enable_html = enable_html self.timezone = timezone self._db_connections: Dict[str, sqlite3.Connection] = {} @property def backend_name(self) -> str: return "local" @property def supports_txt(self) -> bool: return self.enable_txt # ======================================== # SQLiteStorageMixin 抽象方法实现 # ======================================== def _get_configured_time(self) -> datetime: return get_configured_time(self.timezone) def _format_date_folder(self, date: Optional[str] = None) -> str: return format_date_folder(date, self.timezone) def _format_time_filename(self) -> str: return format_time_filename(self.timezone) def _get_db_path(self, date: Optional[str] = None, db_type: str = "news") -> Path: date_str = self._format_date_folder(date) db_dir = self.data_dir / db_type db_dir.mkdir(parents=True, exist_ok=True) return db_dir / f"{date_str}.db" def _get_connection(self, date: Optional[str] = None, db_type: str = "news") -> sqlite3.Connection: db_path = str(self._get_db_path(date, db_type)) if db_path not in self._db_connections: conn = sqlite3.connect(db_path) conn.row_factory = sqlite3.Row self._init_tables(conn, db_type) self._db_connections[db_path] = conn return self._db_connections[db_path] # ======================================== # StorageBackend 接口实现(委托给 mixin) # ======================================== def save_news_data(self, data: NewsData) -> bool: db_path = self._get_db_path(data.date) if not db_path.exists(): # 确保目录存在 db_path.parent.mkdir(parents=True, exist_ok=True) success, new_count, updated_count, title_changed_count, off_list_count = \ self._save_news_data_impl(data, "[本地存储]") if success: # 输出详细的存储统计日志 log_parts = [f"[本地存储] 处理完成:新增 {new_count} 条"] if updated_count > 0: log_parts.append(f"更新 {updated_count} 条") if title_changed_count > 0: log_parts.append(f"标题变更 {title_changed_count} 条") if off_list_count > 0: log_parts.append(f"脱榜 {off_list_count} 条") print(",".join(log_parts)) return success def get_today_all_data(self, date: Optional[str] = None) -> Optional[NewsData]: db_path = self._get_db_path(date) if not db_path.exists(): return None return self._get_today_all_data_impl(date) def get_latest_crawl_data(self, date: Optional[str] = None) -> Optional[NewsData]: db_path = self._get_db_path(date) if not db_path.exists(): return None return self._get_latest_crawl_data_impl(date) def detect_new_titles(self, current_data: NewsData) -> Dict[str, Dict]: return self._detect_new_titles_impl(current_data) def is_first_crawl_today(self, date: Optional[str] = None) -> bool: db_path = self._get_db_path(date) if not db_path.exists(): return True return self._is_first_crawl_today_impl(date) def get_crawl_times(self, date: Optional[str] = None) -> List[str]: db_path = self._get_db_path(date) if not db_path.exists(): return [] return self._get_crawl_times_impl(date) # ======================================== # 时间段执行记录(调度系统) # ======================================== def has_period_executed(self, date_str: str, period_key: str, action: str) -> bool: return self._has_period_executed_impl(date_str, period_key, action) def record_period_execution(self, date_str: str, period_key: str, action: str) -> bool: success = self._record_period_execution_impl(date_str, period_key, action) if success: now_str = self._get_configured_time().strftime("%Y-%m-%d %H:%M:%S") print(f"[本地存储] 时间段执行记录已保存: {period_key}/{action} at {now_str}") return success # ======================================== # RSS 数据存储方法 # ======================================== def save_rss_data(self, data: RSSData) -> bool: success, new_count, updated_count = self._save_rss_data_impl(data, "[本地存储]") if success: # 输出统计日志 log_parts = [f"[本地存储] RSS 处理完成:新增 {new_count} 条"] if updated_count > 0: log_parts.append(f"更新 {updated_count} 条") print(",".join(log_parts)) return success def get_rss_data(self, date: Optional[str] = None) -> Optional[RSSData]: return self._get_rss_data_impl(date) def detect_new_rss_items(self, current_data: RSSData) -> Dict[str, List[RSSItem]]: return self._detect_new_rss_items_impl(current_data) def get_latest_rss_data(self, date: Optional[str] = None) -> Optional[RSSData]: db_path = self._get_db_path(date, db_type="rss") if not db_path.exists(): return None return self._get_latest_rss_data_impl(date) # ======================================== # AI 智能筛选 # ======================================== def get_active_ai_filter_tags(self, date=None, interests_file="ai_interests.txt"): return self._get_active_tags_impl(date, interests_file) def get_latest_prompt_hash(self, date=None, interests_file="ai_interests.txt"): return self._get_latest_prompt_hash_impl(date, interests_file) def get_latest_ai_filter_tag_version(self, date=None): return self._get_latest_tag_version_impl(date) def deprecate_all_ai_filter_tags(self, date=None, interests_file="ai_interests.txt"): return self._deprecate_all_tags_impl(date, interests_file) def save_ai_filter_tags(self, tags, version, prompt_hash, date=None, interests_file="ai_interests.txt"): return self._save_tags_impl(date, tags, version, prompt_hash, interests_file) def save_ai_filter_results(self, results, date=None): return self._save_filter_results_impl(date, results) def get_active_ai_filter_results(self, date=None, interests_file="ai_interests.txt"): return self._get_active_filter_results_impl(date, interests_file) def deprecate_specific_ai_filter_tags(self, tag_ids, date=None): return self._deprecate_specific_tags_impl(date, tag_ids) def update_ai_filter_tags_hash(self, interests_file, new_hash, date=None): return self._update_tags_hash_impl(date, interests_file, new_hash) def update_ai_filter_tag_descriptions(self, tag_updates, date=None, interests_file="ai_interests.txt"): return self._update_tag_descriptions_impl(date, tag_updates, interests_file) def update_ai_filter_tag_priorities(self, tag_priorities, date=None, interests_file="ai_interests.txt"): return self._update_tag_priorities_impl(date, tag_priorities, interests_file) def save_analyzed_news(self, news_ids, source_type, interests_file, prompt_hash, matched_ids, date=None): return self._save_analyzed_news_impl(date, news_ids, source_type, interests_file, prompt_hash, matched_ids) def get_analyzed_news_ids(self, source_type="hotlist", date=None, interests_file="ai_interests.txt"): return self._get_analyzed_news_ids_impl(date, source_type, interests_file) def clear_analyzed_news(self, date=None, interests_file="ai_interests.txt"): return self._clear_analyzed_news_impl(date, interests_file) def clear_unmatched_analyzed_news(self, date=None, interests_file="ai_interests.txt"): return self._clear_unmatched_analyzed_news_impl(date, interests_file) def get_all_news_ids(self, date=None): return self._get_all_news_ids_impl(date) def get_all_rss_ids(self, date=None): return self._get_all_rss_ids_impl(date) # ======================================== # 本地特有功能:TXT/HTML 快照 # ======================================== def save_txt_snapshot(self, data: NewsData) -> Optional[str]: if not self.enable_txt: return None try: date_folder = self._format_date_folder(data.date) txt_dir = self.data_dir / "txt" / date_folder txt_dir.mkdir(parents=True, exist_ok=True) file_path = txt_dir / f"{data.crawl_time}.txt" with open(file_path, "w", encoding="utf-8") as f: for source_id, news_list in data.items.items(): source_name = data.id_to_name.get(source_id, source_id) # 写入来源标题 if source_name and source_name != source_id: f.write(f"{source_id} | {source_name}\n") else: f.write(f"{source_id}\n") # 按排名排序 sorted_news = sorted(news_list, key=lambda x: x.rank) for item in sorted_news: line = f"{item.rank}. {item.title}" if item.url: line += f" [URL:{item.url}]" if item.mobile_url: line += f" [MOBILE:{item.mobile_url}]" f.write(line + "\n") f.write("\n") # 写入失败的来源 if data.failed_ids: f.write("==== 以下ID请求失败 ====\n") for failed_id in data.failed_ids: f.write(f"{failed_id}\n") print(f"[本地存储] TXT 快照已保存: {file_path}") return str(file_path) except Exception as e: print(f"[本地存储] 保存 TXT 快照失败: {e}") return None def save_html_report(self, html_content: str, filename: str) -> Optional[str]: if not self.enable_html: return None try: date_folder = self._format_date_folder() html_dir = self.data_dir / "html" / date_folder html_dir.mkdir(parents=True, exist_ok=True) file_path = html_dir / filename with open(file_path, "w", encoding="utf-8") as f: f.write(html_content) print(f"[本地存储] HTML 报告已保存: {file_path}") return str(file_path) except Exception as e: print(f"[本地存储] 保存 HTML 报告失败: {e}") return None # ======================================== # 本地特有功能:资源清理 # ======================================== def cleanup(self) -> None: for db_path, conn in self._db_connections.items(): try: conn.close() print(f"[本地存储] 关闭数据库连接: {db_path}") except Exception as e: print(f"[本地存储] 关闭连接失败 {db_path}: {e}") self._db_connections.clear() def cleanup_old_data(self, retention_days: int) -> int: if retention_days <= 0: return 0 deleted_count = 0 cutoff_date = self._get_configured_time() - timedelta(days=retention_days) def parse_date_from_name(name: str) -> Optional[datetime]: # 移除 .db 后缀 name = name.replace('.db', '') try: date_match = re.match(r'(\d{4})-(\d{2})-(\d{2})', name) if date_match: return datetime( int(date_match.group(1)), int(date_match.group(2)), int(date_match.group(3)), tzinfo=pytz.timezone(self.timezone) ) except Exception: pass return None try: if not self.data_dir.exists(): return 0 # 清理数据库文件 (news/, rss/) for db_type in ["news", "rss"]: db_dir = self.data_dir / db_type if not db_dir.exists(): continue for db_file in db_dir.glob("*.db"): file_date = parse_date_from_name(db_file.name) if file_date and file_date < cutoff_date: # 先关闭数据库连接 db_path = str(db_file) if db_path in self._db_connections: try: self._db_connections[db_path].close() del self._db_connections[db_path] except Exception: pass # 删除文件 try: db_file.unlink() deleted_count += 1 print(f"[本地存储] 清理过期数据: {db_type}/{db_file.name}") except Exception as e: print(f"[本地存储] 删除文件失败 {db_file}: {e}") # 清理快照目录 (txt/, html/) for snapshot_type in ["txt", "html"]: snapshot_dir = self.data_dir / snapshot_type if not snapshot_dir.exists(): continue for date_folder in snapshot_dir.iterdir(): if not date_folder.is_dir() or date_folder.name.startswith('.'): continue folder_date = parse_date_from_name(date_folder.name) if folder_date and folder_date < cutoff_date: try: shutil.rmtree(date_folder) deleted_count += 1 print(f"[本地存储] 清理过期数据: {snapshot_type}/{date_folder.name}") except Exception as e: print(f"[本地存储] 删除目录失败 {date_folder}: {e}") if deleted_count > 0: print(f"[本地存储] 共清理 {deleted_count} 个过期文件/目录") return deleted_count except Exception as e: print(f"[本地存储] 清理过期数据失败: {e}") return deleted_count def __del__(self): self.cleanup()
--- +++ @@ -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 数据库文件 + - 可选的 TXT 快照(用于调试) + - HTML 报告生成 + """ def __init__( self, @@ -27,6 +40,15 @@ enable_html: bool = True, timezone: str = DEFAULT_TIMEZONE, ): + """ + 初始化本地存储后端 + + Args: + data_dir: 数据目录路径 + enable_txt: 是否启用 TXT 快照 + enable_html: 是否启用 HTML 报告 + timezone: 时区配置 + """ self.data_dir = Path(data_dir) self.enable_txt = enable_txt self.enable_html = enable_html @@ -46,21 +68,48 @@ # ======================================== def _get_configured_time(self) -> datetime: + """获取配置时区的当前时间""" return get_configured_time(self.timezone) def _format_date_folder(self, date: Optional[str] = None) -> str: + """格式化日期文件夹名 (ISO 格式: YYYY-MM-DD)""" return format_date_folder(date, self.timezone) def _format_time_filename(self) -> str: + """格式化时间文件名 (格式: HH-MM)""" return format_time_filename(self.timezone) def _get_db_path(self, date: Optional[str] = None, db_type: str = "news") -> Path: + """ + 获取 SQLite 数据库路径 + + 新结构(扁平):output/{type}/{date}.db + - output/news/2025-12-28.db + - output/rss/2025-12-28.db + + Args: + date: 日期字符串 + db_type: 数据库类型 ("news" 或 "rss") + + Returns: + 数据库文件路径 + """ date_str = self._format_date_folder(date) db_dir = self.data_dir / db_type db_dir.mkdir(parents=True, exist_ok=True) return db_dir / f"{date_str}.db" def _get_connection(self, date: Optional[str] = None, db_type: str = "news") -> sqlite3.Connection: + """ + 获取数据库连接(带缓存) + + Args: + date: 日期字符串 + db_type: 数据库类型 ("news" 或 "rss") + + Returns: + 数据库连接 + """ db_path = str(self._get_db_path(date, db_type)) if db_path not in self._db_connections: @@ -76,6 +125,7 @@ # ======================================== def save_news_data(self, data: NewsData) -> bool: + """保存新闻数据到 SQLite""" db_path = self._get_db_path(data.date) if not db_path.exists(): # 确保目录存在 @@ -98,27 +148,32 @@ return success def get_today_all_data(self, date: Optional[str] = None) -> Optional[NewsData]: + """获取指定日期的所有新闻数据(合并后)""" db_path = self._get_db_path(date) if not db_path.exists(): return None return self._get_today_all_data_impl(date) def get_latest_crawl_data(self, date: Optional[str] = None) -> Optional[NewsData]: + """获取最新一次抓取的数据""" db_path = self._get_db_path(date) if not db_path.exists(): return None return self._get_latest_crawl_data_impl(date) def detect_new_titles(self, current_data: NewsData) -> Dict[str, Dict]: + """检测新增的标题""" return self._detect_new_titles_impl(current_data) def is_first_crawl_today(self, date: Optional[str] = None) -> bool: + """检查是否是当天第一次抓取""" db_path = self._get_db_path(date) if not db_path.exists(): return True return self._is_first_crawl_today_impl(date) def get_crawl_times(self, date: Optional[str] = None) -> List[str]: + """获取指定日期的所有抓取时间列表""" db_path = self._get_db_path(date) if not db_path.exists(): return [] @@ -129,9 +184,11 @@ # ======================================== def has_period_executed(self, date_str: str, period_key: str, action: str) -> bool: + """检查指定时间段的某个 action 是否已执行""" return self._has_period_executed_impl(date_str, period_key, action) def record_period_execution(self, date_str: str, period_key: str, action: str) -> bool: + """记录时间段的 action 执行""" success = self._record_period_execution_impl(date_str, period_key, action) if success: now_str = self._get_configured_time().strftime("%Y-%m-%d %H:%M:%S") @@ -143,6 +200,7 @@ # ======================================== def save_rss_data(self, data: RSSData) -> bool: + """保存 RSS 数据到 SQLite""" success, new_count, updated_count = self._save_rss_data_impl(data, "[本地存储]") if success: @@ -155,12 +213,15 @@ return success def get_rss_data(self, date: Optional[str] = None) -> Optional[RSSData]: + """获取指定日期的所有 RSS 数据""" return self._get_rss_data_impl(date) def detect_new_rss_items(self, current_data: RSSData) -> Dict[str, List[RSSItem]]: + """检测新增的 RSS 条目""" return self._detect_new_rss_items_impl(current_data) def get_latest_rss_data(self, date: Optional[str] = None) -> Optional[RSSData]: + """获取最新一次抓取的 RSS 数据""" db_path = self._get_db_path(date, db_type="rss") if not db_path.exists(): return None @@ -226,6 +287,17 @@ # ======================================== def save_txt_snapshot(self, data: NewsData) -> Optional[str]: + """ + 保存 TXT 快照 + + 新结构:output/txt/{date}/{time}.txt + + Args: + data: 新闻数据 + + Returns: + 保存的文件路径 + """ if not self.enable_txt: return None @@ -273,6 +345,18 @@ return None def save_html_report(self, html_content: str, filename: str) -> Optional[str]: + """ + 保存 HTML 报告 + + 新结构:output/html/{date}/{filename} + + Args: + html_content: HTML 内容 + filename: 文件名 + + Returns: + 保存的文件路径 + """ if not self.enable_html: return None @@ -298,6 +382,7 @@ # ======================================== def cleanup(self) -> None: + """清理资源(关闭数据库连接)""" for db_path, conn in self._db_connections.items(): try: conn.close() @@ -308,6 +393,21 @@ self._db_connections.clear() def cleanup_old_data(self, retention_days: int) -> int: + """ + 清理过期数据 + + 新结构清理逻辑: + - output/news/{date}.db -> 删除过期的 .db 文件 + - output/rss/{date}.db -> 删除过期的 .db 文件 + - output/txt/{date}/ -> 删除过期的日期目录 + - output/html/{date}/ -> 删除过期的日期目录 + + Args: + retention_days: 保留天数(0 表示不清理) + + Returns: + 删除的文件/目录数量 + """ if retention_days <= 0: return 0 @@ -315,6 +415,7 @@ cutoff_date = self._get_configured_time() - timedelta(days=retention_days) def parse_date_from_name(name: str) -> Optional[datetime]: + """从文件名或目录名解析日期 (ISO 格式: YYYY-MM-DD)""" # 移除 .db 后缀 name = name.replace('.db', '') try: @@ -389,4 +490,5 @@ return deleted_count def __del__(self): - self.cleanup()+ """析构函数,确保关闭连接""" + self.cleanup()
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: Dict, total_titles: int, mode: str = "daily", update_info: Optional[Dict] = None, *, region_order: Optional[List[str]] = None, get_time_func: Optional[Callable[[], datetime]] = None, rss_items: Optional[List[Dict]] = None, rss_new_items: Optional[List[Dict]] = None, display_mode: str = "keyword", standalone_data: Optional[Dict] = None, ai_analysis: Optional[Any] = None, show_new_section: bool = True, ) -> str: # 默认区域顺序 default_region_order = ["hotlist", "rss", "new_items", "standalone", "ai_analysis"] if region_order is None: region_order = default_region_order html = """ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>热点新闻分析</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js" integrity="sha512-BNaRQnYJYiPSqHHDb58B0yaPfCu+Wgds8Gp/gU33kqBtgNS4tSPHuGibyoeqMV/TJlSKda6FXzoEyYGjTe+vXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <style> * { box-sizing: border-box; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif; margin: 0; padding: 16px; background: #fafafa; color: #333; line-height: 1.5; } .container { max-width: 600px; margin: 0 auto; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 16px rgba(0,0,0,0.06); } .header { background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%); color: white; padding: 32px 24px; text-align: center; position: relative; } .save-buttons { position: absolute; top: 16px; right: 16px; display: flex; gap: 8px; } .save-btn { background: rgba(255, 255, 255, 0.2); border: 1px solid rgba(255, 255, 255, 0.3); color: white; padding: 8px 16px; border-radius: 6px; cursor: pointer; font-size: 13px; font-weight: 500; transition: all 0.2s ease; backdrop-filter: blur(10px); white-space: nowrap; } .save-btn:hover { background: rgba(255, 255, 255, 0.3); border-color: rgba(255, 255, 255, 0.5); transform: translateY(-1px); } .save-btn:active { transform: translateY(0); } .save-btn:disabled { opacity: 0.6; cursor: not-allowed; } .header-title { font-size: 22px; font-weight: 700; margin: 0 0 20px 0; } .header-info { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; font-size: 14px; opacity: 0.95; } .info-item { text-align: center; } .info-label { display: block; font-size: 12px; opacity: 0.8; margin-bottom: 4px; } .info-value { font-weight: 600; font-size: 16px; } .content { padding: 24px; } .word-group { margin-bottom: 40px; } .word-group:first-child { margin-top: 0; } .word-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; padding-bottom: 8px; border-bottom: 1px solid #f0f0f0; } .word-info { display: flex; align-items: center; gap: 12px; } .word-name { font-size: 17px; font-weight: 600; color: #1a1a1a; } .word-count { color: #666; font-size: 13px; font-weight: 500; } .word-count.hot { color: #dc2626; font-weight: 600; } .word-count.warm { color: #ea580c; font-weight: 600; } .word-index { color: #999; font-size: 12px; } .news-item { margin-bottom: 20px; padding: 16px 0; border-bottom: 1px solid #f5f5f5; position: relative; display: flex; gap: 12px; align-items: center; } .news-item:last-child { border-bottom: none; } .news-item.new::after { content: "NEW"; position: absolute; top: 12px; right: 0; background: #fbbf24; color: #92400e; font-size: 9px; font-weight: 700; padding: 3px 6px; border-radius: 4px; letter-spacing: 0.5px; } .news-number { color: #999; font-size: 13px; font-weight: 600; min-width: 20px; text-align: center; flex-shrink: 0; background: #f8f9fa; border-radius: 50%; width: 24px; height: 24px; display: flex; align-items: center; justify-content: center; align-self: flex-start; margin-top: 8px; } .news-content { flex: 1; min-width: 0; padding-right: 40px; } .news-item.new .news-content { padding-right: 50px; } .news-header { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; flex-wrap: wrap; } .source-name { color: #666; font-size: 12px; font-weight: 500; } .keyword-tag { color: #2563eb; font-size: 12px; font-weight: 500; background: #eff6ff; padding: 2px 6px; border-radius: 4px; } .rank-num { color: #fff; background: #6b7280; font-size: 10px; font-weight: 700; padding: 2px 6px; border-radius: 10px; min-width: 18px; text-align: center; } .rank-num.top { background: #dc2626; } .rank-num.high { background: #ea580c; } .time-info { color: #999; font-size: 11px; } .count-info { color: #059669; font-size: 11px; font-weight: 500; } .news-title { font-size: 15px; line-height: 1.4; color: #1a1a1a; margin: 0; } .news-link { color: #2563eb; text-decoration: none; } .news-link:hover { text-decoration: underline; } .news-link:visited { color: #7c3aed; } /* 通用区域分割线样式 */ .section-divider { margin-top: 32px; padding-top: 24px; border-top: 2px solid #e5e7eb; } /* 热榜统计区样式 */ .hotlist-section { /* 默认无边框,由 section-divider 动态添加 */ } .new-section { margin-top: 40px; padding-top: 24px; } .new-section-title { color: #1a1a1a; font-size: 16px; font-weight: 600; margin: 0 0 20px 0; } .new-source-group { margin-bottom: 24px; } .new-source-title { color: #666; font-size: 13px; font-weight: 500; margin: 0 0 12px 0; padding-bottom: 6px; border-bottom: 1px solid #f5f5f5; } .new-item { display: flex; align-items: center; gap: 12px; padding: 8px 0; border-bottom: 1px solid #f9f9f9; } .new-item:last-child { border-bottom: none; } .new-item-number { color: #999; font-size: 12px; font-weight: 600; min-width: 18px; text-align: center; flex-shrink: 0; background: #f8f9fa; border-radius: 50%; width: 20px; height: 20px; display: flex; align-items: center; justify-content: center; } .new-item-rank { color: #fff; background: #6b7280; font-size: 10px; font-weight: 700; padding: 3px 6px; border-radius: 8px; min-width: 20px; text-align: center; flex-shrink: 0; } .new-item-rank.top { background: #dc2626; } .new-item-rank.high { background: #ea580c; } .new-item-content { flex: 1; min-width: 0; } .new-item-title { font-size: 14px; line-height: 1.4; color: #1a1a1a; margin: 0; } .error-section { background: #fef2f2; border: 1px solid #fecaca; border-radius: 8px; padding: 16px; margin-bottom: 24px; } .error-title { color: #dc2626; font-size: 14px; font-weight: 600; margin: 0 0 8px 0; } .error-list { list-style: none; padding: 0; margin: 0; } .error-item { color: #991b1b; font-size: 13px; padding: 2px 0; font-family: 'SF Mono', Consolas, monospace; } .footer { margin-top: 32px; padding: 20px 24px; background: #f8f9fa; border-top: 1px solid #e5e7eb; text-align: center; } .footer-content { font-size: 13px; color: #6b7280; line-height: 1.6; } .footer-link { color: #4f46e5; text-decoration: none; font-weight: 500; transition: color 0.2s ease; } .footer-link:hover { color: #7c3aed; text-decoration: underline; } .project-name { font-weight: 600; color: #374151; } @media (max-width: 480px) { body { padding: 12px; } .header { padding: 24px 20px; } .content { padding: 20px; } .footer { padding: 16px 20px; } .header-info { grid-template-columns: 1fr; gap: 12px; } .news-header { gap: 6px; } .news-content { padding-right: 45px; } .news-item { gap: 8px; } .new-item { gap: 8px; } .news-number { width: 20px; height: 20px; font-size: 12px; } .save-buttons { position: static; margin-bottom: 16px; display: flex; gap: 8px; justify-content: center; flex-direction: column; width: 100%; } .save-btn { width: 100%; } } /* RSS 订阅内容样式 */ .rss-section { margin-top: 32px; padding-top: 24px; } .rss-section-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; } .rss-section-title { font-size: 18px; font-weight: 600; color: #059669; } .rss-section-count { color: #6b7280; font-size: 14px; } .feed-group { margin-bottom: 24px; } .feed-group:last-child { margin-bottom: 0; } .feed-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; padding-bottom: 8px; border-bottom: 2px solid #10b981; } .feed-name { font-size: 15px; font-weight: 600; color: #059669; } .feed-count { color: #666; font-size: 13px; font-weight: 500; } .rss-item { margin-bottom: 12px; padding: 14px; background: #f0fdf4; border-radius: 8px; border-left: 3px solid #10b981; } .rss-item:last-child { margin-bottom: 0; } .rss-meta { display: flex; align-items: center; gap: 12px; margin-bottom: 6px; flex-wrap: wrap; } .rss-time { color: #6b7280; font-size: 12px; } .rss-author { color: #059669; font-size: 12px; font-weight: 500; } .rss-title { font-size: 14px; line-height: 1.5; margin-bottom: 6px; } .rss-link { color: #1f2937; text-decoration: none; font-weight: 500; } .rss-link:hover { color: #059669; text-decoration: underline; } .rss-summary { font-size: 13px; color: #6b7280; line-height: 1.5; margin: 0; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } /* 独立展示区样式 - 复用热点词汇统计区样式 */ .standalone-section { margin-top: 32px; padding-top: 24px; } .standalone-section-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; } .standalone-section-title { font-size: 18px; font-weight: 600; color: #059669; } .standalone-section-count { color: #6b7280; font-size: 14px; } .standalone-group { margin-bottom: 40px; } .standalone-group:last-child { margin-bottom: 0; } .standalone-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; padding-bottom: 8px; border-bottom: 1px solid #f0f0f0; } .standalone-name { font-size: 17px; font-weight: 600; color: #1a1a1a; } .standalone-count { color: #666; font-size: 13px; font-weight: 500; } /* AI 分析区块样式 */ .ai-section { margin-top: 32px; padding: 24px; background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%); border-radius: 12px; border: 1px solid #bae6fd; } .ai-section-header { display: flex; align-items: center; gap: 10px; margin-bottom: 20px; } .ai-section-title { font-size: 18px; font-weight: 600; color: #0369a1; } .ai-section-badge { background: #0ea5e9; color: white; font-size: 11px; font-weight: 600; padding: 3px 8px; border-radius: 4px; } .ai-block { margin-bottom: 16px; padding: 16px; background: white; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); } .ai-block:last-child { margin-bottom: 0; } .ai-block-title { font-size: 14px; font-weight: 600; color: #0369a1; margin-bottom: 8px; } .ai-block-content { font-size: 14px; line-height: 1.6; color: #334155; white-space: pre-wrap; } .ai-error { padding: 16px; background: #fef2f2; border: 1px solid #fecaca; border-radius: 8px; color: #991b1b; font-size: 14px; } </style> </head> <body> <div class="container"> <div class="header"> <div class="save-buttons"> <button class="save-btn" onclick="saveAsImage()">保存为图片</button> <button class="save-btn" onclick="saveAsMultipleImages()">分段保存</button> </div> <div class="header-title">热点新闻分析</div> <div class="header-info"> <div class="info-item"> <span class="info-label">报告类型</span> <span class="info-value">""" # 处理报告类型显示(根据 mode 直接显示) if mode == "current": html += "当前榜单" elif mode == "incremental": html += "增量分析" else: html += "全天汇总" html += """</span> </div> <div class="info-item"> <span class="info-label">新闻总数</span> <span class="info-value">""" html += f"{total_titles} 条" # 计算筛选后的热点新闻数量 hot_news_count = sum(len(stat["titles"]) for stat in report_data["stats"]) html += """</span> </div> <div class="info-item"> <span class="info-label">热点新闻</span> <span class="info-value">""" html += f"{hot_news_count} 条" html += """</span> </div> <div class="info-item"> <span class="info-label">生成时间</span> <span class="info-value">""" # 使用提供的时间函数或默认 datetime.now if get_time_func: now = get_time_func() else: now = datetime.now() html += now.strftime("%m-%d %H:%M") html += """</span> </div> </div> </div> <div class="content">""" # 处理失败ID错误信息 if report_data["failed_ids"]: html += """ <div class="error-section"> <div class="error-title">⚠️ 请求失败的平台</div> <ul class="error-list">""" for id_value in report_data["failed_ids"]: html += f'<li class="error-item">{html_escape(id_value)}</li>' html += """ </ul> </div>""" # 生成热点词汇统计部分的HTML stats_html = "" if report_data["stats"]: total_count = len(report_data["stats"]) for i, stat in enumerate(report_data["stats"], 1): count = stat["count"] # 确定热度等级 if count >= 10: count_class = "hot" elif count >= 5: count_class = "warm" else: count_class = "" escaped_word = html_escape(stat["word"]) stats_html += f""" <div class="word-group"> <div class="word-header"> <div class="word-info"> <div class="word-name">{escaped_word}</div> <div class="word-count {count_class}">{count} 条</div> </div> <div class="word-index">{i}/{total_count}</div> </div>""" # 处理每个词组下的新闻标题,给每条新闻标上序号 for j, title_data in enumerate(stat["titles"], 1): is_new = title_data.get("is_new", False) new_class = "new" if is_new else "" stats_html += f""" <div class="news-item {new_class}"> <div class="news-number">{j}</div> <div class="news-content"> <div class="news-header">""" # 根据 display_mode 决定显示来源还是关键词 if display_mode == "keyword": # keyword 模式:显示来源 stats_html += f'<span class="source-name">{html_escape(title_data["source_name"])}</span>' else: # platform 模式:显示关键词 matched_keyword = title_data.get("matched_keyword", "") if matched_keyword: stats_html += f'<span class="keyword-tag">[{html_escape(matched_keyword)}]</span>' # 处理排名显示 ranks = title_data.get("ranks", []) if ranks: min_rank = min(ranks) max_rank = max(ranks) rank_threshold = title_data.get("rank_threshold", 10) # 确定排名等级 if min_rank <= 3: rank_class = "top" elif min_rank <= rank_threshold: rank_class = "high" else: rank_class = "" if min_rank == max_rank: rank_text = str(min_rank) else: rank_text = f"{min_rank}-{max_rank}" stats_html += f'<span class="rank-num {rank_class}">{rank_text}</span>' # 处理时间显示 time_display = title_data.get("time_display", "") if time_display: # 简化时间显示格式,将波浪线替换为~ simplified_time = ( time_display.replace(" ~ ", "~") .replace("[", "") .replace("]", "") ) stats_html += ( f'<span class="time-info">{html_escape(simplified_time)}</span>' ) # 处理出现次数 count_info = title_data.get("count", 1) if count_info > 1: stats_html += f'<span class="count-info">{count_info}次</span>' stats_html += """ </div> <div class="news-title">""" # 处理标题和链接 escaped_title = html_escape(title_data["title"]) link_url = title_data.get("mobile_url") or title_data.get("url", "") if link_url: escaped_url = html_escape(link_url) stats_html += f'<a href="{escaped_url}" target="_blank" class="news-link">{escaped_title}</a>' else: stats_html += escaped_title stats_html += """ </div> </div> </div>""" stats_html += """ </div>""" # 给热榜统计添加外层包装 if stats_html: stats_html = f""" <div class="hotlist-section">{stats_html} </div>""" # 生成新增新闻区域的HTML new_titles_html = "" if show_new_section and report_data["new_titles"]: new_titles_html += f""" <div class="new-section"> <div class="new-section-title">本次新增热点 (共 {report_data['total_new_count']} 条)</div>""" for source_data in report_data["new_titles"]: escaped_source = html_escape(source_data["source_name"]) titles_count = len(source_data["titles"]) new_titles_html += f""" <div class="new-source-group"> <div class="new-source-title">{escaped_source} · {titles_count}条</div>""" # 为新增新闻也添加序号 for idx, title_data in enumerate(source_data["titles"], 1): ranks = title_data.get("ranks", []) # 处理新增新闻的排名显示 rank_class = "" if ranks: min_rank = min(ranks) if min_rank <= 3: rank_class = "top" elif min_rank <= title_data.get("rank_threshold", 10): rank_class = "high" if len(ranks) == 1: rank_text = str(ranks[0]) else: rank_text = f"{min(ranks)}-{max(ranks)}" else: rank_text = "?" new_titles_html += f""" <div class="new-item"> <div class="new-item-number">{idx}</div> <div class="new-item-rank {rank_class}">{rank_text}</div> <div class="new-item-content"> <div class="new-item-title">""" # 处理新增新闻的链接 escaped_title = html_escape(title_data["title"]) link_url = title_data.get("mobile_url") or title_data.get("url", "") if link_url: escaped_url = html_escape(link_url) new_titles_html += f'<a href="{escaped_url}" target="_blank" class="news-link">{escaped_title}</a>' else: new_titles_html += escaped_title new_titles_html += """ </div> </div> </div>""" new_titles_html += """ </div>""" new_titles_html += """ </div>""" # 生成 RSS 统计内容 def render_rss_stats_html(stats: List[Dict], title: str = "RSS 订阅更新") -> str: if not stats: return "" # 计算总条目数 total_count = sum(stat.get("count", 0) for stat in stats) if total_count == 0: return "" rss_html = f""" <div class="rss-section"> <div class="rss-section-header"> <div class="rss-section-title">{title}</div> <div class="rss-section-count">{total_count} 条</div> </div>""" # 按关键词分组渲染(与热榜格式一致) for stat in stats: keyword = stat.get("word", "") titles = stat.get("titles", []) if not titles: continue keyword_count = len(titles) rss_html += f""" <div class="feed-group"> <div class="feed-header"> <div class="feed-name">{html_escape(keyword)}</div> <div class="feed-count">{keyword_count} 条</div> </div>""" for title_data in titles: item_title = title_data.get("title", "") url = title_data.get("url", "") time_display = title_data.get("time_display", "") source_name = title_data.get("source_name", "") is_new = title_data.get("is_new", False) rss_html += """ <div class="rss-item"> <div class="rss-meta">""" if time_display: rss_html += f'<span class="rss-time">{html_escape(time_display)}</span>' if source_name: rss_html += f'<span class="rss-author">{html_escape(source_name)}</span>' if is_new: rss_html += '<span class="rss-author" style="color: #dc2626;">NEW</span>' rss_html += """ </div> <div class="rss-title">""" escaped_title = html_escape(item_title) if url: escaped_url = html_escape(url) rss_html += f'<a href="{escaped_url}" target="_blank" class="rss-link">{escaped_title}</a>' else: rss_html += escaped_title rss_html += """ </div> </div>""" rss_html += """ </div>""" rss_html += """ </div>""" return rss_html # 生成独立展示区内容 def render_standalone_html(data: Optional[Dict]) -> str: if not data: return "" platforms = data.get("platforms", []) rss_feeds = data.get("rss_feeds", []) if not platforms and not rss_feeds: return "" # 计算总条目数 total_platform_items = sum(len(p.get("items", [])) for p in platforms) total_rss_items = sum(len(f.get("items", [])) for f in rss_feeds) total_count = total_platform_items + total_rss_items if total_count == 0: return "" standalone_html = f""" <div class="standalone-section"> <div class="standalone-section-header"> <div class="standalone-section-title">独立展示区</div> <div class="standalone-section-count">{total_count} 条</div> </div>""" # 渲染热榜平台(复用 word-group 结构) for platform in platforms: platform_name = platform.get("name", platform.get("id", "")) items = platform.get("items", []) if not items: continue standalone_html += f""" <div class="standalone-group"> <div class="standalone-header"> <div class="standalone-name">{html_escape(platform_name)}</div> <div class="standalone-count">{len(items)} 条</div> </div>""" # 渲染每个条目(复用 news-item 结构) for j, item in enumerate(items, 1): title = item.get("title", "") url = item.get("url", "") or item.get("mobileUrl", "") rank = item.get("rank", 0) ranks = item.get("ranks", []) first_time = item.get("first_time", "") last_time = item.get("last_time", "") count = item.get("count", 1) standalone_html += f""" <div class="news-item"> <div class="news-number">{j}</div> <div class="news-content"> <div class="news-header">""" # 排名显示(复用 rank-num 样式,无 # 前缀) if ranks: min_rank = min(ranks) max_rank = max(ranks) # 确定排名等级 if min_rank <= 3: rank_class = "top" elif min_rank <= 10: rank_class = "high" else: rank_class = "" if min_rank == max_rank: rank_text = str(min_rank) else: rank_text = f"{min_rank}-{max_rank}" standalone_html += f'<span class="rank-num {rank_class}">{rank_text}</span>' elif rank > 0: if rank <= 3: rank_class = "top" elif rank <= 10: rank_class = "high" else: rank_class = "" standalone_html += f'<span class="rank-num {rank_class}">{rank}</span>' # 时间显示(复用 time-info 样式,将 HH-MM 转换为 HH:MM) if first_time and last_time and first_time != last_time: first_time_display = convert_time_for_display(first_time) last_time_display = convert_time_for_display(last_time) standalone_html += f'<span class="time-info">{html_escape(first_time_display)}~{html_escape(last_time_display)}</span>' elif first_time: first_time_display = convert_time_for_display(first_time) standalone_html += f'<span class="time-info">{html_escape(first_time_display)}</span>' # 出现次数(复用 count-info 样式) if count > 1: standalone_html += f'<span class="count-info">{count}次</span>' standalone_html += """ </div> <div class="news-title">""" # 标题和链接(复用 news-link 样式) escaped_title = html_escape(title) if url: escaped_url = html_escape(url) standalone_html += f'<a href="{escaped_url}" target="_blank" class="news-link">{escaped_title}</a>' else: standalone_html += escaped_title standalone_html += """ </div> </div> </div>""" standalone_html += """ </div>""" # 渲染 RSS 源(复用相同结构) for feed in rss_feeds: feed_name = feed.get("name", feed.get("id", "")) items = feed.get("items", []) if not items: continue standalone_html += f""" <div class="standalone-group"> <div class="standalone-header"> <div class="standalone-name">{html_escape(feed_name)}</div> <div class="standalone-count">{len(items)} 条</div> </div>""" for j, item in enumerate(items, 1): title = item.get("title", "") url = item.get("url", "") published_at = item.get("published_at", "") author = item.get("author", "") standalone_html += f""" <div class="news-item"> <div class="news-number">{j}</div> <div class="news-content"> <div class="news-header">""" # 时间显示(格式化 ISO 时间) if published_at: try: from datetime import datetime as dt if "T" in published_at: dt_obj = dt.fromisoformat(published_at.replace("Z", "+00:00")) time_display = dt_obj.strftime("%m-%d %H:%M") else: time_display = published_at except: time_display = published_at standalone_html += f'<span class="time-info">{html_escape(time_display)}</span>' # 作者显示 if author: standalone_html += f'<span class="source-name">{html_escape(author)}</span>' standalone_html += """ </div> <div class="news-title">""" escaped_title = html_escape(title) if url: escaped_url = html_escape(url) standalone_html += f'<a href="{escaped_url}" target="_blank" class="news-link">{escaped_title}</a>' else: standalone_html += escaped_title standalone_html += """ </div> </div> </div>""" standalone_html += """ </div>""" standalone_html += """ </div>""" return standalone_html # 生成 RSS 统计和新增 HTML rss_stats_html = render_rss_stats_html(rss_items, "RSS 订阅更新") if rss_items else "" rss_new_html = render_rss_stats_html(rss_new_items, "RSS 新增更新") if rss_new_items else "" # 生成独立展示区 HTML standalone_html = render_standalone_html(standalone_data) # 生成 AI 分析 HTML ai_html = render_ai_analysis_html_rich(ai_analysis) if ai_analysis else "" # 准备各区域内容映射 region_contents = { "hotlist": stats_html, "rss": rss_stats_html, "new_items": (new_titles_html, rss_new_html), # 元组,分别处理 "standalone": standalone_html, "ai_analysis": ai_html, } def add_section_divider(content: str) -> str: if not content or 'class="' not in content: return content first_class_pos = content.find('class="') if first_class_pos != -1: insert_pos = first_class_pos + len('class="') return content[:insert_pos] + "section-divider " + content[insert_pos:] return content # 按 region_order 顺序组装内容,动态添加分割线 has_previous_content = False for region in region_order: content = region_contents.get(region, "") if region == "new_items": # 特殊处理 new_items 区域(包含热榜新增和 RSS 新增两部分) new_html, rss_new = content if new_html: if has_previous_content: new_html = add_section_divider(new_html) html += new_html has_previous_content = True if rss_new: if has_previous_content: rss_new = add_section_divider(rss_new) html += rss_new has_previous_content = True elif content: if has_previous_content: content = add_section_divider(content) html += content has_previous_content = True html += """ </div> <div class="footer"> <div class="footer-content"> 由 <span class="project-name">TrendRadar</span> 生成 · <a href="https://github.com/sansan0/TrendRadar" target="_blank" class="footer-link"> GitHub 开源项目 </a>""" if update_info: html += f""" <br> <span style="color: #ea580c; font-weight: 500;"> 发现新版本 {update_info['remote_version']},当前版本 {update_info['current_version']} </span>""" html += """ </div> </div> </div> <script> async function saveAsImage() { const button = event.target; const originalText = button.textContent; try { button.textContent = '生成中...'; button.disabled = true; window.scrollTo(0, 0); // 等待页面稳定 await new Promise(resolve => setTimeout(resolve, 200)); // 截图前隐藏按钮 const buttons = document.querySelector('.save-buttons'); buttons.style.visibility = 'hidden'; // 再次等待确保按钮完全隐藏 await new Promise(resolve => setTimeout(resolve, 100)); const container = document.querySelector('.container'); const canvas = await html2canvas(container, { backgroundColor: '#ffffff', scale: 1.5, useCORS: true, allowTaint: false, imageTimeout: 10000, removeContainer: false, foreignObjectRendering: false, logging: false, width: container.offsetWidth, height: container.offsetHeight, x: 0, y: 0, scrollX: 0, scrollY: 0, windowWidth: window.innerWidth, windowHeight: window.innerHeight }); buttons.style.visibility = 'visible'; const link = document.createElement('a'); const now = new Date(); const filename = `TrendRadar_热点新闻分析_${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}_${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}.png`; link.download = filename; link.href = canvas.toDataURL('image/png', 1.0); // 触发下载 document.body.appendChild(link); link.click(); document.body.removeChild(link); button.textContent = '保存成功!'; setTimeout(() => { button.textContent = originalText; button.disabled = false; }, 2000); } catch (error) { const buttons = document.querySelector('.save-buttons'); buttons.style.visibility = 'visible'; button.textContent = '保存失败'; setTimeout(() => { button.textContent = originalText; button.disabled = false; }, 2000); } } async function saveAsMultipleImages() { const button = event.target; const originalText = button.textContent; const container = document.querySelector('.container'); const scale = 1.5; const maxHeight = 5000 / scale; try { button.textContent = '分析中...'; button.disabled = true; // 获取所有可能的分割元素 const newsItems = Array.from(container.querySelectorAll('.news-item')); const wordGroups = Array.from(container.querySelectorAll('.word-group')); const newSection = container.querySelector('.new-section'); const errorSection = container.querySelector('.error-section'); const header = container.querySelector('.header'); const footer = container.querySelector('.footer'); // 计算元素位置和高度 const containerRect = container.getBoundingClientRect(); const elements = []; // 添加header作为必须包含的元素 elements.push({ type: 'header', element: header, top: 0, bottom: header.offsetHeight, height: header.offsetHeight }); // 添加错误信息(如果存在) if (errorSection) { const rect = errorSection.getBoundingClientRect(); elements.push({ type: 'error', element: errorSection, top: rect.top - containerRect.top, bottom: rect.bottom - containerRect.top, height: rect.height }); } // 按word-group分组处理news-item wordGroups.forEach(group => { const groupRect = group.getBoundingClientRect(); const groupNewsItems = group.querySelectorAll('.news-item'); // 添加word-group的header部分 const wordHeader = group.querySelector('.word-header'); if (wordHeader) { const headerRect = wordHeader.getBoundingClientRect(); elements.push({ type: 'word-header', element: wordHeader, parent: group, top: groupRect.top - containerRect.top, bottom: headerRect.bottom - containerRect.top, height: headerRect.height }); } // 添加每个news-item groupNewsItems.forEach(item => { const rect = item.getBoundingClientRect(); elements.push({ type: 'news-item', element: item, parent: group, top: rect.top - containerRect.top, bottom: rect.bottom - containerRect.top, height: rect.height }); }); }); // 添加新增新闻部分 if (newSection) { const rect = newSection.getBoundingClientRect(); elements.push({ type: 'new-section', element: newSection, top: rect.top - containerRect.top, bottom: rect.bottom - containerRect.top, height: rect.height }); } // 添加footer const footerRect = footer.getBoundingClientRect(); elements.push({ type: 'footer', element: footer, top: footerRect.top - containerRect.top, bottom: footerRect.bottom - containerRect.top, height: footer.offsetHeight }); // 计算分割点 const segments = []; let currentSegment = { start: 0, end: 0, height: 0, includeHeader: true }; let headerHeight = header.offsetHeight; currentSegment.height = headerHeight; for (let i = 1; i < elements.length; i++) { const element = elements[i]; const potentialHeight = element.bottom - currentSegment.start; // 检查是否需要创建新分段 if (potentialHeight > maxHeight && currentSegment.height > headerHeight) { // 在前一个元素结束处分割 currentSegment.end = elements[i - 1].bottom; segments.push(currentSegment); // 开始新分段 currentSegment = { start: currentSegment.end, end: 0, height: element.bottom - currentSegment.end, includeHeader: false }; } else { currentSegment.height = potentialHeight; currentSegment.end = element.bottom; } } // 添加最后一个分段 if (currentSegment.height > 0) { currentSegment.end = container.offsetHeight; segments.push(currentSegment); } button.textContent = `生成中 (0/${segments.length})...`; // 隐藏保存按钮 const buttons = document.querySelector('.save-buttons'); buttons.style.visibility = 'hidden'; // 为每个分段生成图片 const images = []; for (let i = 0; i < segments.length; i++) { const segment = segments[i]; button.textContent = `生成中 (${i + 1}/${segments.length})...`; // 创建临时容器用于截图 const tempContainer = document.createElement('div'); tempContainer.style.cssText = ` position: absolute; left: -9999px; top: 0; width: ${container.offsetWidth}px; background: white; `; tempContainer.className = 'container'; // 克隆容器内容 const clonedContainer = container.cloneNode(true); // 移除克隆内容中的保存按钮 const clonedButtons = clonedContainer.querySelector('.save-buttons'); if (clonedButtons) { clonedButtons.style.display = 'none'; } tempContainer.appendChild(clonedContainer); document.body.appendChild(tempContainer); // 等待DOM更新 await new Promise(resolve => setTimeout(resolve, 100)); // 使用html2canvas截取特定区域 const canvas = await html2canvas(clonedContainer, { backgroundColor: '#ffffff', scale: scale, useCORS: true, allowTaint: false, imageTimeout: 10000, logging: false, width: container.offsetWidth, height: segment.end - segment.start, x: 0, y: segment.start, windowWidth: window.innerWidth, windowHeight: window.innerHeight }); images.push(canvas.toDataURL('image/png', 1.0)); // 清理临时容器 document.body.removeChild(tempContainer); } // 恢复按钮显示 buttons.style.visibility = 'visible'; // 下载所有图片 const now = new Date(); const baseFilename = `TrendRadar_热点新闻分析_${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}_${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}`; for (let i = 0; i < images.length; i++) { const link = document.createElement('a'); link.download = `${baseFilename}_part${i + 1}.png`; link.href = images[i]; document.body.appendChild(link); link.click(); document.body.removeChild(link); // 延迟一下避免浏览器阻止多个下载 await new Promise(resolve => setTimeout(resolve, 100)); } button.textContent = `已保存 ${segments.length} 张图片!`; setTimeout(() => { button.textContent = originalText; button.disabled = false; }, 2000); } catch (error) { console.error('分段保存失败:', error); const buttons = document.querySelector('.save-buttons'); buttons.style.visibility = 'visible'; button.textContent = '保存失败'; setTimeout(() => { button.textContent = originalText; button.disabled = false; }, 2000); } } document.addEventListener('DOMContentLoaded', function() { window.scrollTo(0, 0); }); </script> </body> </html> """ return html
--- +++ @@ -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: + report_data: 报告数据字典,包含 stats, new_titles, failed_ids, total_new_count + total_titles: 新闻总数 + mode: 报告模式 ("daily", "current", "incremental") + update_info: 更新信息(可选) + region_order: 区域显示顺序列表 + get_time_func: 获取当前时间的函数(可选,默认使用 datetime.now) + rss_items: RSS 统计条目列表(可选) + rss_new_items: RSS 新增条目列表(可选) + display_mode: 显示模式 ("keyword"=按关键词分组, "platform"=按平台分组) + standalone_data: 独立展示区数据(可选),包含 platforms 和 rss_feeds + ai_analysis: AI 分析结果对象(可选),AIAnalysisResult 实例 + show_new_section: 是否显示新增热点区域 + + Returns: + 渲染后的 HTML 字符串 + """ # 默认区域顺序 default_region_order = ["hotlist", "rss", "new_items", "standalone", "ai_analysis"] if region_order is None: @@ -964,6 +988,30 @@ # 生成 RSS 统计内容 def render_rss_stats_html(stats: List[Dict], title: str = "RSS 订阅更新") -> str: + """渲染 RSS 统计区块 HTML + + Args: + stats: RSS 分组统计列表,格式与热榜一致: + [ + { + "word": "关键词", + "count": 5, + "titles": [ + { + "title": "标题", + "source_name": "Feed 名称", + "time_display": "12-29 08:20", + "url": "...", + "is_new": True/False + } + ] + } + ] + title: 区块标题 + + Returns: + 渲染后的 HTML 字符串 + """ if not stats: return "" @@ -1039,6 +1087,47 @@ # 生成独立展示区内容 def render_standalone_html(data: Optional[Dict]) -> str: + """渲染独立展示区 HTML(复用热点词汇统计区样式) + + Args: + data: 独立展示数据,格式: + { + "platforms": [ + { + "id": "zhihu", + "name": "知乎热榜", + "items": [ + { + "title": "标题", + "url": "链接", + "rank": 1, + "ranks": [1, 2, 1], + "first_time": "08:00", + "last_time": "12:30", + "count": 3, + } + ] + } + ], + "rss_feeds": [ + { + "id": "hacker-news", + "name": "Hacker News", + "items": [ + { + "title": "标题", + "url": "链接", + "published_at": "2025-01-07T08:00:00", + "author": "作者", + } + ] + } + ] + } + + Returns: + 渲染后的 HTML 字符串 + """ if not data: return "" @@ -1241,6 +1330,7 @@ } def add_section_divider(content: str) -> str: + """为内容的外层 div 添加 section-divider 类""" if not content or 'class="' not in content: return content first_class_pos = content.find('class="') @@ -1605,4 +1695,4 @@ </html> """ - return html+ return html
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: str # 当前日计划 collect: bool analyze: bool push: bool report_mode: str ai_mode: str once_analyze: bool once_push: bool frequency_file: Optional[str] = None # 频率词文件路径,None=使用默认 filter_method: Optional[str] = None # 筛选策略: "keyword"|"ai",None=使用全局配置 interests_file: Optional[str] = None # AI 筛选兴趣文件,None=使用默认 class Scheduler: def __init__( self, schedule_config: Dict[str, Any], timeline_data: Dict[str, Any], storage_backend: Any, get_time_func: Callable[[], datetime], fallback_report_mode: str = "current", ): self.schedule_config = schedule_config self.storage = storage_backend self.get_time = get_time_func self.enabled = schedule_config.get("enabled", True) self.fallback_report_mode = fallback_report_mode # 加载并构建最终 timeline self.timeline = self._build_timeline(schedule_config, timeline_data) if self.enabled: self._validate_timeline(self.timeline) def _build_timeline( self, schedule_config: Dict[str, Any], timeline_data: Dict[str, Any], ) -> Dict[str, Any]: preset = schedule_config.get("preset", "always_on") if preset == "custom": timeline = copy.deepcopy(timeline_data.get("custom", {})) else: presets = timeline_data.get("presets", {}) if preset not in presets: raise ValueError( f"未知的预设模板: '{preset}',可选值: " f"{', '.join(presets.keys())}, custom" ) timeline = copy.deepcopy(presets[preset]) # 确保 periods 是 dict(可能为空 {}) if timeline.get("periods") is None: timeline["periods"] = {} return timeline def resolve(self) -> ResolvedSchedule: if not self.enabled: # 调度未启用时返回默认的全功能配置,report_mode 回退使用 config.yaml 的 report.mode return ResolvedSchedule( period_key=None, period_name=None, day_plan="disabled", collect=True, analyze=True, push=True, report_mode=self.fallback_report_mode, ai_mode="follow_report", once_analyze=False, once_push=False, ) now = self.get_time() weekday = now.isoweekday() # 1=周一 ... 7=周日 now_hhmm = now.strftime("%H:%M") # 查找当天的日计划 day_plan_key = self.timeline["week_map"].get(weekday) if day_plan_key is None: raise ValueError(f"week_map 缺少星期映射: {weekday}") day_plan = self.timeline["day_plans"].get(day_plan_key) if day_plan is None: raise ValueError(f"week_map[{weekday}] 引用了不存在的 day_plan: {day_plan_key}") # 查找当前活跃的时间段 period_key = self._find_active_period(now_hhmm, day_plan) # 合并默认配置和时间段配置 merged = self._merge_with_default(period_key) # 打印调度日志 weekday_names = {1: "一", 2: "二", 3: "三", 4: "四", 5: "五", 6: "六", 7: "日"} period_display = "默认配置(未命中任何时间段)" if period_key: period_cfg = self.timeline["periods"][period_key] period_name = period_cfg.get("name", period_key) start = period_cfg.get("start", "?") end = period_cfg.get("end", "?") period_display = f"{period_name} ({start}-{end})" print(f"[调度] 星期{weekday_names.get(weekday, '?')},日计划: {day_plan_key}") print(f"[调度] 当前时间段: {period_display}") resolved = ResolvedSchedule( period_key=period_key, period_name=( self.timeline["periods"][period_key].get("name") if period_key else None ), day_plan=day_plan_key, collect=merged.get("collect", True), analyze=merged.get("analyze", False), push=merged.get("push", False), report_mode=merged.get("report_mode", "current"), ai_mode=self._resolve_ai_mode(merged), once_analyze=merged.get("once", {}).get("analyze", False), once_push=merged.get("once", {}).get("push", False), frequency_file=merged.get("frequency_file"), filter_method=merged.get("filter_method"), interests_file=merged.get("interests_file"), ) # 打印行为摘要 actions = [] if resolved.collect: actions.append("采集") if resolved.analyze: actions.append(f"分析(AI:{resolved.ai_mode})") if resolved.push: actions.append(f"推送(模式:{resolved.report_mode})") print(f"[调度] 行为: {', '.join(actions) if actions else '无'}") if resolved.frequency_file: print(f"[调度] 频率词文件: {resolved.frequency_file}") return resolved def _find_active_period( self, now_hhmm: str, day_plan: Dict[str, Any] ) -> Optional[str]: candidates = [] for idx, key in enumerate(day_plan.get("periods", [])): period = self.timeline["periods"].get(key) if period is None: continue if self._in_range(now_hhmm, period["start"], period["end"]): candidates.append((idx, key)) if not candidates: return None # 检查冲突 if len(candidates) > 1: policy = self.timeline.get("overlap", {}).get("policy", "error_on_overlap") conflicting = [c[1] for c in candidates] if policy == "error_on_overlap": raise ValueError( f"检测到时间段重叠冲突: {', '.join(conflicting)} 在 {now_hhmm} 重叠。" f"请调整时间段配置,或将 overlap.policy 设为 'last_wins'" ) # last_wins:输出重叠警告,列表中后面的优先 print( f"[调度] 检测到时间段重叠: {', '.join(conflicting)} 在 {now_hhmm} 重叠" ) winner = candidates[-1] print(f"[调度] 冲突策略: last_wins,生效时间段: {winner[1]}") return winner[1] return candidates[0][1] @staticmethod def _in_range(now_hhmm: str, start: str, end: str) -> bool: if start <= end: # 正常范围,如 08:00-09:00 return start <= now_hhmm <= end else: # 跨日范围,如 22:00-07:00 return now_hhmm >= start or now_hhmm <= end def _merge_with_default(self, period_key: Optional[str]) -> Dict[str, Any]: base = copy.deepcopy(self.timeline.get("default", {})) if not period_key: return base period = copy.deepcopy(self.timeline["periods"][period_key]) # 先合并 once 子对象 merged_once = dict(base.get("once", {})) merged_once.update(period.get("once", {})) # 标量字段覆盖 base.update(period) # 恢复合并后的 once if merged_once: base["once"] = merged_once return base @staticmethod def _resolve_ai_mode(cfg: Dict[str, Any]) -> str: ai_mode = cfg.get("ai_mode", "follow_report") if ai_mode == "follow_report": return cfg.get("report_mode", "current") return ai_mode def already_executed(self, period_key: str, action: str, date_str: str) -> bool: return self.storage.has_period_executed(date_str, period_key, action) def record_execution(self, period_key: str, action: str, date_str: str) -> None: self.storage.record_period_execution(date_str, period_key, action) # ======================================== # 校验 # ======================================== def _validate_timeline(self, timeline: Dict[str, Any]) -> None: required_top_keys = ["default", "periods", "day_plans", "week_map"] for key in required_top_keys: if key not in timeline: raise ValueError(f"timeline 缺少必须字段: {key}") # week_map 必须覆盖 1..7 for day in range(1, 8): if day not in timeline["week_map"]: raise ValueError(f"week_map 缺少星期映射: {day}") # day_plan 引用完整性 for day, plan_key in timeline["week_map"].items(): if plan_key not in timeline["day_plans"]: raise ValueError( f"week_map[{day}] 引用了不存在的 day_plan: {plan_key}" ) # period 引用完整性 for plan_key, plan in timeline["day_plans"].items(): for period_key in plan.get("periods", []): if period_key not in timeline["periods"]: raise ValueError( f"day_plan[{plan_key}] 引用了不存在的 period: {period_key}" ) # 时间格式校验 for period_key, period in timeline["periods"].items(): if "start" not in period or "end" not in period: raise ValueError( f"period '{period_key}' 缺少 start 或 end 字段" ) self._validate_hhmm(period["start"], f"{period_key}.start") self._validate_hhmm(period["end"], f"{period_key}.end") if period["start"] == period["end"]: raise ValueError( f"period '{period_key}' 的 start 与 end 不能相同: {period['start']}" ) # 检查冲突策略下的重叠 policy = timeline.get("overlap", {}).get("policy", "error_on_overlap") if policy == "error_on_overlap": self._check_period_overlaps(timeline) def _check_period_overlaps(self, timeline: Dict[str, Any]) -> None: periods = timeline.get("periods", {}) for plan_key, plan in timeline["day_plans"].items(): period_keys = plan.get("periods", []) if len(period_keys) <= 1: continue # 收集每个时间段的范围 ranges = [] for pk in period_keys: p = periods.get(pk, {}) if "start" in p and "end" in p: ranges.append((pk, p["start"], p["end"])) # 两两检查重叠 for i in range(len(ranges)): for j in range(i + 1, len(ranges)): if self._ranges_overlap( ranges[i][1], ranges[i][2], ranges[j][1], ranges[j][2], ): raise ValueError( f"day_plan '{plan_key}' 中时间段 '{ranges[i][0]}' " f"({ranges[i][1]}-{ranges[i][2]}) 与 '{ranges[j][0]}' " f"({ranges[j][1]}-{ranges[j][2]}) 存在重叠。" f"请调整时间段,或将 overlap.policy 设为 'last_wins'" ) @staticmethod def _ranges_overlap(s1: str, e1: str, s2: str, e2: str) -> bool: def to_minutes(t: str) -> int: h, m = t.split(":") return int(h) * 60 + int(m) def expand_range(start: str, end: str) -> List[tuple]: s = to_minutes(start) e = to_minutes(end) if s <= e: return [(s, e)] else: # 跨日:拆分为 [start, 23:59] 和 [00:00, end] return [(s, 24 * 60 - 1), (0, e)] segs1 = expand_range(s1, e1) segs2 = expand_range(s2, e2) for a_start, a_end in segs1: for b_start, b_end in segs2: # 两个区间有重叠的条件 if a_start <= b_end and b_start <= a_end: return True return False @staticmethod def _validate_hhmm(value: str, field_name: str) -> None: if not re.match(r"^\d{2}:\d{2}$", value): raise ValueError(f"{field_name} 格式错误: '{value}',期望 HH:MM") h, m = value.split(":") if not (0 <= int(h) <= 23 and 0 <= int(m) <= 59): raise ValueError(f"{field_name} 时间值超出范围: '{value}'")
--- +++ @@ -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,None=默认配置 period_name: Optional[str] # 命中的展示名称 day_plan: str # 当前日计划 @@ -26,6 +33,17 @@ class Scheduler: + """ + 时间线调度器 + + 根据 timeline 配置(periods + day_plans + week_map)解析当前时间应执行的行为。 + 支持: + - 预设模板 + 自定义模式 + - 跨日时间段(如 22:00-07:00) + - 每天 / 每周差异化配置 + - once 执行去重(analyze / push 独立维度) + - 冲突策略(error_on_overlap / last_wins) + """ def __init__( self, @@ -35,6 +53,16 @@ get_time_func: Callable[[], datetime], fallback_report_mode: str = "current", ): + """ + 初始化调度器 + + Args: + schedule_config: config.yaml 中的 schedule 段(含 preset 等) + timeline_data: timeline.yaml 的完整数据 + storage_backend: 存储后端(用于 once 去重记录) + get_time_func: 获取当前时间的函数(应使用配置的时区) + fallback_report_mode: 调度未启用时回退使用的 report_mode(来自 config.yaml 的 report.mode) + """ self.schedule_config = schedule_config self.storage = storage_backend self.get_time = get_time_func @@ -51,6 +79,7 @@ schedule_config: Dict[str, Any], timeline_data: Dict[str, Any], ) -> Dict[str, Any]: + """从 preset 或 custom 构建 timeline""" preset = schedule_config.get("preset", "always_on") if preset == "custom": @@ -71,6 +100,12 @@ return timeline def resolve(self) -> ResolvedSchedule: + """ + 解析当前时间对应的调度配置 + + Returns: + ResolvedSchedule 包含当前应执行的行为 + """ if not self.enabled: # 调度未启用时返回默认的全功能配置,report_mode 回退使用 config.yaml 的 report.mode return ResolvedSchedule( @@ -155,6 +190,16 @@ def _find_active_period( self, now_hhmm: str, day_plan: Dict[str, Any] ) -> Optional[str]: + """ + 查找当前时间命中的活跃时间段 + + Args: + now_hhmm: 当前时间 HH:MM + day_plan: 日计划配置 + + Returns: + 命中的 period key,或 None + """ candidates = [] for idx, key in enumerate(day_plan.get("periods", [])): period = self.timeline["periods"].get(key) @@ -189,6 +234,17 @@ @staticmethod def _in_range(now_hhmm: str, start: str, end: str) -> bool: + """ + 检查时间是否在范围内(支持跨日) + + Args: + now_hhmm: 当前时间 HH:MM + start: 开始时间 HH:MM + end: 结束时间 HH:MM + + Returns: + 是否在范围内 + """ if start <= end: # 正常范围,如 08:00-09:00 return start <= now_hhmm <= end @@ -197,6 +253,7 @@ return now_hhmm >= start or now_hhmm <= end def _merge_with_default(self, period_key: Optional[str]) -> Dict[str, Any]: + """合并默认配置和时间段配置""" base = copy.deepcopy(self.timeline.get("default", {})) if not period_key: return base @@ -218,15 +275,35 @@ @staticmethod def _resolve_ai_mode(cfg: Dict[str, Any]) -> str: + """解析最终的 AI 模式""" ai_mode = cfg.get("ai_mode", "follow_report") if ai_mode == "follow_report": return cfg.get("report_mode", "current") return ai_mode def already_executed(self, period_key: str, action: str, date_str: str) -> bool: + """ + 检查指定时间段的某个 action 今天是否已执行 + + Args: + period_key: 时间段 key + action: 动作类型 (analyze / push) + date_str: 日期 YYYY-MM-DD + + Returns: + 是否已执行 + """ return self.storage.has_period_executed(date_str, period_key, action) def record_execution(self, period_key: str, action: str, date_str: str) -> None: + """ + 记录时间段的 action 执行 + + Args: + period_key: 时间段 key + action: 动作类型 (analyze / push) + date_str: 日期 YYYY-MM-DD + """ self.storage.record_period_execution(date_str, period_key, action) # ======================================== @@ -234,6 +311,12 @@ # ======================================== def _validate_timeline(self, timeline: Dict[str, Any]) -> None: + """ + 启动时校验 timeline 配置 + + Raises: + ValueError: 配置不合法时抛出 + """ required_top_keys = ["default", "periods", "day_plans", "week_map"] for key in required_top_keys: if key not in timeline: @@ -278,6 +361,11 @@ self._check_period_overlaps(timeline) def _check_period_overlaps(self, timeline: Dict[str, Any]) -> None: + """ + 检查每个日计划中的时间段是否存在重叠 + + 仅在 overlap.policy == "error_on_overlap" 时调用 + """ periods = timeline.get("periods", {}) for plan_key, plan in timeline["day_plans"].items(): @@ -308,11 +396,13 @@ @staticmethod def _ranges_overlap(s1: str, e1: str, s2: str, e2: str) -> bool: + """检查两个时间范围是否重叠(支持跨日)""" def to_minutes(t: str) -> int: h, m = t.split(":") return int(h) * 60 + int(m) def expand_range(start: str, end: str) -> List[tuple]: + """将时间范围展开为分钟段列表,跨日时拆分为两段""" s = to_minutes(start) e = to_minutes(end) if s <= e: @@ -333,8 +423,9 @@ @staticmethod def _validate_hhmm(value: str, field_name: str) -> None: + """校验 HH:MM 格式""" if not re.match(r"^\d{2}:\d{2}$", value): raise ValueError(f"{field_name} 格式错误: '{value}',期望 HH:MM") h, m = value.split(":") if not (0 <= int(h) <= 23 and 0 <= int(m) <= 59): - raise ValueError(f"{field_name} 时间值超出范围: '{value}'")+ raise ValueError(f"{field_name} 时间值超出范围: '{value}'")
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 = title_data.get("ranks", []) if not ranks: return 0.0 count = title_data.get("count", len(ranks)) # 排名权重:Σ(11 - min(rank, 10)) / 出现次数 rank_scores = [] for rank in ranks: score = 11 - min(rank, 10) rank_scores.append(score) rank_weight = sum(rank_scores) / len(ranks) if ranks else 0 # 频次权重:min(出现次数, 10) × 10 frequency_weight = min(count, 10) * 10 # 热度加成:高排名次数 / 总出现次数 × 100 high_rank_count = sum(1 for rank in ranks if rank <= rank_threshold) hotness_ratio = high_rank_count / len(ranks) if ranks else 0 hotness_weight = hotness_ratio * 100 total_weight = ( rank_weight * weight_config["RANK_WEIGHT"] + frequency_weight * weight_config["FREQUENCY_WEIGHT"] + hotness_weight * weight_config["HOTNESS_WEIGHT"] ) return total_weight def format_time_display( first_time: str, last_time: str, convert_time_func: Callable[[str], str], ) -> str: if not first_time: return "" # 转换为显示格式 first_display = convert_time_func(first_time) last_display = convert_time_func(last_time) if first_display == last_display or not last_display: return first_display else: return f"[{first_display} ~ {last_display}]" def count_word_frequency( results: Dict, word_groups: List[Dict], filter_words: List[str], id_to_name: Dict, title_info: Optional[Dict] = None, rank_threshold: int = 3, new_titles: Optional[Dict] = None, mode: str = "daily", global_filters: Optional[List[str]] = None, weight_config: Optional[Dict] = None, max_news_per_keyword: int = 0, sort_by_position_first: bool = False, is_first_crawl_func: Optional[Callable[[], bool]] = None, convert_time_func: Optional[Callable[[str], str]] = None, quiet: bool = False, ) -> Tuple[List[Dict], int]: # 默认权重配置 if weight_config is None: weight_config = { "RANK_WEIGHT": 0.4, "FREQUENCY_WEIGHT": 0.3, "HOTNESS_WEIGHT": 0.3, } # 默认时间转换函数 if convert_time_func is None: convert_time_func = lambda x: x # 默认首次爬取检测函数 if is_first_crawl_func is None: is_first_crawl_func = lambda: True # 如果没有配置词组,创建一个包含所有新闻的虚拟词组 if not word_groups: print("频率词配置为空,将显示所有新闻") word_groups = [{"required": [], "normal": [], "group_key": "全部新闻"}] filter_words = [] # 清空过滤词,显示所有新闻 is_first_today = is_first_crawl_func() # 确定处理的数据源和新增标记逻辑 if mode == "incremental": if is_first_today: # 增量模式 + 当天第一次:处理所有新闻,都标记为新增 results_to_process = results all_news_are_new = True else: # 增量模式 + 当天非第一次:只处理新增的新闻 results_to_process = new_titles if new_titles else {} all_news_are_new = True elif mode == "current": # current 模式:只处理当前时间批次的新闻,但统计信息来自全部历史 if title_info: latest_time = None for source_titles in title_info.values(): for title_data in source_titles.values(): last_time = title_data.get("last_time", "") if last_time: if latest_time is None or last_time > latest_time: latest_time = last_time # 只处理 last_time 等于最新时间的新闻 if latest_time: results_to_process = {} for source_id, source_titles in results.items(): if source_id in title_info: filtered_titles = {} for title, title_data in source_titles.items(): if title in title_info[source_id]: info = title_info[source_id][title] if info.get("last_time") == latest_time: filtered_titles[title] = title_data if filtered_titles: results_to_process[source_id] = filtered_titles if not quiet: print( f"当前榜单模式:最新时间 {latest_time},筛选出 {sum(len(titles) for titles in results_to_process.values())} 条当前榜单新闻" ) else: results_to_process = results else: results_to_process = results all_news_are_new = False else: # 当日汇总模式:处理所有新闻 results_to_process = results all_news_are_new = False total_input_news = sum(len(titles) for titles in results.values()) filter_status = ( "全部显示" if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻" else "频率词过滤" ) print(f"当日汇总模式:处理 {total_input_news} 条新闻,模式:{filter_status}") word_stats = {} total_titles = 0 processed_titles = {} matched_new_count = 0 if title_info is None: title_info = {} if new_titles is None: new_titles = {} for group in word_groups: group_key = group["group_key"] word_stats[group_key] = {"count": 0, "titles": {}} for source_id, titles_data in results_to_process.items(): total_titles += len(titles_data) if source_id not in processed_titles: processed_titles[source_id] = {} for title, title_data in titles_data.items(): if title in processed_titles.get(source_id, {}): continue # 使用统一的匹配逻辑 matches_frequency_words = matches_word_groups( title, word_groups, filter_words, global_filters ) if not matches_frequency_words: continue # 如果是增量模式或 current 模式第一次,统计匹配的新增新闻数量 if (mode == "incremental" and all_news_are_new) or ( mode == "current" and is_first_today ): matched_new_count += 1 source_ranks = title_data.get("ranks", []) source_url = title_data.get("url", "") source_mobile_url = title_data.get("mobileUrl", "") # 找到匹配的词组(防御性转换确保类型安全) title_lower = str(title).lower() if not isinstance(title, str) else title.lower() for group in word_groups: required_words = group["required"] normal_words = group["normal"] # 如果是"全部新闻"模式,所有标题都匹配第一个(唯一的)词组 if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻": group_key = group["group_key"] word_stats[group_key]["count"] += 1 if source_id not in word_stats[group_key]["titles"]: word_stats[group_key]["titles"][source_id] = [] else: # 原有的匹配逻辑(支持正则语法) if required_words: all_required_present = all( _word_matches(req_item, title_lower) for req_item in required_words ) if not all_required_present: continue if normal_words: any_normal_present = any( _word_matches(normal_item, title_lower) for normal_item in normal_words ) if not any_normal_present: continue group_key = group["group_key"] word_stats[group_key]["count"] += 1 if source_id not in word_stats[group_key]["titles"]: word_stats[group_key]["titles"][source_id] = [] first_time = "" last_time = "" count_info = 1 ranks = source_ranks if source_ranks else [] url = source_url mobile_url = source_mobile_url rank_timeline = [] # 对于 current 模式,从历史统计信息中获取完整数据 if ( mode == "current" and title_info and source_id in title_info and title in title_info[source_id] ): info = title_info[source_id][title] first_time = info.get("first_time", "") last_time = info.get("last_time", "") count_info = info.get("count", 1) if "ranks" in info and info["ranks"]: ranks = info["ranks"] url = info.get("url", source_url) mobile_url = info.get("mobileUrl", source_mobile_url) rank_timeline = info.get("rank_timeline", []) elif ( title_info and source_id in title_info and title in title_info[source_id] ): info = title_info[source_id][title] first_time = info.get("first_time", "") last_time = info.get("last_time", "") count_info = info.get("count", 1) if "ranks" in info and info["ranks"]: ranks = info["ranks"] url = info.get("url", source_url) mobile_url = info.get("mobileUrl", source_mobile_url) rank_timeline = info.get("rank_timeline", []) if not ranks: ranks = [99] time_display = format_time_display(first_time, last_time, convert_time_func) source_name = id_to_name.get(source_id, source_id) # 判断是否为新增 is_new = False if all_news_are_new: # 增量模式下所有处理的新闻都是新增,或者当天第一次的所有新闻都是新增 is_new = True elif new_titles and source_id in new_titles: # 检查是否在新增列表中 new_titles_for_source = new_titles[source_id] is_new = title in new_titles_for_source word_stats[group_key]["titles"][source_id].append( { "title": title, "source_name": source_name, "first_time": first_time, "last_time": last_time, "time_display": time_display, "count": count_info, "ranks": ranks, "rank_threshold": rank_threshold, "url": url, "mobileUrl": mobile_url, "is_new": is_new, "rank_timeline": rank_timeline, } ) if source_id not in processed_titles: processed_titles[source_id] = {} processed_titles[source_id][title] = True break # 最后统一打印汇总信息 if mode == "incremental": if is_first_today: total_input_news = sum(len(titles) for titles in results.values()) filter_status = ( "全部显示" if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻" else "频率词匹配" ) if not quiet: print( f"增量模式:当天第一次爬取,{total_input_news} 条新闻中有 {matched_new_count} 条{filter_status}" ) else: if new_titles: total_new_count = sum(len(titles) for titles in new_titles.values()) filter_status = ( "全部显示" if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻" else "匹配频率词" ) if not quiet: print( f"增量模式:{total_new_count} 条新增新闻中,有 {matched_new_count} 条{filter_status}" ) if matched_new_count == 0 and len(word_groups) > 1: print("增量模式:没有新增新闻匹配频率词,将不会发送通知") else: if not quiet: print("增量模式:未检测到新增新闻") elif mode == "current": total_input_news = sum(len(titles) for titles in results_to_process.values()) if is_first_today: filter_status = ( "全部显示" if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻" else "频率词匹配" ) if not quiet: print( f"当前榜单模式:当天第一次爬取,{total_input_news} 条当前榜单新闻中有 {matched_new_count} 条{filter_status}" ) else: matched_count = sum(stat["count"] for stat in word_stats.values()) filter_status = ( "全部显示" if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部新闻" else "频率词匹配" ) if not quiet: print( f"当前榜单模式:{total_input_news} 条当前榜单新闻中有 {matched_count} 条{filter_status}" ) stats = [] # 创建 group_key 到位置、最大数量、显示名称的映射 group_key_to_position = { group["group_key"]: idx for idx, group in enumerate(word_groups) } group_key_to_max_count = { group["group_key"]: group.get("max_count", 0) for group in word_groups } group_key_to_display_name = { group["group_key"]: group.get("display_name") for group in word_groups } for group_key, data in word_stats.items(): all_titles = [] for source_id, title_list in data["titles"].items(): all_titles.extend(title_list) # 按权重排序 sorted_titles = sorted( all_titles, key=lambda x: ( -calculate_news_weight(x, rank_threshold, weight_config), min(x["ranks"]) if x["ranks"] else 999, -x["count"], ), ) # 应用最大显示数量限制(优先级:单独配置 > 全局配置) group_max_count = group_key_to_max_count.get(group_key, 0) if group_max_count == 0: # 使用全局配置 group_max_count = max_news_per_keyword if group_max_count > 0: sorted_titles = sorted_titles[:group_max_count] # 优先使用 display_name,否则使用 group_key display_word = group_key_to_display_name.get(group_key) or group_key stats.append( { "word": display_word, "count": data["count"], "position": group_key_to_position.get(group_key, 999), "titles": sorted_titles, "percentage": ( round(data["count"] / total_titles * 100, 2) if total_titles > 0 else 0 ), } ) # 根据配置选择排序优先级 if sort_by_position_first: # 先按配置位置,再按热点条数 stats.sort(key=lambda x: (x["position"], -x["count"])) else: # 先按热点条数,再按配置位置(原逻辑) stats.sort(key=lambda x: (-x["count"], x["position"])) # 打印过滤后的匹配新闻数 matched_news_count = sum(len(stat["titles"]) for stat in stats if stat["count"] > 0) if not quiet and mode == "daily": print(f"当日汇总模式:处理 {total_titles} 条新闻,模式:频率词过滤") print(f"频率词过滤后:{matched_news_count} 条新闻匹配") return stats, total_titles def count_rss_frequency( rss_items: List[Dict], word_groups: List[Dict], filter_words: List[str], global_filters: Optional[List[str]] = None, new_items: Optional[List[Dict]] = None, max_news_per_keyword: int = 0, sort_by_position_first: bool = False, timezone: str = DEFAULT_TIMEZONE, rank_threshold: int = 5, quiet: bool = False, ) -> Tuple[List[Dict], int]: from trendradar.utils.time import format_iso_time_friendly if not rss_items: return [], 0 # 如果没有配置词组,创建一个包含所有条目的虚拟词组 if not word_groups: if not quiet: print("[RSS] 频率词配置为空,将显示所有 RSS 条目") word_groups = [{"required": [], "normal": [], "group_key": "全部 RSS"}] filter_words = [] # 创建新增条目的 URL 集合,用于快速查找 new_urls = set() if new_items: for item in new_items: if item.get("url"): new_urls.add(item["url"]) # 初始化词组统计 word_stats = {} for group in word_groups: group_key = group["group_key"] word_stats[group_key] = {"count": 0, "titles": []} total_items = len(rss_items) processed_urls = set() # 用于去重 # 为每个条目分配一个基于发布时间的"排名" # 按发布时间排序,最新的排在前面 sorted_items = sorted( rss_items, key=lambda x: x.get("published_at", ""), reverse=True ) url_to_rank = {item.get("url", ""): idx + 1 for idx, item in enumerate(sorted_items)} for item in rss_items: title = item.get("title", "") url = item.get("url", "") # 去重 if url and url in processed_urls: continue if url: processed_urls.add(url) # 使用统一的匹配逻辑 if not matches_word_groups(title, word_groups, filter_words, global_filters): continue # 找到匹配的词组 title_lower = title.lower() for group in word_groups: required_words = group["required"] normal_words = group["normal"] group_key = group["group_key"] # "全部 RSS" 模式:所有条目都匹配 if len(word_groups) == 1 and word_groups[0]["group_key"] == "全部 RSS": matched = True else: # 检查必须词(支持正则语法) if required_words: all_required_present = all( _word_matches(req_item, title_lower) for req_item in required_words ) if not all_required_present: continue # 检查普通词(支持正则语法) if normal_words: any_normal_present = any( _word_matches(normal_item, title_lower) for normal_item in normal_words ) if not any_normal_present: continue matched = True if matched: word_stats[group_key]["count"] += 1 # 格式化时间显示 published_at = item.get("published_at", "") time_display = format_iso_time_friendly(published_at, timezone, include_date=True) if published_at else "" # 判断是否为新增 is_new = url in new_urls if url else False # 获取排名(基于发布时间顺序) rank = url_to_rank.get(url, 99) if url else 99 title_data = { "title": title, "source_name": item.get("feed_name", item.get("feed_id", "RSS")), "time_display": time_display, "count": 1, # RSS 条目通常只出现一次 "ranks": [rank], "rank_threshold": rank_threshold, "url": url, "mobile_url": "", "is_new": is_new, } word_stats[group_key]["titles"].append(title_data) break # 一个条目只匹配第一个词组 # 构建统计结果 stats = [] group_key_to_position = { group["group_key"]: idx for idx, group in enumerate(word_groups) } group_key_to_max_count = { group["group_key"]: group.get("max_count", 0) for group in word_groups } group_key_to_display_name = { group["group_key"]: group.get("display_name") for group in word_groups } for group_key, data in word_stats.items(): if data["count"] == 0: continue # 按发布时间排序(最新在前) sorted_titles = sorted( data["titles"], key=lambda x: x["ranks"][0] if x["ranks"] else 999 ) # 应用最大显示数量限制 group_max_count = group_key_to_max_count.get(group_key, 0) if group_max_count == 0: group_max_count = max_news_per_keyword if group_max_count > 0: sorted_titles = sorted_titles[:group_max_count] # 优先使用 display_name,否则使用 group_key display_word = group_key_to_display_name.get(group_key) or group_key stats.append({ "word": display_word, "count": data["count"], "position": group_key_to_position.get(group_key, 999), "titles": sorted_titles, "percentage": round(data["count"] / total_items * 100, 2) if total_items > 0 else 0, }) # 排序 if sort_by_position_first: stats.sort(key=lambda x: (x["position"], -x["count"])) else: stats.sort(key=lambda x: (-x["count"], x["position"])) matched_count = sum(stat["count"] for stat in stats) if not quiet: print(f"[RSS] 关键词分组统计:{matched_count}/{total_items} 条匹配") return stats, total_items def convert_keyword_stats_to_platform_stats( keyword_stats: List[Dict], weight_config: Dict, rank_threshold: int = 5, ) -> List[Dict]: # 1. 收集所有新闻,按平台分组 platform_map: Dict[str, List[Dict]] = {} for stat in keyword_stats: keyword = stat["word"] for title_data in stat["titles"]: source_name = title_data["source_name"] if source_name not in platform_map: platform_map[source_name] = [] # 复制 title_data 并添加匹配的关键词 title_with_keyword = title_data.copy() title_with_keyword["matched_keyword"] = keyword platform_map[source_name].append(title_with_keyword) # 2. 去重(同一平台下相同标题只保留一条,保留第一个匹配的关键词) for source_name, titles in platform_map.items(): seen_titles: Dict[str, bool] = {} unique_titles = [] for title_data in titles: title_text = title_data["title"] if title_text not in seen_titles: seen_titles[title_text] = True unique_titles.append(title_data) platform_map[source_name] = unique_titles # 3. 按权重排序每个平台内的新闻 for source_name, titles in platform_map.items(): platform_map[source_name] = sorted( titles, key=lambda x: ( -calculate_news_weight(x, rank_threshold, weight_config), min(x["ranks"]) if x["ranks"] else 999, -x["count"], ), ) # 4. 构建平台统计结果 platform_stats = [] for source_name, titles in platform_map.items(): platform_stats.append({ "word": source_name, # 平台名作为分组标识 "count": len(titles), "titles": titles, "percentage": 0, # 可后续计算 }) # 5. 按新闻条数排序平台 platform_stats.sort(key=lambda x: -x["count"]) return platform_stats
--- +++ @@ -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: + """ + 计算新闻权重,用于排序 + + Args: + title_data: 标题数据,包含 ranks 和 count + rank_threshold: 排名阈值 + weight_config: 权重配置 {RANK_WEIGHT, FREQUENCY_WEIGHT, HOTNESS_WEIGHT} + + Returns: + float: 计算出的权重值 + """ ranks = title_data.get("ranks", []) if not ranks: return 0.0 @@ -47,6 +66,17 @@ last_time: str, convert_time_func: Callable[[str], str], ) -> str: + """ + 格式化时间显示(将 HH-MM 转换为 HH:MM) + + Args: + first_time: 首次出现时间 + last_time: 最后出现时间 + convert_time_func: 时间格式转换函数 + + Returns: + str: 格式化后的时间显示字符串 + """ if not first_time: return "" # 转换为显示格式 @@ -75,6 +105,29 @@ convert_time_func: Optional[Callable[[str], str]] = None, quiet: bool = False, ) -> Tuple[List[Dict], int]: + """ + 统计词频,支持必须词、频率词、过滤词、全局过滤词,并标记新增标题 + + Args: + results: 抓取结果 {source_id: {title: title_data}} + word_groups: 词组配置列表 + filter_words: 过滤词列表 + id_to_name: ID 到名称的映射 + title_info: 标题统计信息(可选) + rank_threshold: 排名阈值 + new_titles: 新增标题(可选) + mode: 报告模式 (daily/incremental/current) + global_filters: 全局过滤词(可选) + weight_config: 权重配置 + max_news_per_keyword: 每个关键词最大显示数量 + sort_by_position_first: 是否优先按配置位置排序 + is_first_crawl_func: 检测是否是当天第一次爬取的函数 + convert_time_func: 时间格式转换函数 + quiet: 是否静默模式(不打印日志) + + Returns: + Tuple[List[Dict], int]: (统计结果列表, 总标题数) + """ # 默认权重配置 if weight_config is None: weight_config = { @@ -448,6 +501,50 @@ rank_threshold: int = 5, quiet: bool = False, ) -> Tuple[List[Dict], int]: + """ + 按关键词分组统计 RSS 条目(与热榜统计格式一致) + + Args: + rss_items: RSS 条目列表,每个条目包含: + - title: 标题 + - feed_id: RSS 源 ID + - feed_name: RSS 源名称 + - url: 文章链接 + - published_at: 发布时间(ISO 格式) + word_groups: 词组配置列表 + filter_words: 过滤词列表 + global_filters: 全局过滤词(可选) + new_items: 新增条目列表(可选,用于标记 is_new) + max_news_per_keyword: 每个关键词最大显示数量 + sort_by_position_first: 是否优先按配置位置排序 + timezone: 时区名称(用于时间格式化) + quiet: 是否静默模式 + + Returns: + Tuple[List[Dict], int]: (统计结果列表, 总条目数) + 统计结果格式与热榜一致: + [ + { + "word": "关键词", + "count": 5, + "position": 0, + "titles": [ + { + "title": "标题", + "source_name": "Hacker News", + "time_display": "12-29 08:20", + "count": 1, + "ranks": [1], # RSS 用发布时间顺序作为排名 + "rank_threshold": 50, + "url": "...", + "mobile_url": "", + "is_new": True/False + } + ], + "percentage": 10.0 + } + ] + """ from trendradar.utils.time import format_iso_time_friendly if not rss_items: @@ -615,6 +712,17 @@ weight_config: Dict, rank_threshold: int = 5, ) -> List[Dict]: + """ + 将按关键词分组的统计数据转换为按平台分组的统计数据 + + Args: + keyword_stats: 原始按关键词分组的统计数据 + weight_config: 权重配置 + rank_threshold: 排名阈值 + + Returns: + 按平台分组的统计数据,格式与原 stats 一致 + """ # 1. 收集所有新闻,按平台分组 platform_map: Dict[str, List[Dict]] = {} @@ -666,4 +774,4 @@ # 5. 按新闻条数排序平台 platform_stats.sort(key=lambda x: -x["count"]) - return platform_stats+ return platform_stats
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, "description": str, "count": int, "items": [ # {"title": str, "source_id": str, "source_name": str, # "url": str, "mobile_url": str, "rank": int, "ranks": [...], # "first_time": str, "last_time": str, "count": int, # "relevance_score": float, "source_type": str} # ]}] total_matched: int = 0 # 匹配新闻总数 total_processed: int = 0 # 处理新闻总数 success: bool = False error: str = "" class AIFilter: def __init__( self, ai_config: Dict[str, Any], filter_config: Dict[str, Any], get_time_func: Callable, debug: bool = False, ): self.client = AIClient(ai_config) self.filter_config = filter_config self.batch_size = filter_config.get("BATCH_SIZE", 200) self.get_time_func = get_time_func self.debug = debug # 加载提示词模板 self.classify_system, self.classify_user = self._load_prompt( filter_config.get("PROMPT_FILE", "ai_filter_prompt.txt") ) self.extract_system, self.extract_user = self._load_prompt( filter_config.get("EXTRACT_PROMPT_FILE", "ai_filter_extract_prompt.txt") ) self.update_tags_system, self.update_tags_user = self._load_prompt( filter_config.get("UPDATE_TAGS_PROMPT_FILE", "update_tags_prompt.txt") ) def _load_prompt(self, filename: str) -> tuple: config_dir = Path(__file__).parent.parent.parent / "config" / "ai_filter" prompt_path = config_dir / filename if not prompt_path.exists(): print(f"[AI筛选] 提示词文件不存在: {prompt_path}") return "", "" content = prompt_path.read_text(encoding="utf-8") system_prompt = "" user_prompt = "" if "[system]" in content and "[user]" in content: parts = content.split("[user]") system_part = parts[0] user_part = parts[1] if len(parts) > 1 else "" if "[system]" in system_part: system_prompt = system_part.split("[system]")[1].strip() user_prompt = user_part.strip() else: user_prompt = content return system_prompt, user_prompt def compute_interests_hash(self, interests_content: str, filename: str = "ai_interests.txt") -> str: # 去除前后空白和注释行,确保内容变化才改变 hash lines = [] for line in interests_content.strip().splitlines(): line = line.strip() if line and not line.startswith("#"): lines.append(line) normalized = "\n".join(lines) content_hash = hashlib.md5(normalized.encode("utf-8")).hexdigest() return f"{filename}:{content_hash}" def load_interests_content(self, interests_file: Optional[str] = None) -> Optional[str]: config_dir = Path(__file__).parent.parent.parent / "config" configured_file = interests_file if configured_file: # 自定义兴趣文件:仅查 custom/ai 目录 filename = configured_file interests_path = config_dir / "custom" / "ai" / filename if not interests_path.exists(): print(f"[AI筛选] 自定义兴趣描述文件不存在: {filename}") print(f"[AI筛选] 已查找: {interests_path}") return None else: # 默认兴趣文件:固定使用 config/ai_interests.txt filename = "ai_interests.txt" interests_path = config_dir / filename if not interests_path.exists(): print(f"[AI筛选] 默认兴趣描述文件不存在: {filename}") print(f"[AI筛选] 已查找: {interests_path}") return None if not interests_path.exists(): print(f"[AI筛选] 兴趣描述文件不存在: {interests_path}") return None content = interests_path.read_text(encoding="utf-8").strip() if not content: print("[AI筛选] 兴趣描述文件为空") return None return content def extract_tags(self, interests_content: str) -> List[Dict]: if not self.extract_user: print("[AI筛选] 标签提取提示词模板为空") return [] user_prompt = self.extract_user.replace("{interests_content}", interests_content) messages = [] if self.extract_system: messages.append({"role": "system", "content": self.extract_system}) messages.append({"role": "user", "content": user_prompt}) if self.debug: print(f"\n[AI筛选][DEBUG] === 标签提取 Prompt ===") for m in messages: print(f"[{m['role']}]\n{m['content']}") print(f"[AI筛选][DEBUG] === Prompt 结束 ===") try: response = self.client.chat(messages) if self.debug: print(f"\n[AI筛选][DEBUG] === 标签提取 AI 原始响应 ===") # 尝试格式化 JSON 便于阅读 self._print_formatted_json(response) print(f"[AI筛选][DEBUG] === 响应结束 ===") tags = self._parse_tags_response(response) print(f"[AI筛选] 提取到 {len(tags)} 个标签") for t in tags: print(f" {t['tag']}: {t.get('description', '')}") if self.debug: json_str = self._extract_json(response) if not json_str: print(f"[AI筛选][DEBUG] 无法从响应中提取 JSON") else: raw_data = json.loads(json_str) raw_tags = raw_data.get("tags", []) skipped = len(raw_tags) - len(tags) if skipped > 0: print(f"[AI筛选][DEBUG] 原始标签 {len(raw_tags)} 个,有效 {len(tags)} 个,跳过 {skipped} 个(缺少 tag 字段或格式无效)") return tags except json.JSONDecodeError as e: print(f"[AI筛选] 标签提取失败: JSON 解析错误: {e}") if self.debug: print(f"[AI筛选][DEBUG] 尝试解析的 JSON 内容: {self._extract_json(response) if response else '(空响应)'}") return [] except Exception as e: print(f"[AI筛选] 标签提取失败: {type(e).__name__}: {e}") return [] def update_tags(self, old_tags: List[Dict], interests_content: str) -> Optional[Dict]: if not self.update_tags_user: print("[AI筛选] 标签更新提示词模板为空,回退到重新提取") return None # 构造旧标签 JSON old_tags_json = json.dumps( [{"tag": t["tag"], "description": t.get("description", "")} for t in old_tags], ensure_ascii=False, indent=2 ) user_prompt = self.update_tags_user.replace( "{old_tags_json}", old_tags_json ).replace( "{interests_content}", interests_content ) messages = [] if self.update_tags_system: messages.append({"role": "system", "content": self.update_tags_system}) messages.append({"role": "user", "content": user_prompt}) if self.debug: print(f"\n[AI筛选][DEBUG] === 标签更新 Prompt ===") for m in messages: print(f"[{m['role']}]\n{m['content']}") print(f"[AI筛选][DEBUG] === Prompt 结束 ===") try: response = self.client.chat(messages) if self.debug: print(f"\n[AI筛选][DEBUG] === 标签更新 AI 原始响应 ===") self._print_formatted_json(response) print(f"[AI筛选][DEBUG] === 响应结束 ===") result = self._parse_update_tags_response(response) if result is None: return None keep_count = len(result.get("keep", [])) add_count = len(result.get("add", [])) remove_count = len(result.get("remove", [])) ratio = result.get("change_ratio", 0) print(f"[AI筛选] AI 标签更新方案: 保留 {keep_count}, 新增 {add_count}, 移除 {remove_count}, change_ratio={ratio:.2f}") return result except Exception as e: print(f"[AI筛选] 标签更新失败: {type(e).__name__}: {e}") return None def _parse_update_tags_response(self, response: str) -> Optional[Dict]: json_str = self._extract_json(response) if not json_str: print("[AI筛选] 无法从标签更新响应中提取 JSON") return None data = json.loads(json_str) # 校验必需字段 keep = data.get("keep", []) add = data.get("add", []) remove = data.get("remove", []) change_ratio = float(data.get("change_ratio", 0)) # 校验 keep/add 格式 validated_keep = [] for t in keep: if isinstance(t, dict) and "tag" in t: validated_keep.append({ "tag": str(t["tag"]).strip(), "description": str(t.get("description", "")).strip(), }) validated_add = [] for t in add: if isinstance(t, dict) and "tag" in t: validated_add.append({ "tag": str(t["tag"]).strip(), "description": str(t.get("description", "")).strip(), }) validated_remove = [str(r).strip() for r in remove if r] # change_ratio 限制在 0~1 change_ratio = max(0.0, min(1.0, change_ratio)) return { "keep": validated_keep, "add": validated_add, "remove": validated_remove, "change_ratio": change_ratio, } def _parse_tags_response(self, response: str) -> List[Dict]: json_str = self._extract_json(response) if not json_str: return [] data = json.loads(json_str) tags_raw = data.get("tags", []) tags = [] for t in tags_raw: if not isinstance(t, dict) or "tag" not in t: continue tags.append({ "tag": str(t["tag"]).strip(), "description": str(t.get("description", "")).strip(), }) return tags def classify_batch( self, titles: List[Dict], tags: List[Dict], interests_content: str = "", ) -> List[Dict]: if not titles or not tags: return [] if not self.classify_user: print("[AI筛选] 分类提示词模板为空") return [] # 构建标签列表文本 tags_list = "\n".join( f"{t['id']}. {t['tag']}: {t.get('description', '')}" for t in tags ) # 构建新闻列表文本 news_list = "\n".join( f"{t['id']}. [{t.get('source', '')}] {t['title']}" for t in titles ) # 填充模板 user_prompt = self.classify_user user_prompt = user_prompt.replace("{interests_content}", interests_content) user_prompt = user_prompt.replace("{tags_list}", tags_list) user_prompt = user_prompt.replace("{news_count}", str(len(titles))) user_prompt = user_prompt.replace("{news_list}", news_list) messages = [] if self.classify_system: messages.append({"role": "system", "content": self.classify_system}) messages.append({"role": "user", "content": user_prompt}) if self.debug: print(f"\n[AI筛选][DEBUG] === 分类 Prompt (标题数={len(titles)}, 标签={len(tags)}) ===") for m in messages: role = m['role'] content = m['content'] # 截断过长的新闻列表:只显示前5条和后5条 lines = content.split('\n') # 找到新闻列表区域并截断 if len(lines) > 30: # 显示前15行 + 省略提示 + 后10行 head = lines[:15] tail = lines[-10:] omitted = len(lines) - 25 truncated = '\n'.join(head) + f'\n... (省略 {omitted} 行) ...\n' + '\n'.join(tail) print(f"[{role}]\n{truncated}") else: print(f"[{role}]\n{content}") print(f"[AI筛选][DEBUG] === Prompt 结束 (长度: {sum(len(m['content']) for m in messages)} 字符) ===") try: response = self.client.chat(messages) return self._parse_classify_response(response, titles, tags) except Exception as e: print(f"[AI筛选] 分类请求失败: {type(e).__name__}: {e}") return [] def _parse_classify_response( self, response: str, titles: List[Dict], tags: List[Dict], ) -> List[Dict]: json_str = self._extract_json(response) if not json_str: if self.debug: print(f"[AI筛选][DEBUG] 无法从分类响应中提取 JSON,原始响应前 500 字符: {(response or '')[:500]}") return [] try: data = json.loads(json_str) except json.JSONDecodeError as e: if self.debug: print(f"[AI筛选][DEBUG] 分类响应 JSON 解析失败: {e}") print(f"[AI筛选][DEBUG] 提取的 JSON 文本前 500 字符: {json_str[:500]}") return [] if not isinstance(data, list): if self.debug: print(f"[AI筛选][DEBUG] 分类响应顶层不是数组,实际类型: {type(data).__name__}") return [] # 构建 id 映射 title_ids = {t["id"] for t in titles} title_map = {t["id"]: t["title"] for t in titles} tag_id_set = {t["id"] for t in tags} tag_name_map = {t["id"]: t["tag"] for t in tags} # 每条新闻只保留一个最高分的 tag best_per_news: Dict[int, Dict] = {} # news_id -> {"tag_id": ..., "score": ...} skipped_news_ids = 0 skipped_tag_ids = 0 skipped_empty = 0 for item in data: if not isinstance(item, dict): continue news_id = item.get("id") if news_id not in title_ids: skipped_news_ids += 1 continue # 收集此条新闻的所有候选 tag candidates = [] if "tag_id" in item: # 新格式(扁平): {"id": 1, "tag_id": 1, "score": 0.9} candidates.append({"tag_id": item["tag_id"], "score": item.get("score", 0.5)}) elif "tags" in item: # 旧格式(嵌套): {"id": 1, "tags": [{"tag_id": 1, "score": 0.9}]} matched_tags = item.get("tags", []) if isinstance(matched_tags, list): if not matched_tags: skipped_empty += 1 continue candidates.extend(matched_tags) if not candidates: skipped_empty += 1 continue # 取最高分的有效 tag best_tag_id = None best_score = -1.0 for tag_match in candidates: if not isinstance(tag_match, dict): continue tag_id = tag_match.get("tag_id") if tag_id not in tag_id_set: skipped_tag_ids += 1 continue score = tag_match.get("score", 0.5) try: score = float(score) score = max(0.0, min(1.0, score)) except (ValueError, TypeError): score = 0.5 if score > best_score: best_score = score best_tag_id = tag_id if best_tag_id is not None: # 如果同一条新闻被多次返回,只保留分数更高的 existing = best_per_news.get(news_id) if existing is None or best_score > existing["relevance_score"]: best_per_news[news_id] = { "news_item_id": news_id, "tag_id": best_tag_id, "relevance_score": best_score, } results = list(best_per_news.values()) if self.debug: ai_returned = len(data) print(f"[AI筛选][DEBUG] --- 分类解析结果 ---") print(f"[AI筛选][DEBUG] AI 返回 {ai_returned} 条, 有效 {len(results)} 条 (每条新闻仅保留最高分 tag)") if skipped_empty > 0: print(f"[AI筛选][DEBUG] 跳过空 tags: {skipped_empty} 条") if skipped_news_ids > 0: print(f"[AI筛选][DEBUG] !! 跳过无效 news_id: {skipped_news_ids} 条") if skipped_tag_ids > 0: print(f"[AI筛选][DEBUG] !! 跳过无效 tag_id: {skipped_tag_ids} 条") # 按标签汇总 tag_summary: Dict[int, List[str]] = {} for r in results: tid = r["tag_id"] if tid not in tag_summary: tag_summary[tid] = [] tag_summary[tid].append( f" [{r['news_item_id']}] {title_map.get(r['news_item_id'], '?')[:40]} (score={r['relevance_score']:.2f})" ) for tid, items in tag_summary.items(): tname = tag_name_map.get(tid, f"tag_{tid}") print(f"[AI筛选][DEBUG] 标签「{tname}」匹配 {len(items)} 条:") for line in items: print(line) return results def _extract_json(self, response: str) -> Optional[str]: if not response or not response.strip(): return None json_str = response.strip() if "```json" in json_str: parts = json_str.split("```json", 1) if len(parts) > 1: code_block = parts[1] end_idx = code_block.find("```") json_str = code_block[:end_idx] if end_idx != -1 else code_block elif "```" in json_str: parts = json_str.split("```", 2) if len(parts) >= 2: json_str = parts[1] json_str = json_str.strip() return json_str if json_str else None def _print_formatted_json(self, response: str) -> None: if not response: print("(空响应)") return json_str = self._extract_json(response) if json_str: try: data = json.loads(json_str) if isinstance(data, list): # 数组:每个元素压成一行 lines = [json.dumps(item, ensure_ascii=False) for item in data] print("[\n " + ",\n ".join(lines) + "\n]") else: print(json.dumps(data, ensure_ascii=False, indent=2)) return except json.JSONDecodeError: pass # JSON 解析失败,直接打印原始响应 print(response)
--- +++ @@ -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, "description": str, "count": int, "items": [ # {"title": str, "source_id": str, "source_name": str, @@ -25,6 +33,7 @@ class AIFilter: + """AI 智能筛选器""" def __init__( self, @@ -51,6 +60,7 @@ ) def _load_prompt(self, filename: str) -> tuple: + """加载提示词文件,返回 (system_prompt, user_prompt_template)""" config_dir = Path(__file__).parent.parent.parent / "config" / "ai_filter" prompt_path = config_dir / filename @@ -77,6 +87,7 @@ return system_prompt, user_prompt def compute_interests_hash(self, interests_content: str, filename: str = "ai_interests.txt") -> str: + """计算兴趣描述的 hash,格式为 filename:md5""" # 去除前后空白和注释行,确保内容变化才改变 hash lines = [] for line in interests_content.strip().splitlines(): @@ -88,6 +99,15 @@ return f"{filename}:{content_hash}" def load_interests_content(self, interests_file: Optional[str] = None) -> Optional[str]: + """加载兴趣描述文件内容 + + 解析逻辑: + - interests_file 为 None:使用默认 config/ai_interests.txt + - interests_file 有值:仅查 config/custom/ai/{filename} + + 注意:调用方(context.py)已完成 config/timeline 的合并决策, + 此处不再二次读取 filter_config,避免语义冲突。 + """ config_dir = Path(__file__).parent.parent.parent / "config" configured_file = interests_file @@ -120,6 +140,15 @@ return content def extract_tags(self, interests_content: str) -> List[Dict]: + """ + 阶段 A:从兴趣描述中提取结构化标签 + + Args: + interests_content: 用户的兴趣描述文本 + + Returns: + [{"tag": str, "description": str}, ...] + """ if not self.extract_user: print("[AI筛选] 标签提取提示词模板为空") return [] @@ -173,6 +202,20 @@ return [] def update_tags(self, old_tags: List[Dict], interests_content: str) -> Optional[Dict]: + """ + 阶段 A':AI 对比旧标签和新兴趣描述,给出更新方案 + + Args: + old_tags: [{"tag": str, "description": str, "id": int}, ...] + interests_content: 新的兴趣描述文本 + + Returns: + {"keep": [{"tag": str, "description": str}], + "add": [{"tag": str, "description": str}], + "remove": [str], + "change_ratio": float} + 失败返回 None + """ if not self.update_tags_user: print("[AI筛选] 标签更新提示词模板为空,回退到重新提取") return None @@ -224,6 +267,7 @@ return None def _parse_update_tags_response(self, response: str) -> Optional[Dict]: + """解析标签更新的 AI 响应""" json_str = self._extract_json(response) if not json_str: print("[AI筛选] 无法从标签更新响应中提取 JSON") @@ -267,6 +311,7 @@ } def _parse_tags_response(self, response: str) -> List[Dict]: + """解析标签提取的 AI 响应""" json_str = self._extract_json(response) if not json_str: return [] @@ -291,6 +336,17 @@ tags: List[Dict], interests_content: str = "", ) -> List[Dict]: + """ + 阶段 B:对一批新闻标题做分类 + + Args: + titles: [{"id": news_item_id, "title": str, "source": str}] + tags: [{"id": tag_id, "tag": str, "description": str}] + interests_content: 用户的兴趣描述(含质量过滤要求) + + Returns: + [{"news_item_id": int, "tag_id": int, "relevance_score": float}, ...] + """ if not titles or not tags: return [] @@ -355,6 +411,14 @@ titles: List[Dict], tags: List[Dict], ) -> List[Dict]: + """解析分类的 AI 响应 + + 支持两种 JSON 格式: + - 新格式(扁平): [{"id": 1, "tag_id": 1, "score": 0.9}, ...] + - 旧格式(嵌套): [{"id": 1, "tags": [{"tag_id": 1, "score": 0.9}]}, ...] + + 每条新闻只保留一个最高分的 tag,杜绝同一条出现在多个标签下。 + """ json_str = self._extract_json(response) if not json_str: if self.debug: @@ -478,6 +542,7 @@ return results def _extract_json(self, response: str) -> Optional[str]: + """从 AI 响应中提取 JSON 字符串""" if not response or not response.strip(): return None @@ -498,6 +563,7 @@ return json_str if json_str else None def _print_formatted_json(self, response: str) -> None: + """格式化打印 AI 响应中的 JSON,便于 debug 阅读""" if not response: print("(空响应)") return @@ -517,4 +583,4 @@ pass # JSON 解析失败,直接打印原始响应 - print(response)+ print(response)
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() # 0. 合并序号与紧随的【标签】(防御性处理) # 将 "1.\n【投资者】:" 或 "1. 【投资者】:" 合并为 "1. 投资者:" text = re.sub(r'(\d+\.)\s*【([^】]+)】([::]?)', r'\1 \2:', text) # 1. 规范化:确保 "1." 后面有空格 result = re.sub(r'(\d+)\.([^ \d])', r'\1. \2', text) # 2. 强制换行:匹配 "数字.",且前面不是换行符 # (?!\d) 排除版本号/小数(如 2.0、3.5),避免将其误判为列表序号 result = re.sub(r'(?<=[^\n])\s+(\d+\.)(?!\d)', r'\n\1', result) # 3. 处理 "1.**粗体**" 这种情况(虽然 Prompt 要求不输出 Markdown,但防御性处理) result = re.sub(r'(?<=[^\n])(\d+\.\*\*)', r'\n\1', result) # 4. 处理中文标点后的换行(排除版本号/小数) result = re.sub(r'([::;,。;,])\s*(\d+\.)(?!\d)', r'\1\n\2', result) # 5. 处理 "XX方面:"、"XX领域:" 等子标题换行 # 只有在中文标点(句号、逗号、分号等)后才触发换行,避免破坏 "1. XX领域:" 格式 result = re.sub(r'([。!?;,、])\s*([a-zA-Z0-9\u4e00-\u9fa5]+(方面|领域)[::])', r'\1\n\2', result) # 6. 处理 【标签】 格式 # 6a. 标签前确保空行分隔(文本开头除外) result = re.sub(r'(?<=\S)\n*(【[^】]+】)', r'\n\n\1', result) # 6b. 合并标签与被换行拆开的冒号:【tag】\n: → 【tag】: result = re.sub(r'(【[^】]+】)\n+([::])', r'\1\2', result) # 6c. 标签后(含可选冒号),如果紧跟非空白非冒号内容则另起一行 # 用 (?=[^\s::]) 避免正则回溯将冒号误判为"内容"而拆开 【tag】: result = re.sub(r'(【[^】]+】[::]?)[ \t]*(?=[^\s::])', r'\1\n', result) # 7. 在列表项之间增加视觉空行(排除版本号/小数) # 排除 【标签】 行(以】结尾)和子标题行(以冒号结尾)之后的情况,避免标题与首项之间出现空行 result = re.sub(r'(?<![::】])\n(\d+\.)(?!\d)', r'\n\n\1', result) return result def _format_standalone_summaries(summaries: dict) -> str: if not summaries: return "" lines = [] for source_name, summary in summaries.items(): if summary: lines.append(f"[{source_name}]:\n{summary}") return "\n\n".join(lines) def render_ai_analysis_markdown(result: AIAnalysisResult) -> str: if not result.success: return f"⚠️ AI 分析失败: {result.error}" lines = ["**✨ AI 热点分析**", ""] if result.core_trends: lines.extend(["**核心热点态势**", _format_list_content(result.core_trends), ""]) if result.sentiment_controversy: lines.extend( ["**舆论风向争议**", _format_list_content(result.sentiment_controversy), ""] ) if result.signals: lines.extend(["**异动与弱信号**", _format_list_content(result.signals), ""]) if result.rss_insights: lines.extend( ["**RSS 深度洞察**", _format_list_content(result.rss_insights), ""] ) if result.outlook_strategy: lines.extend( ["**研判策略建议**", _format_list_content(result.outlook_strategy), ""] ) if result.standalone_summaries: summaries_text = _format_standalone_summaries(result.standalone_summaries) if summaries_text: lines.extend(["**独立源点速览**", summaries_text]) return "\n".join(lines) def render_ai_analysis_feishu(result: AIAnalysisResult) -> str: if not result.success: return f"⚠️ AI 分析失败: {result.error}" lines = ["**✨ AI 热点分析**", ""] if result.core_trends: lines.extend(["**核心热点态势**", _format_list_content(result.core_trends), ""]) if result.sentiment_controversy: lines.extend( ["**舆论风向争议**", _format_list_content(result.sentiment_controversy), ""] ) if result.signals: lines.extend(["**异动与弱信号**", _format_list_content(result.signals), ""]) if result.rss_insights: lines.extend( ["**RSS 深度洞察**", _format_list_content(result.rss_insights), ""] ) if result.outlook_strategy: lines.extend( ["**研判策略建议**", _format_list_content(result.outlook_strategy), ""] ) if result.standalone_summaries: summaries_text = _format_standalone_summaries(result.standalone_summaries) if summaries_text: lines.extend(["**独立源点速览**", summaries_text]) return "\n".join(lines) def render_ai_analysis_dingtalk(result: AIAnalysisResult) -> str: if not result.success: return f"⚠️ AI 分析失败: {result.error}" lines = ["### ✨ AI 热点分析", ""] if result.core_trends: lines.extend( ["#### 核心热点态势", _format_list_content(result.core_trends), ""] ) if result.sentiment_controversy: lines.extend( [ "#### 舆论风向争议", _format_list_content(result.sentiment_controversy), "", ] ) if result.signals: lines.extend(["#### 异动与弱信号", _format_list_content(result.signals), ""]) if result.rss_insights: lines.extend( ["#### RSS 深度洞察", _format_list_content(result.rss_insights), ""] ) if result.outlook_strategy: lines.extend( ["#### 研判策略建议", _format_list_content(result.outlook_strategy), ""] ) if result.standalone_summaries: summaries_text = _format_standalone_summaries(result.standalone_summaries) if summaries_text: lines.extend(["#### 独立源点速览", summaries_text]) return "\n".join(lines) def render_ai_analysis_html(result: AIAnalysisResult) -> str: if not result.success: return ( f'<div class="ai-error">⚠️ AI 分析失败: {_escape_html(result.error)}</div>' ) html_parts = ['<div class="ai-analysis">', "<h3>✨ AI 热点分析</h3>"] if result.core_trends: content = _format_list_content(result.core_trends) content_html = _escape_html(content).replace("\n", "<br>") html_parts.extend( [ '<div class="ai-section">', "<h4>核心热点态势</h4>", f'<div class="ai-content">{content_html}</div>', "</div>", ] ) if result.sentiment_controversy: content = _format_list_content(result.sentiment_controversy) content_html = _escape_html(content).replace("\n", "<br>") html_parts.extend( [ '<div class="ai-section">', "<h4>舆论风向争议</h4>", f'<div class="ai-content">{content_html}</div>', "</div>", ] ) if result.signals: content = _format_list_content(result.signals) content_html = _escape_html(content).replace("\n", "<br>") html_parts.extend( [ '<div class="ai-section">', "<h4>异动与弱信号</h4>", f'<div class="ai-content">{content_html}</div>', "</div>", ] ) if result.rss_insights: content = _format_list_content(result.rss_insights) content_html = _escape_html(content).replace("\n", "<br>") html_parts.extend( [ '<div class="ai-section">', "<h4>RSS 深度洞察</h4>", f'<div class="ai-content">{content_html}</div>', "</div>", ] ) if result.outlook_strategy: content = _format_list_content(result.outlook_strategy) content_html = _escape_html(content).replace("\n", "<br>") html_parts.extend( [ '<div class="ai-section ai-conclusion">', "<h4>研判策略建议</h4>", f'<div class="ai-content">{content_html}</div>', "</div>", ] ) if result.standalone_summaries: summaries_text = _format_standalone_summaries(result.standalone_summaries) if summaries_text: summaries_html = _escape_html(summaries_text).replace("\n", "<br>") html_parts.extend( [ '<div class="ai-section">', "<h4>独立源点速览</h4>", f'<div class="ai-content">{summaries_html}</div>', "</div>", ] ) html_parts.append("</div>") return "\n".join(html_parts) def render_ai_analysis_plain(result: AIAnalysisResult) -> str: if not result.success: return f"AI 分析失败: {result.error}" lines = ["【✨ AI 热点分析】", ""] if result.core_trends: lines.extend(["[核心热点态势]", _format_list_content(result.core_trends), ""]) if result.sentiment_controversy: lines.extend( ["[舆论风向争议]", _format_list_content(result.sentiment_controversy), ""] ) if result.signals: lines.extend(["[异动与弱信号]", _format_list_content(result.signals), ""]) if result.rss_insights: lines.extend(["[RSS 深度洞察]", _format_list_content(result.rss_insights), ""]) if result.outlook_strategy: lines.extend(["[研判策略建议]", _format_list_content(result.outlook_strategy), ""]) if result.standalone_summaries: summaries_text = _format_standalone_summaries(result.standalone_summaries) if summaries_text: lines.extend(["[独立源点速览]", summaries_text]) return "\n".join(lines) def get_ai_analysis_renderer(channel: str): renderers = { "feishu": render_ai_analysis_feishu, "dingtalk": render_ai_analysis_dingtalk, "wework": render_ai_analysis_markdown, "telegram": render_ai_analysis_markdown, "email": render_ai_analysis_html_rich, # 邮件使用丰富样式,配合 HTML 报告的 CSS "ntfy": render_ai_analysis_markdown, "bark": render_ai_analysis_plain, "slack": render_ai_analysis_markdown, } return renderers.get(channel, render_ai_analysis_markdown) def render_ai_analysis_html_rich(result: AIAnalysisResult) -> str: if not result: return "" # 检查是否成功 if not result.success: error_msg = result.error or "未知错误" return f""" <div class="ai-section"> <div class="ai-error">⚠️ AI 分析失败: {_escape_html(str(error_msg))}</div> </div>""" ai_html = """ <div class="ai-section"> <div class="ai-section-header"> <div class="ai-section-title">✨ AI 热点分析</div> <span class="ai-section-badge">AI</span> </div>""" if result.core_trends: content = _format_list_content(result.core_trends) content_html = _escape_html(content).replace("\n", "<br>") ai_html += f""" <div class="ai-block"> <div class="ai-block-title">核心热点态势</div> <div class="ai-block-content">{content_html}</div> </div>""" if result.sentiment_controversy: content = _format_list_content(result.sentiment_controversy) content_html = _escape_html(content).replace("\n", "<br>") ai_html += f""" <div class="ai-block"> <div class="ai-block-title">舆论风向争议</div> <div class="ai-block-content">{content_html}</div> </div>""" if result.signals: content = _format_list_content(result.signals) content_html = _escape_html(content).replace("\n", "<br>") ai_html += f""" <div class="ai-block"> <div class="ai-block-title">异动与弱信号</div> <div class="ai-block-content">{content_html}</div> </div>""" if result.rss_insights: content = _format_list_content(result.rss_insights) content_html = _escape_html(content).replace("\n", "<br>") ai_html += f""" <div class="ai-block"> <div class="ai-block-title">RSS 深度洞察</div> <div class="ai-block-content">{content_html}</div> </div>""" if result.outlook_strategy: content = _format_list_content(result.outlook_strategy) content_html = _escape_html(content).replace("\n", "<br>") ai_html += f""" <div class="ai-block"> <div class="ai-block-title">研判策略建议</div> <div class="ai-block-content">{content_html}</div> </div>""" if result.standalone_summaries: summaries_text = _format_standalone_summaries(result.standalone_summaries) if summaries_text: summaries_html = _escape_html(summaries_text).replace("\n", "<br>") ai_html += f""" <div class="ai-block"> <div class="ai-block-title">独立源点速览</div> <div class="ai-block-content">{summaries_html}</div> </div>""" ai_html += """ </div>""" return ai_html
--- +++ @@ -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: + """ + 格式化列表内容,确保序号前有换行 + 例如将 "1. xxx 2. yyy" 转换为: + 1. xxx + 2. yyy + """ if not text: return "" @@ -54,6 +66,7 @@ def _format_standalone_summaries(summaries: dict) -> str: + """格式化独立展示区概括为纯文本行,每个源名称单独一行""" if not summaries: return "" lines = [] @@ -64,6 +77,7 @@ def render_ai_analysis_markdown(result: AIAnalysisResult) -> str: + """渲染为通用 Markdown 格式(Telegram、企业微信、ntfy、Bark、Slack)""" if not result.success: return f"⚠️ AI 分析失败: {result.error}" @@ -99,6 +113,7 @@ def render_ai_analysis_feishu(result: AIAnalysisResult) -> str: + """渲染为飞书卡片 Markdown 格式""" if not result.success: return f"⚠️ AI 分析失败: {result.error}" @@ -134,6 +149,7 @@ def render_ai_analysis_dingtalk(result: AIAnalysisResult) -> str: + """渲染为钉钉 Markdown 格式""" if not result.success: return f"⚠️ AI 分析失败: {result.error}" @@ -175,6 +191,7 @@ def render_ai_analysis_html(result: AIAnalysisResult) -> str: + """渲染为 HTML 格式(邮件)""" if not result.success: return ( f'<div class="ai-error">⚠️ AI 分析失败: {_escape_html(result.error)}</div>' @@ -260,6 +277,7 @@ def render_ai_analysis_plain(result: AIAnalysisResult) -> str: + """渲染为纯文本格式""" if not result.success: return f"AI 分析失败: {result.error}" @@ -291,6 +309,7 @@ def get_ai_analysis_renderer(channel: str): + """根据渠道获取对应的渲染函数""" renderers = { "feishu": render_ai_analysis_feishu, "dingtalk": render_ai_analysis_dingtalk, @@ -305,6 +324,7 @@ def render_ai_analysis_html_rich(result: AIAnalysisResult) -> str: + """渲染为丰富样式的 HTML 格式(HTML 报告用)""" if not result: return "" @@ -380,4 +400,4 @@ ai_html += """ </div>""" - return ai_html+ return ai_html
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 pytz.UnknownTimeZoneError: print(f"[警告] 未知时区 '{timezone}',使用默认时区 {DEFAULT_TIMEZONE}") tz = pytz.timezone(DEFAULT_TIMEZONE) return datetime.now(tz) def format_date_folder( date: Optional[str] = None, timezone: str = DEFAULT_TIMEZONE ) -> str: if date: return date return get_configured_time(timezone).strftime("%Y-%m-%d") def format_time_filename(timezone: str = DEFAULT_TIMEZONE) -> str: return get_configured_time(timezone).strftime("%H-%M") def get_current_time_display(timezone: str = DEFAULT_TIMEZONE) -> str: return get_configured_time(timezone).strftime("%H:%M") def convert_time_for_display(time_str: str) -> str: if time_str and "-" in time_str and len(time_str) == 5: return time_str.replace("-", ":") return time_str def format_iso_time_friendly( iso_time: str, timezone: str = DEFAULT_TIMEZONE, include_date: bool = True, ) -> str: if not iso_time: return "" try: # 尝试解析各种 ISO 格式 dt = None # 尝试解析带时区的格式 if "+" in iso_time or iso_time.endswith("Z"): iso_time = iso_time.replace("Z", "+00:00") try: dt = datetime.fromisoformat(iso_time) except ValueError: pass # 尝试解析不带时区的格式(假设为 UTC) if dt is None: try: # 处理 T 分隔符 if "T" in iso_time: dt = datetime.fromisoformat(iso_time.replace("T", " ").split(".")[0]) else: dt = datetime.fromisoformat(iso_time.split(".")[0]) # 假设为 UTC 时间 dt = pytz.UTC.localize(dt) except ValueError: pass if dt is None: # 无法解析,返回原始字符串的简化版本 if "T" in iso_time: parts = iso_time.split("T") if len(parts) == 2: date_part = parts[0][5:] # MM-DD time_part = parts[1][:5] # HH:MM return f"{date_part} {time_part}" if include_date else time_part return iso_time # 转换到目标时区 try: target_tz = pytz.timezone(timezone) except pytz.UnknownTimeZoneError: target_tz = pytz.timezone(DEFAULT_TIMEZONE) dt_local = dt.astimezone(target_tz) # 格式化输出 if include_date: return dt_local.strftime("%m-%d %H:%M") else: return dt_local.strftime("%H:%M") except Exception: # 出错时返回原始字符串的简化版本 if "T" in iso_time: parts = iso_time.split("T") if len(parts) == 2: date_part = parts[0][5:] # MM-DD time_part = parts[1][:5] # HH:MM return f"{date_part} {time_part}" if include_date else time_part return iso_time def is_within_days( iso_time: str, max_days: int, timezone: str = DEFAULT_TIMEZONE, ) -> bool: # 无时间戳或禁用过滤时,保留文章 if not iso_time: return True if max_days <= 0: return True # max_days=0 表示禁用过滤 try: dt = None # 尝试解析带时区的格式 if "+" in iso_time or iso_time.endswith("Z"): iso_time_normalized = iso_time.replace("Z", "+00:00") try: dt = datetime.fromisoformat(iso_time_normalized) except ValueError: pass # 尝试解析不带时区的格式(假设为 UTC) if dt is None: try: if "T" in iso_time: dt = datetime.fromisoformat(iso_time.replace("T", " ").split(".")[0]) else: dt = datetime.fromisoformat(iso_time.split(".")[0]) dt = pytz.UTC.localize(dt) except ValueError: pass if dt is None: # 无法解析时间,保留文章 return True # 获取当前时间(配置的时区,带时区信息) now = get_configured_time(timezone) # 计算时间差(两个带时区的 datetime 相减会自动处理时区差异) diff = now - dt days_diff = diff.total_seconds() / (24 * 60 * 60) return days_diff <= max_days except Exception: # 出错时保留文章 return True def calculate_days_old(iso_time: str, timezone: str = DEFAULT_TIMEZONE) -> Optional[float]: if not iso_time: return None try: dt = None # 尝试解析带时区的格式 if "+" in iso_time or iso_time.endswith("Z"): iso_time_normalized = iso_time.replace("Z", "+00:00") try: dt = datetime.fromisoformat(iso_time_normalized) except ValueError: pass # 尝试解析不带时区的格式(假设为 UTC) if dt is None: try: if "T" in iso_time: dt = datetime.fromisoformat(iso_time.replace("T", " ").split(".")[0]) else: dt = datetime.fromisoformat(iso_time.split(".")[0]) dt = pytz.UTC.localize(dt) except ValueError: pass if dt is None: return None now = get_configured_time(timezone) diff = now - dt return diff.total_seconds() / (24 * 60 * 60) except Exception: return None class TimeWindowChecker: def __init__( self, storage_backend, get_time_func=None, window_name: str = "时间窗口", ): self.storage_backend = storage_backend self.get_time_func = get_time_func or (lambda: get_configured_time(DEFAULT_TIMEZONE)) self.window_name = window_name def is_in_time_range(self, start_time: str, end_time: str) -> bool: now = self.get_time_func() current_time = now.strftime("%H:%M") normalized_start = self._normalize_time(start_time) normalized_end = self._normalize_time(end_time) normalized_current = self._normalize_time(current_time) # 判断是否跨日窗口(start > end 表示跨日,如 22:00-02:00) if normalized_start <= normalized_end: # 正常窗口:09:00-21:00 result = normalized_start <= normalized_current <= normalized_end else: # 跨日窗口:22:00-02:00 # 当前时间 >= 开始时间(如 23:00 >= 22:00)或 当前时间 <= 结束时间(如 01:00 <= 02:00) result = normalized_current >= normalized_start or normalized_current <= normalized_end if not result: print(f"[{self.window_name}] 当前 {normalized_current},窗口 {normalized_start}-{normalized_end}") return result def _normalize_time(self, time_str: str) -> str: try: parts = time_str.strip().split(":") if len(parts) != 2: raise ValueError(f"时间格式错误: {time_str}") hour = int(parts[0]) minute = int(parts[1]) if not (0 <= hour <= 23 and 0 <= minute <= 59): raise ValueError(f"时间范围错误: {time_str}") return f"{hour:02d}:{minute:02d}" except Exception as e: print(f"[{self.window_name}] 时间格式化错误 '{time_str}': {e}") return time_str def check_window( self, window_config: dict, check_once_per_day_func=None, record_func=None, ) -> Tuple[bool, str]: if not window_config.get("ENABLED", False): return True, "窗口控制未启用" time_range = window_config.get("TIME_RANGE", {}) start_time = time_range.get("START", "00:00") end_time = time_range.get("END", "23:59") # 检查时间范围 if not self.is_in_time_range(start_time, end_time): now = self.get_time_func() return False, f"当前时间 {now.strftime('%H:%M')} 不在窗口 {start_time}-{end_time} 内" # 检查 once_per_day if window_config.get("ONCE_PER_DAY", False) and check_once_per_day_func: if check_once_per_day_func(): return False, "今天已执行过" else: print(f"[{self.window_name}] 今天首次执行") return True, "在窗口内" def get_status(self, window_config: dict, check_once_per_day_func=None) -> dict: now = self.get_time_func() status = { "enabled": window_config.get("ENABLED", False), "current_time": now.strftime("%H:%M:%S"), "current_date": now.strftime("%Y-%m-%d"), "timezone": str(now.tzinfo), } if status["enabled"]: time_range = window_config.get("TIME_RANGE", {}) status["window_start"] = time_range.get("START", "00:00") status["window_end"] = time_range.get("END", "23:59") status["in_window"] = self.is_in_time_range( status["window_start"], status["window_end"] ) status["once_per_day"] = window_config.get("ONCE_PER_DAY", False) if status["once_per_day"] and check_once_per_day_func: status["executed_today"] = check_once_per_day_func() return status
--- +++ @@ -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: + timezone: 时区名称,如 'Asia/Shanghai', 'America/Los_Angeles' + + Returns: + 带时区信息的当前时间 + """ try: tz = pytz.timezone(timezone) except pytz.UnknownTimeZoneError: @@ -21,20 +35,59 @@ def format_date_folder( date: Optional[str] = None, timezone: str = DEFAULT_TIMEZONE ) -> str: + """ + 格式化日期文件夹名 (ISO 格式: YYYY-MM-DD) + + Args: + date: 指定日期字符串,为 None 则使用当前日期 + timezone: 时区名称 + + Returns: + 格式化后的日期字符串,如 '2025-12-09' + """ if date: return date return get_configured_time(timezone).strftime("%Y-%m-%d") def format_time_filename(timezone: str = DEFAULT_TIMEZONE) -> str: + """ + 格式化时间文件名 (格式: HH-MM,用于文件名) + + Windows 系统不支持冒号作为文件名,因此使用连字符 + + Args: + timezone: 时区名称 + + Returns: + 格式化后的时间字符串,如 '15-30' + """ return get_configured_time(timezone).strftime("%H-%M") def get_current_time_display(timezone: str = DEFAULT_TIMEZONE) -> str: + """ + 获取当前时间显示 (格式: HH:MM,用于显示) + + Args: + timezone: 时区名称 + + Returns: + 格式化后的时间字符串,如 '15:30' + """ return get_configured_time(timezone).strftime("%H:%M") def convert_time_for_display(time_str: str) -> str: + """ + 将 HH-MM 格式转换为 HH:MM 格式用于显示 + + Args: + time_str: 输入时间字符串,如 '15-30' + + Returns: + 转换后的时间字符串,如 '15:30' + """ if time_str and "-" in time_str and len(time_str) == 5: return time_str.replace("-", ":") return time_str @@ -45,6 +98,17 @@ timezone: str = DEFAULT_TIMEZONE, include_date: bool = True, ) -> str: + """ + 将 ISO 格式时间转换为用户时区的友好显示格式 + + Args: + iso_time: ISO 格式时间字符串,如 '2025-12-29T00:20:00' 或 '2025-12-29T00:20:00+00:00' + timezone: 目标时区名称 + include_date: 是否包含日期部分 + + Returns: + 友好格式的时间字符串,如 '12-29 08:20' 或 '08:20' + """ if not iso_time: return "" @@ -113,6 +177,22 @@ max_days: int, timezone: str = DEFAULT_TIMEZONE, ) -> bool: + """ + 检查 ISO 格式时间是否在指定天数内 + + 用于 RSS 文章新鲜度过滤,判断文章发布时间是否超过指定天数。 + + Args: + iso_time: ISO 格式时间字符串(如 '2025-12-29T00:20:00' 或带时区) + max_days: 最大天数(文章发布时间距今不超过此天数则返回 True) + - max_days > 0: 正常过滤,保留 N 天内的文章 + - max_days <= 0: 禁用过滤,保留所有文章 + timezone: 时区名称(用于获取当前时间) + + Returns: + True 如果时间在指定天数内(应保留),False 如果超过指定天数(应过滤) + 如果无法解析时间,返回 True(保留文章) + """ # 无时间戳或禁用过滤时,保留文章 if not iso_time: return True @@ -160,6 +240,16 @@ def calculate_days_old(iso_time: str, timezone: str = DEFAULT_TIMEZONE) -> Optional[float]: + """ + 计算 ISO 格式时间距今多少天 + + Args: + iso_time: ISO 格式时间字符串 + timezone: 时区名称 + + Returns: + 距今天数(浮点数),如果无法解析返回 None + """ if not iso_time: return None @@ -197,6 +287,14 @@ class TimeWindowChecker: + """ + 时间窗口检查器 + + 统一管理时间窗口控制逻辑,支持: + - 推送窗口控制 (push_window) + - AI 分析窗口控制 (analysis_window) + - once_per_day 功能 + """ def __init__( self, @@ -204,11 +302,33 @@ get_time_func=None, window_name: str = "时间窗口", ): + """ + 初始化时间窗口检查器 + + Args: + storage_backend: 存储后端实例 + get_time_func: 获取当前时间的函数 + window_name: 窗口名称(用于日志输出) + """ self.storage_backend = storage_backend self.get_time_func = get_time_func or (lambda: get_configured_time(DEFAULT_TIMEZONE)) self.window_name = window_name def is_in_time_range(self, start_time: str, end_time: str) -> bool: + """ + 检查当前时间是否在指定时间范围内 + + 支持跨日时间窗口,例如: + - 正常窗口:09:00-21:00(当天 9 点到 21 点) + - 跨日窗口:22:00-02:00(当天 22 点到次日 2 点) + + Args: + start_time: 开始时间(格式:HH:MM) + end_time: 结束时间(格式:HH:MM) + + Returns: + 是否在时间范围内 + """ now = self.get_time_func() current_time = now.strftime("%H:%M") @@ -231,6 +351,7 @@ return result def _normalize_time(self, time_str: str) -> str: + """将时间字符串标准化为 HH:MM 格式""" try: parts = time_str.strip().split(":") if len(parts) != 2: @@ -253,6 +374,22 @@ check_once_per_day_func=None, record_func=None, ) -> Tuple[bool, str]: + """ + 统一的时间窗口检查逻辑 + + Args: + window_config: 窗口配置字典,包含: + - ENABLED: 是否启用窗口控制 + - TIME_RANGE: {"START": "HH:MM", "END": "HH:MM"} + - ONCE_PER_DAY: 是否每天只执行一次 + check_once_per_day_func: 检查今天是否已执行的函数 + record_func: 记录执行的函数(成功后调用) + + Returns: + (should_proceed, reason) 元组: + - should_proceed: 是否应该继续执行 + - reason: 原因说明 + """ if not window_config.get("ENABLED", False): return True, "窗口控制未启用" @@ -275,6 +412,16 @@ return True, "在窗口内" def get_status(self, window_config: dict, check_once_per_day_func=None) -> dict: + """ + 获取窗口状态信息 + + Args: + window_config: 窗口配置 + check_once_per_day_func: 检查今天是否已执行的函数 + + Returns: + 状态信息字典 + """ now = self.get_time_func() status = { "enabled": window_config.get("ENABLED", False), @@ -295,4 +442,4 @@ if status["once_per_day"] and check_once_per_day_func: status["executed_today"] = check_once_per_day_func() - return status+ return status
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, format_iso_time_friendly, is_within_days, ) from trendradar.core import ( load_frequency_words, matches_word_groups, read_all_today_titles, detect_latest_new_titles, count_word_frequency, Scheduler, ) from trendradar.report import ( prepare_report_data, generate_html_report, render_html_content, ) from trendradar.notification import ( render_feishu_content, render_dingtalk_content, split_content_into_batches, NotificationDispatcher, ) from trendradar.ai import AITranslator from trendradar.ai.filter import AIFilter, AIFilterResult from trendradar.storage import get_storage_manager class AppContext: def __init__(self, config: Dict[str, Any]): self.config = config self._storage_manager = None self._scheduler = None # === 配置访问 === @property def timezone(self) -> str: return self.config.get("TIMEZONE", DEFAULT_TIMEZONE) @property def rank_threshold(self) -> int: return self.config.get("RANK_THRESHOLD", 50) @property def weight_config(self) -> Dict: return self.config.get("WEIGHT_CONFIG", {}) @property def platforms(self) -> List[Dict]: return self.config.get("PLATFORMS", []) @property def platform_ids(self) -> List[str]: return [p["id"] for p in self.platforms] @property def rss_config(self) -> Dict: return self.config.get("RSS", {}) @property def rss_enabled(self) -> bool: return self.rss_config.get("ENABLED", False) @property def rss_feeds(self) -> List[Dict]: return self.rss_config.get("FEEDS", []) @property def display_mode(self) -> str: return self.config.get("DISPLAY_MODE", "keyword") @property def show_new_section(self) -> bool: return self.config.get("DISPLAY", {}).get("REGIONS", {}).get("NEW_ITEMS", True) @property def region_order(self) -> List[str]: default_order = ["hotlist", "rss", "new_items", "standalone", "ai_analysis"] return self.config.get("DISPLAY", {}).get("REGION_ORDER", default_order) @property def filter_method(self) -> str: return self.config.get("FILTER", {}).get("METHOD", "keyword") @property def ai_priority_sort_enabled(self) -> bool: return self.config.get("FILTER", {}).get("PRIORITY_SORT_ENABLED", False) @property def ai_filter_config(self) -> Dict: return self.config.get("AI_FILTER", {}) @property def ai_filter_enabled(self) -> bool: return self.filter_method == "ai" # === 时间操作 === def get_time(self) -> datetime: return get_configured_time(self.timezone) def format_date(self) -> str: return format_date_folder(timezone=self.timezone) def format_time(self) -> str: return format_time_filename(self.timezone) def get_time_display(self) -> str: return get_current_time_display(self.timezone) @staticmethod def convert_time_display(time_str: str) -> str: return convert_time_for_display(time_str) # === 存储操作 === def get_storage_manager(self): if self._storage_manager is None: storage_config = self.config.get("STORAGE", {}) remote_config = storage_config.get("REMOTE", {}) local_config = storage_config.get("LOCAL", {}) pull_config = storage_config.get("PULL", {}) self._storage_manager = get_storage_manager( backend_type=storage_config.get("BACKEND", "auto"), data_dir=local_config.get("DATA_DIR", "output"), enable_txt=storage_config.get("FORMATS", {}).get("TXT", True), enable_html=storage_config.get("FORMATS", {}).get("HTML", True), remote_config={ "bucket_name": remote_config.get("BUCKET_NAME", ""), "access_key_id": remote_config.get("ACCESS_KEY_ID", ""), "secret_access_key": remote_config.get("SECRET_ACCESS_KEY", ""), "endpoint_url": remote_config.get("ENDPOINT_URL", ""), "region": remote_config.get("REGION", ""), }, local_retention_days=local_config.get("RETENTION_DAYS", 0), remote_retention_days=remote_config.get("RETENTION_DAYS", 0), pull_enabled=pull_config.get("ENABLED", False), pull_days=pull_config.get("DAYS", 7), timezone=self.timezone, ) return self._storage_manager def get_output_path(self, subfolder: str, filename: str) -> str: output_dir = Path("output") / subfolder / self.format_date() output_dir.mkdir(parents=True, exist_ok=True) return str(output_dir / filename) # === 数据处理 === def read_today_titles( self, platform_ids: Optional[List[str]] = None, quiet: bool = False ) -> Tuple[Dict, Dict, Dict]: return read_all_today_titles(self.get_storage_manager(), platform_ids, quiet=quiet) def detect_new_titles( self, platform_ids: Optional[List[str]] = None, quiet: bool = False ) -> Dict: return detect_latest_new_titles(self.get_storage_manager(), platform_ids, quiet=quiet) def is_first_crawl(self) -> bool: return self.get_storage_manager().is_first_crawl_today() # === 频率词处理 === def load_frequency_words( self, frequency_file: Optional[str] = None ) -> Tuple[List[Dict], List[str], List[str]]: return load_frequency_words(frequency_file) def matches_word_groups( self, title: str, word_groups: List[Dict], filter_words: List[str], global_filters: Optional[List[str]] = None, ) -> bool: return matches_word_groups(title, word_groups, filter_words, global_filters) # === 统计分析 === def count_frequency( self, results: Dict, word_groups: List[Dict], filter_words: List[str], id_to_name: Dict, title_info: Optional[Dict] = None, new_titles: Optional[Dict] = None, mode: str = "daily", global_filters: Optional[List[str]] = None, quiet: bool = False, ) -> Tuple[List[Dict], int]: return count_word_frequency( results=results, word_groups=word_groups, filter_words=filter_words, id_to_name=id_to_name, title_info=title_info, rank_threshold=self.rank_threshold, new_titles=new_titles, mode=mode, global_filters=global_filters, weight_config=self.weight_config, max_news_per_keyword=self.config.get("MAX_NEWS_PER_KEYWORD", 0), sort_by_position_first=self.config.get("SORT_BY_POSITION_FIRST", False), is_first_crawl_func=self.is_first_crawl, convert_time_func=self.convert_time_display, quiet=quiet, ) # === 报告生成 === def prepare_report( self, stats: List[Dict], failed_ids: Optional[List] = None, new_titles: Optional[Dict] = None, id_to_name: Optional[Dict] = None, mode: str = "daily", frequency_file: Optional[str] = None, ) -> Dict: return prepare_report_data( stats=stats, failed_ids=failed_ids, new_titles=new_titles, id_to_name=id_to_name, mode=mode, rank_threshold=self.rank_threshold, matches_word_groups_func=self.matches_word_groups, load_frequency_words_func=lambda: self.load_frequency_words(frequency_file), show_new_section=self.show_new_section, ) def generate_html( self, stats: List[Dict], total_titles: int, failed_ids: Optional[List] = None, new_titles: Optional[Dict] = None, id_to_name: Optional[Dict] = None, mode: str = "daily", update_info: Optional[Dict] = None, rss_items: Optional[List[Dict]] = None, rss_new_items: Optional[List[Dict]] = None, ai_analysis: Optional[Any] = None, standalone_data: Optional[Dict] = None, frequency_file: Optional[str] = None, ) -> str: return generate_html_report( stats=stats, total_titles=total_titles, failed_ids=failed_ids, new_titles=new_titles, id_to_name=id_to_name, mode=mode, update_info=update_info, rank_threshold=self.rank_threshold, output_dir="output", date_folder=self.format_date(), time_filename=self.format_time(), render_html_func=lambda *args, **kwargs: self.render_html(*args, rss_items=rss_items, rss_new_items=rss_new_items, ai_analysis=ai_analysis, standalone_data=standalone_data, **kwargs), matches_word_groups_func=self.matches_word_groups, load_frequency_words_func=lambda: self.load_frequency_words(frequency_file), ) def render_html( self, report_data: Dict, total_titles: int, mode: str = "daily", update_info: Optional[Dict] = None, rss_items: Optional[List[Dict]] = None, rss_new_items: Optional[List[Dict]] = None, ai_analysis: Optional[Any] = None, standalone_data: Optional[Dict] = None, ) -> str: return render_html_content( report_data=report_data, total_titles=total_titles, mode=mode, update_info=update_info, region_order=self.region_order, get_time_func=self.get_time, rss_items=rss_items, rss_new_items=rss_new_items, display_mode=self.display_mode, ai_analysis=ai_analysis, show_new_section=self.show_new_section, standalone_data=standalone_data, ) # === 通知内容渲染 === def render_feishu( self, report_data: Dict, update_info: Optional[Dict] = None, mode: str = "daily", ) -> str: return render_feishu_content( report_data=report_data, update_info=update_info, mode=mode, separator=self.config.get("FEISHU_MESSAGE_SEPARATOR", "---"), region_order=self.region_order, get_time_func=self.get_time, show_new_section=self.show_new_section, ) def render_dingtalk( self, report_data: Dict, update_info: Optional[Dict] = None, mode: str = "daily", ) -> str: return render_dingtalk_content( report_data=report_data, update_info=update_info, mode=mode, region_order=self.region_order, get_time_func=self.get_time, show_new_section=self.show_new_section, ) def split_content( self, report_data: Dict, format_type: str, update_info: Optional[Dict] = None, max_bytes: Optional[int] = None, mode: str = "daily", rss_items: Optional[list] = None, rss_new_items: Optional[list] = None, ai_content: Optional[str] = None, standalone_data: Optional[Dict] = None, ai_stats: Optional[Dict] = None, report_type: str = "热点分析报告", ) -> List[str]: return split_content_into_batches( report_data=report_data, format_type=format_type, update_info=update_info, max_bytes=max_bytes, mode=mode, batch_sizes={ "dingtalk": self.config.get("DINGTALK_BATCH_SIZE", 20000), "feishu": self.config.get("FEISHU_BATCH_SIZE", 29000), "default": self.config.get("MESSAGE_BATCH_SIZE", 4000), }, feishu_separator=self.config.get("FEISHU_MESSAGE_SEPARATOR", "---"), region_order=self.region_order, get_time_func=self.get_time, rss_items=rss_items, rss_new_items=rss_new_items, timezone=self.config.get("TIMEZONE", DEFAULT_TIMEZONE), display_mode=self.display_mode, ai_content=ai_content, standalone_data=standalone_data, rank_threshold=self.rank_threshold, ai_stats=ai_stats, report_type=report_type, show_new_section=self.show_new_section, ) # === 通知发送 === def create_notification_dispatcher(self) -> NotificationDispatcher: # 创建翻译器(如果启用) translator = None trans_config = self.config.get("AI_TRANSLATION", {}) if trans_config.get("ENABLED", False): ai_config = self.config.get("AI", {}) translator = AITranslator(trans_config, ai_config) return NotificationDispatcher( config=self.config, get_time_func=self.get_time, split_content_func=self.split_content, translator=translator, ) def create_scheduler(self) -> Scheduler: if self._scheduler is None: schedule_config = self.config.get("SCHEDULE", {}) timeline_data = self.config.get("_TIMELINE_DATA", {}) self._scheduler = Scheduler( schedule_config=schedule_config, timeline_data=timeline_data, storage_backend=self.get_storage_manager(), get_time_func=self.get_time, fallback_report_mode=self.config.get("REPORT_MODE", "current"), ) return self._scheduler # === AI 智能筛选 === @staticmethod def _with_ordered_priorities(tags: List[Dict], start_priority: int = 1) -> List[Dict]: normalized: List[Dict] = [] priority = start_priority for tag_data in tags: if not isinstance(tag_data, dict): continue tag_name = str(tag_data.get("tag", "")).strip() if not tag_name: continue item = dict(tag_data) item["tag"] = tag_name item["priority"] = priority normalized.append(item) priority += 1 return normalized def run_ai_filter(self, interests_file: Optional[str] = None) -> Optional[AIFilterResult]: if not self.ai_filter_enabled: return None filter_config = self.ai_filter_config ai_config = self.config.get("AI", {}) debug = self.config.get("DEBUG", False) # 创建 AIFilter 实例 ai_filter = AIFilter(ai_config, filter_config, self.get_time, debug) # 确定实际使用的兴趣文件名 # None = 使用默认 config/ai_interests.txt,指定文件名 = config/custom/ai/{name} configured_interests = interests_file or filter_config.get("INTERESTS_FILE") effective_interests_file = configured_interests or "ai_interests.txt" if debug: print(f"[AI筛选][DEBUG] === 配置信息 ===") print(f"[AI筛选][DEBUG] 存储后端: {self.get_storage_manager().backend_name}") print(f"[AI筛选][DEBUG] batch_size={filter_config.get('BATCH_SIZE', 200)}, " f"batch_interval={filter_config.get('BATCH_INTERVAL', 5)}") print(f"[AI筛选][DEBUG] interests_file={effective_interests_file}") print(f"[AI筛选][DEBUG] prompt_file={filter_config.get('PROMPT_FILE', 'prompt.txt')}") print(f"[AI筛选][DEBUG] extract_prompt_file={filter_config.get('EXTRACT_PROMPT_FILE', 'extract_prompt.txt')}") # 1. 读取兴趣描述 # 传 configured_interests(可能为 None)给 load_interests_content, # 让它区分"默认文件(config/ai_interests.txt)"和"自定义文件(config/custom/ai/)" interests_content = ai_filter.load_interests_content(configured_interests) if not interests_content: return AIFilterResult(success=False, error="兴趣描述文件为空或不存在") current_hash = ai_filter.compute_interests_hash(interests_content, effective_interests_file) storage = self.get_storage_manager() if debug: print(f"[AI筛选][DEBUG] 兴趣描述 hash: {current_hash}") print(f"[AI筛选][DEBUG] 兴趣描述内容 ({len(interests_content)} 字符):\n{interests_content}") # 2. 开启批量模式(远程后端延迟上传,所有写操作完成后统一上传) storage.begin_batch() # 3. 检查提示词是否变更 stored_hash = storage.get_latest_prompt_hash(interests_file=effective_interests_file) if debug: print(f"[AI筛选][DEBUG] 数据库存储 hash: {stored_hash}") print(f"[AI筛选][DEBUG] hash 对比: stored={stored_hash} vs current={current_hash} → {'匹配' if stored_hash == current_hash else '不匹配'}") if stored_hash != current_hash: new_version = storage.get_latest_ai_filter_tag_version() + 1 threshold = filter_config.get("RECLASSIFY_THRESHOLD", 0.6) if stored_hash is None: # 首次运行,直接提取并保存全部标签 print(f"[AI筛选] 首次运行 ({effective_interests_file}),提取标签...") tags_data = ai_filter.extract_tags(interests_content) if not tags_data: storage.end_batch() return AIFilterResult(success=False, error="标签提取失败") tags_data = self._with_ordered_priorities(tags_data, start_priority=1) saved_count = storage.save_ai_filter_tags(tags_data, new_version, current_hash, interests_file=effective_interests_file) print(f"[AI筛选] 已保存 {saved_count} 个标签 (版本 {new_version})") else: # 兴趣描述已变更,让 AI 对比旧标签和新兴趣,给出更新方案 old_tags = storage.get_active_ai_filter_tags(interests_file=effective_interests_file) update_result = ai_filter.update_tags(old_tags, interests_content) if update_result is None: # AI 标签更新失败,回退到重新提取全部标签 print(f"[AI筛选] AI 标签更新失败,回退到重新提取") tags_data = ai_filter.extract_tags(interests_content) if not tags_data: storage.end_batch() return AIFilterResult(success=False, error="标签提取失败") tags_data = self._with_ordered_priorities(tags_data, start_priority=1) deprecated_count = storage.deprecate_all_ai_filter_tags(interests_file=effective_interests_file) storage.clear_analyzed_news(interests_file=effective_interests_file) saved_count = storage.save_ai_filter_tags(tags_data, new_version, current_hash, interests_file=effective_interests_file) print(f"[AI筛选] 废弃 {deprecated_count} 个旧标签, 保存 {saved_count} 个新标签 (版本 {new_version})") else: change_ratio = update_result["change_ratio"] keep_tags = update_result["keep"] add_tags = update_result["add"] remove_tags = update_result["remove"] if debug: print(f"[AI筛选][DEBUG] AI 标签更新: keep={len(keep_tags)}, add={len(add_tags)}, remove={len(remove_tags)}, change_ratio={change_ratio:.2f}, threshold={threshold:.2f}") if change_ratio >= threshold: # 全量重分类:废弃所有旧标签,用 extract_tags 重新提取 print(f"[AI筛选] 兴趣文件变更: {effective_interests_file} (AI change_ratio={change_ratio:.2f} >= threshold={threshold:.2f} → 全量重分类)") tags_data = ai_filter.extract_tags(interests_content) if not tags_data: storage.end_batch() return AIFilterResult(success=False, error="标签提取失败") tags_data = self._with_ordered_priorities(tags_data, start_priority=1) deprecated_count = storage.deprecate_all_ai_filter_tags(interests_file=effective_interests_file) storage.clear_analyzed_news(interests_file=effective_interests_file) saved_count = storage.save_ai_filter_tags(tags_data, new_version, current_hash, interests_file=effective_interests_file) print(f"[AI筛选] 废弃 {deprecated_count} 个旧标签, 保存 {saved_count} 个新标签 (版本 {new_version})") else: # 增量更新:按 AI 指示操作 print(f"[AI筛选] 兴趣文件变更: {effective_interests_file} (AI change_ratio={change_ratio:.2f} < threshold={threshold:.2f} → 增量更新)") print(f"[AI筛选] 保留 {len(keep_tags)} 个标签, 新增 {len(add_tags)} 个, 废弃 {len(remove_tags)} 个") # 废弃 AI 标记移除的标签 if remove_tags: remove_set = set(remove_tags) removed_ids = [t["id"] for t in old_tags if t["tag"] in remove_set] if removed_ids: storage.deprecate_specific_ai_filter_tags(removed_ids) if debug: print(f"[AI筛选][DEBUG] 废弃标签 IDs: {removed_ids}") # 更新保留标签的描述 keep_with_priority = [] if keep_tags: storage.update_ai_filter_tag_descriptions(keep_tags, interests_file=effective_interests_file) keep_with_priority = self._with_ordered_priorities(keep_tags, start_priority=1) storage.update_ai_filter_tag_priorities(keep_with_priority, interests_file=effective_interests_file) # 保存新增标签 if add_tags: add_start = keep_with_priority[-1]["priority"] + 1 if keep_with_priority else 1 add_with_priority = self._with_ordered_priorities(add_tags, start_priority=add_start) saved_count = storage.save_ai_filter_tags(add_with_priority, new_version, current_hash, interests_file=effective_interests_file) if debug: print(f"[AI筛选][DEBUG] 新增保存 {saved_count} 个标签") # 更新保留标签的 hash(标记为已处理) storage.update_ai_filter_tags_hash(effective_interests_file, current_hash) # 增量更新:清除不匹配新闻的分析记录,让它们有机会被新标签集重新分析 if add_tags: cleared = storage.clear_unmatched_analyzed_news(interests_file=effective_interests_file) if cleared > 0: print(f"[AI筛选] 清除 {cleared} 条不匹配记录,将在新标签下重新分析") # 3. 获取当前 active 标签 active_tags = storage.get_active_ai_filter_tags(interests_file=effective_interests_file) if debug: print(f"[AI筛选][DEBUG] 从数据库获取 active 标签: {len(active_tags)} 个") for t in active_tags: print(f"[AI筛选][DEBUG] id={t['id']} tag={t['tag']} priority={t.get('priority', 9999)} version={t.get('version')} hash={t.get('prompt_hash', '')[:8]}...") if not active_tags: storage.end_batch() return AIFilterResult(success=False, error="没有可用的标签") print(f"[AI筛选] 使用 {len(active_tags)} 个标签") # 4. 收集待分类新闻 # 热榜 all_news = storage.get_all_news_ids() analyzed_hotlist = storage.get_analyzed_news_ids("hotlist", interests_file=effective_interests_file) pending_news = [n for n in all_news if n["id"] not in analyzed_hotlist] # RSS(先做新鲜度过滤,再去除已分类的) pending_rss = [] freshness_filtered_rss = 0 if self.rss_enabled: all_rss = storage.get_all_rss_ids() # 应用新鲜度过滤(与推送阶段一致) rss_config = self.rss_config freshness_config = rss_config.get("FRESHNESS_FILTER", {}) freshness_enabled = freshness_config.get("ENABLED", True) default_max_age_days = freshness_config.get("MAX_AGE_DAYS", 3) timezone = self.config.get("TIMEZONE", DEFAULT_TIMEZONE) # 构建 feed_id -> max_age_days 的映射 feed_max_age_map = {} for feed_cfg in self.rss_feeds: feed_id = feed_cfg.get("id", "") max_age = feed_cfg.get("max_age_days") if max_age is not None: try: feed_max_age_map[feed_id] = int(max_age) except (ValueError, TypeError): pass fresh_rss = [] for n in all_rss: published_at = n.get("published_at", "") feed_id = n.get("source_id", "") max_days = feed_max_age_map.get(feed_id, default_max_age_days) if freshness_enabled and max_days > 0 and published_at: if not is_within_days(published_at, max_days, timezone): freshness_filtered_rss += 1 continue fresh_rss.append(n) analyzed_rss = storage.get_analyzed_news_ids("rss", interests_file=effective_interests_file) pending_rss = [n for n in fresh_rss if n["id"] not in analyzed_rss] # 始终打印总量/已分析/待分析 的详细数据 hotlist_total = len(all_news) hotlist_skipped = len(analyzed_hotlist) hotlist_pending = len(pending_news) print(f"[AI筛选] 热榜: 总计 {hotlist_total} 条, 已分析跳过 {hotlist_skipped} 条, 本次发送AI分析 {hotlist_pending} 条") if self.rss_enabled: rss_total = len(all_rss) rss_skipped = len(analyzed_rss) rss_pending = len(pending_rss) freshness_info = f", 新鲜度过滤 {freshness_filtered_rss} 条" if freshness_filtered_rss > 0 else "" print(f"[AI筛选] RSS: 总计 {rss_total} 条{freshness_info}, 已分析跳过 {rss_skipped} 条, 本次发送AI分析 {rss_pending} 条") total_pending = len(pending_news) + len(pending_rss) if total_pending == 0: print("[AI筛选] 没有新增新闻需要分类") # 5. 批量分类 batch_size = filter_config.get("BATCH_SIZE", 200) batch_interval = filter_config.get("BATCH_INTERVAL", 5) total_results = [] batch_count = 0 # 跨热榜和 RSS 的全局批次计数 # 处理热榜 for i in range(0, len(pending_news), batch_size): if batch_count > 0 and batch_interval > 0: import time print(f"[AI筛选] 批次间隔等待 {batch_interval} 秒...") time.sleep(batch_interval) batch = pending_news[i:i + batch_size] titles_for_ai = [ {"id": n["id"], "title": n["title"], "source": n.get("source_name", "")} for n in batch ] batch_results = ai_filter.classify_batch(titles_for_ai, active_tags, interests_content) for r in batch_results: r["source_type"] = "hotlist" total_results.extend(batch_results) batch_count += 1 print(f"[AI筛选] 热榜批次 {i // batch_size + 1}: {len(batch)} 条 → {len(batch_results)} 条匹配") # 处理 RSS for i in range(0, len(pending_rss), batch_size): if batch_count > 0 and batch_interval > 0: import time print(f"[AI筛选] 批次间隔等待 {batch_interval} 秒...") time.sleep(batch_interval) batch = pending_rss[i:i + batch_size] titles_for_ai = [ {"id": n["id"], "title": n["title"], "source": n.get("source_name", "")} for n in batch ] batch_results = ai_filter.classify_batch(titles_for_ai, active_tags, interests_content) for r in batch_results: r["source_type"] = "rss" total_results.extend(batch_results) batch_count += 1 print(f"[AI筛选] RSS 批次 {i // batch_size + 1}: {len(batch)} 条 → {len(batch_results)} 条匹配") # 6. 保存结果 if total_results: saved = storage.save_ai_filter_results(total_results) print(f"[AI筛选] 保存 {saved} 条分类结果") if debug and saved != len(total_results): print(f"[AI筛选][DEBUG] !! 保存数量不一致: 期望 {len(total_results)}, 实际 {saved}(可能有重复记录被跳过)") # 6.5 记录所有已分析的新闻(匹配+不匹配,用于去重) matched_hotlist_ids = {r["news_item_id"] for r in total_results if r.get("source_type") == "hotlist"} matched_rss_ids = {r["news_item_id"] for r in total_results if r.get("source_type") == "rss"} if pending_news: hotlist_ids = [n["id"] for n in pending_news] storage.save_analyzed_news( hotlist_ids, "hotlist", effective_interests_file, current_hash, matched_hotlist_ids ) if pending_rss: rss_ids = [n["id"] for n in pending_rss] storage.save_analyzed_news( rss_ids, "rss", effective_interests_file, current_hash, matched_rss_ids ) if pending_news or pending_rss: total_analyzed = len(pending_news) + len(pending_rss) total_matched = len(matched_hotlist_ids) + len(matched_rss_ids) print(f"[AI筛选] 已记录 {total_analyzed} 条新闻分析状态 (匹配 {total_matched}, 不匹配 {total_analyzed - total_matched})") # 7. 结束批量模式(统一上传数据库到远程存储) storage.end_batch() # 8. 查询并组装返回结果 all_results = storage.get_active_ai_filter_results(interests_file=effective_interests_file) if debug: print(f"[AI筛选][DEBUG] === 最终汇总 ===") print(f"[AI筛选][DEBUG] 数据库 active 分类结果: {len(all_results)} 条") # 按标签统计 tag_counts: dict = {} for r in all_results: tag_name = r.get("tag", "?") src_type = r.get("source_type", "?") key = f"{tag_name}({src_type})" tag_counts[key] = tag_counts.get(key, 0) + 1 for key, count in sorted(tag_counts.items()): print(f"[AI筛选][DEBUG] {key}: {count} 条") return self._build_filter_result(all_results, active_tags, total_pending) def _build_filter_result( self, raw_results: List[Dict], tags: List[Dict], total_processed: int, ) -> AIFilterResult: priority_sort_enabled = self.ai_priority_sort_enabled tag_priority_map = {} for idx, t in enumerate(tags, start=1): tag_name = str(t.get("tag", "")).strip() if isinstance(t, dict) else "" if not tag_name: continue try: tag_priority_map[tag_name] = int(t.get("priority", idx)) except (TypeError, ValueError): tag_priority_map[tag_name] = idx # 按标签分组 tag_groups: Dict[str, Dict] = {} seen_titles: Dict[str, set] = {} # 每个标签下去重 for r in raw_results: tag_name = r["tag"] if tag_name not in tag_groups: raw_priority = r.get("tag_priority", tag_priority_map.get(tag_name, 9999)) try: tag_position = int(raw_priority) except (TypeError, ValueError): tag_position = 9999 tag_groups[tag_name] = { "tag": tag_name, "description": r.get("tag_description", ""), "position": tag_position, "count": 0, "items": [], } seen_titles[tag_name] = set() title = r["title"] if title in seen_titles[tag_name]: continue seen_titles[tag_name].add(title) tag_groups[tag_name]["items"].append({ "title": title, "source_id": r.get("source_id", ""), "source_name": r.get("source_name", ""), "url": r.get("url", ""), "mobile_url": r.get("mobile_url", ""), "rank": r.get("rank", 0), "ranks": r.get("ranks", []), "first_time": r.get("first_time", ""), "last_time": r.get("last_time", ""), "count": r.get("count", 1), "relevance_score": r.get("relevance_score", 0), "source_type": r.get("source_type", "hotlist"), }) tag_groups[tag_name]["count"] += 1 # 根据配置排序:位置优先 / 数量优先 if priority_sort_enabled: sorted_tags = sorted( tag_groups.values(), key=lambda x: (x.get("position", 9999), -x["count"], x["tag"]), ) else: sorted_tags = sorted( tag_groups.values(), key=lambda x: (-x["count"], x.get("position", 9999), x["tag"]), ) total_matched = sum(t["count"] for t in sorted_tags) return AIFilterResult( tags=sorted_tags, total_matched=total_matched, total_processed=total_processed, success=True, ) def convert_ai_filter_to_report_data( self, ai_filter_result: AIFilterResult, mode: str = "daily", new_titles: Optional[Dict] = None, rss_new_urls: Optional[set] = None, ) -> tuple: hotlist_stats = [] rss_stats = [] max_news = self.config.get("MAX_NEWS_PER_KEYWORD", 0) min_score = self.ai_filter_config.get("MIN_SCORE", 0) # current 模式:计算最新时间,只保留当前在榜的热榜新闻 # 与 count_word_frequency(mode="current") 的过滤逻辑对齐 latest_time = None if mode == "current": for tag_data in ai_filter_result.tags: for item in tag_data.get("items", []): if item.get("source_type", "hotlist") == "hotlist": last_time = item.get("last_time", "") if last_time and (latest_time is None or last_time > latest_time): latest_time = last_time if latest_time: print(f"[AI筛选] current 模式:最新时间 {latest_time},过滤已下榜新闻") # RSS 新鲜度过滤配置(与推送阶段一致) rss_config = self.rss_config freshness_config = rss_config.get("FRESHNESS_FILTER", {}) freshness_enabled = freshness_config.get("ENABLED", True) default_max_age_days = freshness_config.get("MAX_AGE_DAYS", 3) timezone = self.config.get("TIMEZONE", DEFAULT_TIMEZONE) feed_max_age_map = {} for feed_cfg in self.rss_feeds: feed_id = feed_cfg.get("id", "") max_age = feed_cfg.get("max_age_days") if max_age is not None: try: feed_max_age_map[feed_id] = int(max_age) except (ValueError, TypeError): pass filtered_count = 0 for tag_data in ai_filter_result.tags: tag_name = tag_data.get("tag", "") items = tag_data.get("items", []) if not items: continue hotlist_titles = [] rss_titles = [] for item in items: source_type = item.get("source_type", "hotlist") # current 模式:跳过已下榜的热榜新闻 if mode == "current" and latest_time and source_type == "hotlist": if item.get("last_time", "") != latest_time: filtered_count += 1 continue # 分数阈值过滤:跳过相关度低于 min_score 的新闻 if min_score > 0: score = item.get("relevance_score", 0) if score < min_score: continue # 构建时间显示 first_time = item.get("first_time", "") last_time = item.get("last_time", "") if source_type == "rss": # RSS 新鲜度过滤:跳过超过 max_age_days 的旧文章 if freshness_enabled and first_time: feed_id = item.get("source_id", "") max_days = feed_max_age_map.get(feed_id, default_max_age_days) if max_days > 0 and not is_within_days(first_time, max_days, timezone): continue # RSS 条目:first_time 是 ISO 格式,用友好格式显示 if first_time: time_display = format_iso_time_friendly(first_time, timezone, include_date=True) else: time_display = "" else: # 热榜条目:使用 [HH:MM ~ HH:MM] 格式(与 keyword 模式一致) if first_time and last_time and first_time != last_time: first_display = convert_time_for_display(first_time) last_display = convert_time_for_display(last_time) time_display = f"[{first_display} ~ {last_display}]" elif first_time: time_display = convert_time_for_display(first_time) else: time_display = "" # 计算 is_new(与 keyword 模式 core/analyzer.py:335-342 对齐) if source_type == "rss": is_new = False if rss_new_urls: item_url = item.get("url", "") is_new = item_url in rss_new_urls if item_url else False else: is_new = False if new_titles: item_source_id = item.get("source_id", "") item_title = item.get("title", "") if item_source_id in new_titles: is_new = item_title in new_titles[item_source_id] # incremental 模式下仅保留本轮新增命中的条目。 # run_ai_filter() 返回的是 active 结果集合,因此这里需要 # 显式过滤掉历史已命中的旧条目,才能与 keyword 模式行为对齐。 if mode == "incremental" and not is_new: continue title_entry = { "title": item.get("title", ""), "source_name": item.get("source_name", ""), "url": item.get("url", ""), "mobile_url": item.get("mobile_url", ""), "ranks": item.get("ranks", []), "rank_threshold": self.rank_threshold, "count": item.get("count", 1), "is_new": is_new, "time_display": time_display, "matched_keyword": tag_name, } if source_type == "rss": rss_titles.append(title_entry) else: hotlist_titles.append(title_entry) if hotlist_titles: if max_news > 0: hotlist_titles = hotlist_titles[:max_news] hotlist_stats.append({ "word": tag_name, "count": len(hotlist_titles), "position": tag_data.get("position", 9999), "titles": hotlist_titles, }) if rss_titles: if max_news > 0: rss_titles = rss_titles[:max_news] rss_stats.append({ "word": tag_name, "count": len(rss_titles), "position": tag_data.get("position", 9999), "titles": rss_titles, }) if mode == "current" and filtered_count > 0: total_kept = sum(s["count"] for s in hotlist_stats) print(f"[AI筛选] current 模式:过滤 {filtered_count} 条已下榜新闻,保留 {total_kept} 条当前在榜") if min_score > 0: hotlist_kept = sum(s["count"] for s in hotlist_stats) rss_kept = sum(s["count"] for s in rss_stats) total_kept = hotlist_kept + rss_kept parts = [f"热榜 {hotlist_kept} 条"] if rss_kept > 0: parts.append(f"RSS {rss_kept} 条") print(f"[AI筛选] 分数过滤:min_score={min_score},保留 {total_kept} 条 score≥{min_score} ({', '.join(parts)})") priority_sort_enabled = self.ai_priority_sort_enabled if priority_sort_enabled: hotlist_stats.sort(key=lambda x: (x.get("position", 9999), -x["count"], x["word"])) rss_stats.sort(key=lambda x: (x.get("position", 9999), -x["count"], x["word"])) else: hotlist_stats.sort(key=lambda x: (-x["count"], x.get("position", 9999), x["word"])) rss_stats.sort(key=lambda x: (-x["count"], x.get("position", 9999), x["word"])) return hotlist_stats, rss_stats # === 资源清理 === def cleanup(self): if self._storage_manager: self._storage_manager.cleanup_old_data() self._storage_manager.cleanup() self._storage_manager = None
--- +++ @@ -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() + ctx = AppContext(config) + + # 时间操作 + now = ctx.get_time() + date_folder = ctx.format_date() + + # 存储操作 + storage = ctx.get_storage_manager() + + # 报告生成 + html = ctx.generate_html_report(stats, total_titles, ...) + """ def __init__(self, config: Dict[str, Any]): + """ + 初始化应用上下文 + + Args: + config: 完整的配置字典 + """ self.config = config self._storage_manager = None self._scheduler = None @@ -49,86 +80,107 @@ @property def timezone(self) -> str: + """获取配置的时区""" return self.config.get("TIMEZONE", DEFAULT_TIMEZONE) @property def rank_threshold(self) -> int: + """获取排名阈值""" return self.config.get("RANK_THRESHOLD", 50) @property def weight_config(self) -> Dict: + """获取权重配置""" return self.config.get("WEIGHT_CONFIG", {}) @property def platforms(self) -> List[Dict]: + """获取平台配置列表""" return self.config.get("PLATFORMS", []) @property def platform_ids(self) -> List[str]: + """获取平台ID列表""" return [p["id"] for p in self.platforms] @property def rss_config(self) -> Dict: + """获取 RSS 配置""" return self.config.get("RSS", {}) @property def rss_enabled(self) -> bool: + """RSS 是否启用""" return self.rss_config.get("ENABLED", False) @property def rss_feeds(self) -> List[Dict]: + """获取 RSS 源列表""" return self.rss_config.get("FEEDS", []) @property def display_mode(self) -> str: + """获取显示模式 (keyword | platform)""" return self.config.get("DISPLAY_MODE", "keyword") @property def show_new_section(self) -> bool: + """是否显示新增热点区域""" return self.config.get("DISPLAY", {}).get("REGIONS", {}).get("NEW_ITEMS", True) @property def region_order(self) -> List[str]: + """获取区域显示顺序""" default_order = ["hotlist", "rss", "new_items", "standalone", "ai_analysis"] return self.config.get("DISPLAY", {}).get("REGION_ORDER", default_order) @property def filter_method(self) -> str: + """获取筛选策略: keyword | ai""" return self.config.get("FILTER", {}).get("METHOD", "keyword") @property def ai_priority_sort_enabled(self) -> bool: + """AI 模式标签排序开关(与 keyword 的 sort_by_position_first 解耦)""" return self.config.get("FILTER", {}).get("PRIORITY_SORT_ENABLED", False) @property def ai_filter_config(self) -> Dict: + """获取 AI 筛选配置""" return self.config.get("AI_FILTER", {}) @property def ai_filter_enabled(self) -> bool: + """AI 筛选是否启用(基于 filter.method 判断)""" return self.filter_method == "ai" # === 时间操作 === def get_time(self) -> datetime: + """获取当前配置时区的时间""" return get_configured_time(self.timezone) def format_date(self) -> str: + """格式化日期文件夹 (YYYY-MM-DD)""" return format_date_folder(timezone=self.timezone) def format_time(self) -> str: + """格式化时间文件名 (HH-MM)""" return format_time_filename(self.timezone) def get_time_display(self) -> str: + """获取时间显示 (HH:MM)""" return get_current_time_display(self.timezone) @staticmethod def convert_time_display(time_str: str) -> str: + """将 HH-MM 转换为 HH:MM""" return convert_time_for_display(time_str) # === 存储操作 === def get_storage_manager(self): + """获取存储管理器(延迟初始化,单例)""" if self._storage_manager is None: storage_config = self.config.get("STORAGE", {}) remote_config = storage_config.get("REMOTE", {}) @@ -156,6 +208,7 @@ return self._storage_manager def get_output_path(self, subfolder: str, filename: str) -> str: + """获取输出路径(扁平化结构:output/类型/日期/文件名)""" output_dir = Path("output") / subfolder / self.format_date() output_dir.mkdir(parents=True, exist_ok=True) return str(output_dir / filename) @@ -165,14 +218,17 @@ def read_today_titles( self, platform_ids: Optional[List[str]] = None, quiet: bool = False ) -> Tuple[Dict, Dict, Dict]: + """读取当天所有标题""" return read_all_today_titles(self.get_storage_manager(), platform_ids, quiet=quiet) def detect_new_titles( self, platform_ids: Optional[List[str]] = None, quiet: bool = False ) -> Dict: + """检测最新批次的新增标题""" return detect_latest_new_titles(self.get_storage_manager(), platform_ids, quiet=quiet) def is_first_crawl(self) -> bool: + """检测是否是当天第一次爬取""" return self.get_storage_manager().is_first_crawl_today() # === 频率词处理 === @@ -180,6 +236,7 @@ def load_frequency_words( self, frequency_file: Optional[str] = None ) -> Tuple[List[Dict], List[str], List[str]]: + """加载频率词配置""" return load_frequency_words(frequency_file) def matches_word_groups( @@ -189,6 +246,7 @@ filter_words: List[str], global_filters: Optional[List[str]] = None, ) -> bool: + """检查标题是否匹配词组规则""" return matches_word_groups(title, word_groups, filter_words, global_filters) # === 统计分析 === @@ -205,6 +263,7 @@ global_filters: Optional[List[str]] = None, quiet: bool = False, ) -> Tuple[List[Dict], int]: + """统计词频""" return count_word_frequency( results=results, word_groups=word_groups, @@ -234,6 +293,7 @@ mode: str = "daily", frequency_file: Optional[str] = None, ) -> Dict: + """准备报告数据""" return prepare_report_data( stats=stats, failed_ids=failed_ids, @@ -261,6 +321,7 @@ standalone_data: Optional[Dict] = None, frequency_file: Optional[str] = None, ) -> str: + """生成HTML报告""" return generate_html_report( stats=stats, total_titles=total_titles, @@ -289,6 +350,7 @@ ai_analysis: Optional[Any] = None, standalone_data: Optional[Dict] = None, ) -> str: + """渲染HTML内容""" return render_html_content( report_data=report_data, total_titles=total_titles, @@ -312,6 +374,7 @@ update_info: Optional[Dict] = None, mode: str = "daily", ) -> str: + """渲染飞书内容""" return render_feishu_content( report_data=report_data, update_info=update_info, @@ -328,6 +391,7 @@ update_info: Optional[Dict] = None, mode: str = "daily", ) -> str: + """渲染钉钉内容""" return render_dingtalk_content( report_data=report_data, update_info=update_info, @@ -351,6 +415,24 @@ ai_stats: Optional[Dict] = None, report_type: str = "热点分析报告", ) -> List[str]: + """分批处理消息内容(支持热榜+RSS合并+AI分析+独立展示区) + + Args: + report_data: 报告数据 + format_type: 格式类型 + update_info: 更新信息 + max_bytes: 最大字节数 + mode: 报告模式 + rss_items: RSS 统计条目列表 + rss_new_items: RSS 新增条目列表 + ai_content: AI 分析内容(已渲染的字符串) + standalone_data: 独立展示区数据 + ai_stats: AI 分析统计数据 + report_type: 报告类型 + + Returns: + 分批后的消息内容列表 + """ return split_content_into_batches( report_data=report_data, format_type=format_type, @@ -380,6 +462,7 @@ # === 通知发送 === def create_notification_dispatcher(self) -> NotificationDispatcher: + """创建通知调度器""" # 创建翻译器(如果启用) translator = None trans_config = self.config.get("AI_TRANSLATION", {}) @@ -395,6 +478,11 @@ ) def create_scheduler(self) -> Scheduler: + """ + 创建调度器(延迟初始化,单例) + + 基于 config.yaml 的 schedule 段 + timeline.yaml 构建。 + """ if self._scheduler is None: schedule_config = self.config.get("SCHEDULE", {}) timeline_data = self.config.get("_TIMELINE_DATA", {}) @@ -412,6 +500,7 @@ @staticmethod def _with_ordered_priorities(tags: List[Dict], start_priority: int = 1) -> List[Dict]: + """按当前列表顺序补齐优先级(值越小优先级越高)""" normalized: List[Dict] = [] priority = start_priority for tag_data in tags: @@ -428,6 +517,22 @@ return normalized def run_ai_filter(self, interests_file: Optional[str] = None) -> Optional[AIFilterResult]: + """ + 执行 AI 智能筛选完整流程 + + Args: + interests_file: 兴趣描述文件名(位于 config/custom/ai/),None=使用默认 config/ai_interests.txt + + 1. 读取兴趣描述文件,计算 hash + 2. 对比数据库 prompt_hash,决定是否重新提取标签 + 3. 收集待分类新闻(去重) + 4. 按 batch_size 分组调用 AI 分类 + 5. 保存结果 + 6. 查询 active 结果,按标签分组返回 + + Returns: + AIFilterResult 或 None(未启用或出错) + """ if not self.ai_filter_enabled: return None @@ -738,6 +843,7 @@ tags: List[Dict], total_processed: int, ) -> AIFilterResult: + """将数据库查询结果组装为 AIFilterResult""" priority_sort_enabled = self.ai_priority_sort_enabled tag_priority_map = {} for idx, t in enumerate(tags, start=1): @@ -819,6 +925,24 @@ new_titles: Optional[Dict] = None, rss_new_urls: Optional[set] = None, ) -> tuple: + """ + 将 AI 筛选结果转换为与关键词匹配相同的数据结构 + + AIFilterResult.tags 中每个 tag 对应一个 "word"(关键词组)。 + tag.items 中 source_type="hotlist" 的条目进入热榜 stats, + source_type="rss" 的条目进入 rss_items stats。 + + Args: + ai_filter_result: AI 筛选结果 + mode: 报告模式 ("daily" | "current" | "incremental") + new_titles: 热榜新增标题 {source_id: {title: data}},用于 is_new 检测 + rss_new_urls: 新增 RSS 条目的 URL 集合,用于 is_new 检测 + + Returns: + (hotlist_stats, rss_stats): + - hotlist_stats: 与 count_word_frequency() 产出格式一致 + - rss_stats: 与 rss_items 格式一致 + """ hotlist_stats = [] rss_stats = [] max_news = self.config.get("MAX_NEWS_PER_KEYWORD", 0) @@ -990,7 +1114,8 @@ # === 资源清理 === def cleanup(self): + """清理资源""" if self._storage_manager: self._storage_manager.cleanup_old_data() self._storage_manager.cleanup() - self._storage_manager = None+ self._storage_manager = None
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 # 是否成功 error: str = "" # 错误信息 @dataclass class BatchTranslationResult: results: List[TranslationResult] = field(default_factory=list) success_count: int = 0 fail_count: int = 0 total_count: int = 0 prompt: str = "" # debug: 发送给 AI 的完整 prompt raw_response: str = "" # debug: AI 原始响应 parsed_count: int = 0 # debug: AI 响应解析出的条目数 class AITranslator: def __init__(self, translation_config: Dict[str, Any], ai_config: Dict[str, Any]): self.translation_config = translation_config self.ai_config = ai_config # 翻译配置 self.enabled = translation_config.get("ENABLED", False) self.target_language = translation_config.get("LANGUAGE", "English") self.scope = translation_config.get("SCOPE", {"HOTLIST": True, "RSS": True, "STANDALONE": True}) # 创建 AI 客户端(基于 LiteLLM) self.client = AIClient(ai_config) # 加载提示词模板 self.system_prompt, self.user_prompt_template = self._load_prompt_template( translation_config.get("PROMPT_FILE", "ai_translation_prompt.txt") ) def _load_prompt_template(self, prompt_file: str) -> tuple: config_dir = Path(__file__).parent.parent.parent / "config" prompt_path = config_dir / prompt_file if not prompt_path.exists(): print(f"[翻译] 提示词文件不存在: {prompt_path}") return "", "" content = prompt_path.read_text(encoding="utf-8") # 解析 [system] 和 [user] 部分 system_prompt = "" user_prompt = "" if "[system]" in content and "[user]" in content: parts = content.split("[user]") system_part = parts[0] user_part = parts[1] if len(parts) > 1 else "" if "[system]" in system_part: system_prompt = system_part.split("[system]")[1].strip() user_prompt = user_part.strip() else: user_prompt = content return system_prompt, user_prompt def translate(self, text: str) -> TranslationResult: result = TranslationResult(original_text=text) if not self.enabled: result.error = "翻译功能未启用" return result if not self.client.api_key: result.error = "未配置 AI API Key" return result if not text or not text.strip(): result.translated_text = text result.success = True return result try: # 构建提示词 user_prompt = self.user_prompt_template user_prompt = user_prompt.replace("{target_language}", self.target_language) user_prompt = user_prompt.replace("{content}", text) # 调用 AI API response = self._call_ai(user_prompt) result.translated_text = response.strip() result.success = True except Exception as e: error_type = type(e).__name__ error_msg = str(e) if len(error_msg) > 100: error_msg = error_msg[:100] + "..." result.error = f"翻译失败 ({error_type}): {error_msg}" return result def translate_batch(self, texts: List[str]) -> BatchTranslationResult: batch_result = BatchTranslationResult(total_count=len(texts)) if not self.enabled: for text in texts: batch_result.results.append(TranslationResult( original_text=text, error="翻译功能未启用" )) batch_result.fail_count = len(texts) return batch_result if not self.client.api_key: for text in texts: batch_result.results.append(TranslationResult( original_text=text, error="未配置 AI API Key" )) batch_result.fail_count = len(texts) return batch_result if not texts: return batch_result # 过滤空文本 non_empty_indices = [] non_empty_texts = [] for i, text in enumerate(texts): if text and text.strip(): non_empty_indices.append(i) non_empty_texts.append(text) # 初始化结果列表 for text in texts: batch_result.results.append(TranslationResult(original_text=text)) # 空文本直接标记成功 for i, text in enumerate(texts): if not text or not text.strip(): batch_result.results[i].translated_text = text batch_result.results[i].success = True batch_result.success_count += 1 if not non_empty_texts: return batch_result try: # 构建批量翻译内容(使用编号格式) batch_content = self._format_batch_content(non_empty_texts) # 构建提示词 user_prompt = self.user_prompt_template user_prompt = user_prompt.replace("{target_language}", self.target_language) user_prompt = user_prompt.replace("{content}", batch_content) # 记录 debug 信息(包含完整的 system + user prompt) if self.system_prompt: batch_result.prompt = f"[system]\n{self.system_prompt}\n\n[user]\n{user_prompt}" else: batch_result.prompt = user_prompt # 调用 AI API response = self._call_ai(user_prompt) # 记录 AI 原始响应 batch_result.raw_response = response # 解析批量翻译结果 translated_texts, raw_parsed_count = self._parse_batch_response(response, len(non_empty_texts)) batch_result.parsed_count = raw_parsed_count # 填充结果 for idx, translated in zip(non_empty_indices, translated_texts): batch_result.results[idx].translated_text = translated batch_result.results[idx].success = True batch_result.success_count += 1 except Exception as e: error_msg = f"批量翻译失败: {type(e).__name__}: {str(e)[:100]}" for idx in non_empty_indices: batch_result.results[idx].error = error_msg batch_result.fail_count = len(non_empty_indices) return batch_result def _format_batch_content(self, texts: List[str]) -> str: lines = [] for i, text in enumerate(texts, 1): lines.append(f"[{i}] {text}") return "\n".join(lines) def _parse_batch_response(self, response: str, expected_count: int) -> tuple: results = [] lines = response.strip().split("\n") current_idx = None current_text = [] for line in lines: # 尝试匹配 [数字] 格式 stripped = line.strip() if stripped.startswith("[") and "]" in stripped: bracket_end = stripped.index("]") try: idx = int(stripped[1:bracket_end]) # 保存之前的内容 if current_idx is not None: results.append((current_idx, "\n".join(current_text).strip())) current_idx = idx current_text = [stripped[bracket_end + 1:].strip()] except ValueError: if current_idx is not None: current_text.append(line) else: if current_idx is not None: current_text.append(line) # 保存最后一条 if current_idx is not None: results.append((current_idx, "\n".join(current_text).strip())) # 按索引排序并提取文本 results.sort(key=lambda x: x[0]) translated = [text for _, text in results] raw_parsed_count = len(translated) # 如果解析结果数量不匹配,尝试简单按行分割 if len(translated) != expected_count: # 回退:按行分割(去除编号) translated = [] for line in lines: stripped = line.strip() if stripped.startswith("[") and "]" in stripped: bracket_end = stripped.index("]") translated.append(stripped[bracket_end + 1:].strip()) elif stripped: translated.append(stripped) raw_parsed_count = len(translated) # 确保返回正确数量 while len(translated) < expected_count: translated.append("") return translated[:expected_count], raw_parsed_count def _call_ai(self, user_prompt: str) -> str: messages = [] if self.system_prompt: messages.append({"role": "system", "content": self.system_prompt}) messages.append({"role": "user", "content": user_prompt}) return self.client.chat(messages)
--- +++ @@ -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 = "" # 原始文本 success: bool = False # 是否成功 @@ -17,6 +24,7 @@ @dataclass class BatchTranslationResult: + """批量翻译结果""" results: List[TranslationResult] = field(default_factory=list) success_count: int = 0 fail_count: int = 0 @@ -27,8 +35,16 @@ class AITranslator: + """AI 翻译器""" def __init__(self, translation_config: Dict[str, Any], ai_config: Dict[str, Any]): + """ + 初始化 AI 翻译器 + + Args: + translation_config: AI 翻译配置 (AI_TRANSLATION) + ai_config: AI 模型配置(LiteLLM 格式) + """ self.translation_config = translation_config self.ai_config = ai_config @@ -46,6 +62,7 @@ ) def _load_prompt_template(self, prompt_file: str) -> tuple: + """加载提示词模板""" config_dir = Path(__file__).parent.parent.parent / "config" prompt_path = config_dir / prompt_file @@ -74,6 +91,15 @@ return system_prompt, user_prompt def translate(self, text: str) -> TranslationResult: + """ + 翻译单条文本 + + Args: + text: 要翻译的文本 + + Returns: + TranslationResult: 翻译结果 + """ result = TranslationResult(original_text=text) if not self.enabled: @@ -110,6 +136,15 @@ return result def translate_batch(self, texts: List[str]) -> BatchTranslationResult: + """ + 批量翻译文本(单次 API 调用) + + Args: + texts: 要翻译的文本列表 + + Returns: + BatchTranslationResult: 批量翻译结果 + """ batch_result = BatchTranslationResult(total_count=len(texts)) if not self.enabled: @@ -195,12 +230,23 @@ return batch_result def _format_batch_content(self, texts: List[str]) -> str: + """格式化批量翻译内容""" lines = [] for i, text in enumerate(texts, 1): lines.append(f"[{i}] {text}") return "\n".join(lines) def _parse_batch_response(self, response: str, expected_count: int) -> tuple: + """ + 解析批量翻译响应 + + Args: + response: AI 响应文本 + expected_count: 期望的翻译数量 + + Returns: + tuple: (翻译结果列表, AI 原始解析出的条目数) + """ results = [] lines = response.strip().split("\n") @@ -255,9 +301,10 @@ return translated[:expected_count], raw_parsed_count def _call_ai(self, user_prompt: str) -> str: + """调用 AI API(使用 LiteLLM)""" messages = [] if self.system_prompt: messages.append({"role": "system", "content": self.system_prompt}) messages.append({"role": "user", "content": user_prompt}) - return self.client.chat(messages)+ return self.client.chat(messages)
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 = "" # 来源平台名称(运行时使用,数据库不存储) rank: int = 0 # 排名 url: str = "" # 链接 URL mobile_url: str = "" # 移动端 URL crawl_time: str = "" # 抓取时间(HH:MM 格式) # 统计信息(用于分析) ranks: List[int] = field(default_factory=list) # 历史排名列表 first_time: str = "" # 首次出现时间 last_time: str = "" # 最后出现时间 count: int = 1 # 出现次数 rank_timeline: List[Dict[str, Any]] = field(default_factory=list) # 完整排名时间线 # 格式: [{"time": "09:30", "rank": 1}, {"time": "10:00", "rank": 2}, ...] # None 表示脱榜: [{"time": "11:00", "rank": None}] def to_dict(self) -> Dict[str, Any]: return { "title": self.title, "source_id": self.source_id, "source_name": self.source_name, "rank": self.rank, "url": self.url, "mobile_url": self.mobile_url, "crawl_time": self.crawl_time, "ranks": self.ranks, "first_time": self.first_time, "last_time": self.last_time, "count": self.count, "rank_timeline": self.rank_timeline, } @classmethod def from_dict(cls, data: Dict[str, Any]) -> "NewsItem": return cls( title=data.get("title", ""), source_id=data.get("source_id", ""), source_name=data.get("source_name", ""), rank=data.get("rank", 0), url=data.get("url", ""), mobile_url=data.get("mobile_url", ""), crawl_time=data.get("crawl_time", ""), ranks=data.get("ranks", []), first_time=data.get("first_time", ""), last_time=data.get("last_time", ""), count=data.get("count", 1), rank_timeline=data.get("rank_timeline", []), ) @dataclass class RSSItem: title: str # 标题 feed_id: str # RSS 源 ID(如 "hacker-news") feed_name: str = "" # RSS 源名称(运行时使用) url: str = "" # 文章链接 published_at: str = "" # RSS 发布时间(ISO 格式) summary: str = "" # 摘要/描述 author: str = "" # 作者 crawl_time: str = "" # 抓取时间(HH:MM 格式) # 统计信息 first_time: str = "" # 首次抓取时间 last_time: str = "" # 最后抓取时间 count: int = 1 # 抓取次数 def to_dict(self) -> Dict[str, Any]: return { "title": self.title, "feed_id": self.feed_id, "feed_name": self.feed_name, "url": self.url, "published_at": self.published_at, "summary": self.summary, "author": self.author, "crawl_time": self.crawl_time, "first_time": self.first_time, "last_time": self.last_time, "count": self.count, } @classmethod def from_dict(cls, data: Dict[str, Any]) -> "RSSItem": return cls( title=data.get("title", ""), feed_id=data.get("feed_id", ""), feed_name=data.get("feed_name", ""), url=data.get("url", ""), published_at=data.get("published_at", ""), summary=data.get("summary", ""), author=data.get("author", ""), crawl_time=data.get("crawl_time", ""), first_time=data.get("first_time", ""), last_time=data.get("last_time", ""), count=data.get("count", 1), ) @dataclass class RSSData: date: str # 日期 crawl_time: str # 抓取时间 items: Dict[str, List[RSSItem]] # 按 feed_id 分组的条目 id_to_name: Dict[str, str] = field(default_factory=dict) # ID到名称映射 failed_ids: List[str] = field(default_factory=list) # 失败的ID def to_dict(self) -> Dict[str, Any]: items_dict = {} for feed_id, rss_list in self.items.items(): items_dict[feed_id] = [item.to_dict() for item in rss_list] return { "date": self.date, "crawl_time": self.crawl_time, "items": items_dict, "id_to_name": self.id_to_name, "failed_ids": self.failed_ids, } @classmethod def from_dict(cls, data: Dict[str, Any]) -> "RSSData": items = {} items_data = data.get("items", {}) for feed_id, rss_list in items_data.items(): items[feed_id] = [RSSItem.from_dict(item) for item in rss_list] return cls( date=data.get("date", ""), crawl_time=data.get("crawl_time", ""), items=items, id_to_name=data.get("id_to_name", {}), failed_ids=data.get("failed_ids", []), ) def get_total_count(self) -> int: return sum(len(rss_list) for rss_list in self.items.values()) @dataclass class NewsData: date: str # 日期 crawl_time: str # 抓取时间 items: Dict[str, List[NewsItem]] # 按来源分组的新闻 id_to_name: Dict[str, str] = field(default_factory=dict) # ID到名称映射 failed_ids: List[str] = field(default_factory=list) # 失败的ID def to_dict(self) -> Dict[str, Any]: items_dict = {} for source_id, news_list in self.items.items(): items_dict[source_id] = [item.to_dict() for item in news_list] return { "date": self.date, "crawl_time": self.crawl_time, "items": items_dict, "id_to_name": self.id_to_name, "failed_ids": self.failed_ids, } @classmethod def from_dict(cls, data: Dict[str, Any]) -> "NewsData": items = {} items_data = data.get("items", {}) for source_id, news_list in items_data.items(): items[source_id] = [NewsItem.from_dict(item) for item in news_list] return cls( date=data.get("date", ""), crawl_time=data.get("crawl_time", ""), items=items, id_to_name=data.get("id_to_name", {}), failed_ids=data.get("failed_ids", []), ) def get_total_count(self) -> int: return sum(len(news_list) for news_list in self.items.values()) def merge_with(self, other: "NewsData") -> "NewsData": merged_items = {} # 复制当前数据 for source_id, news_list in self.items.items(): merged_items[source_id] = {item.title: item for item in news_list} # 合并其他数据 for source_id, news_list in other.items.items(): if source_id not in merged_items: merged_items[source_id] = {} for item in news_list: if item.title in merged_items[source_id]: # 合并已存在的新闻 existing = merged_items[source_id][item.title] # 合并排名 existing_ranks = set(existing.ranks) if existing.ranks else set() new_ranks = set(item.ranks) if item.ranks else set() merged_ranks = sorted(existing_ranks | new_ranks) existing.ranks = merged_ranks # 更新时间 if item.first_time and (not existing.first_time or item.first_time < existing.first_time): existing.first_time = item.first_time if item.last_time and (not existing.last_time or item.last_time > existing.last_time): existing.last_time = item.last_time # 更新计数 existing.count += 1 # 保留URL(如果原来没有) if not existing.url and item.url: existing.url = item.url if not existing.mobile_url and item.mobile_url: existing.mobile_url = item.mobile_url else: # 添加新新闻 merged_items[source_id][item.title] = item # 转换回列表格式 final_items = {} for source_id, items_dict in merged_items.items(): final_items[source_id] = list(items_dict.values()) # 合并 id_to_name merged_id_to_name = {**self.id_to_name, **other.id_to_name} # 合并 failed_ids(去重) merged_failed_ids = list(set(self.failed_ids + other.failed_ids)) return NewsData( date=self.date or other.date, crawl_time=other.crawl_time, # 使用较新的抓取时间 items=final_items, id_to_name=merged_id_to_name, failed_ids=merged_failed_ids, ) class StorageBackend(ABC): @abstractmethod def save_news_data(self, data: NewsData) -> bool: pass @abstractmethod def get_today_all_data(self, date: Optional[str] = None) -> Optional[NewsData]: pass @abstractmethod def get_latest_crawl_data(self, date: Optional[str] = None) -> Optional[NewsData]: pass @abstractmethod def detect_new_titles(self, current_data: NewsData) -> Dict[str, Dict]: pass @abstractmethod def save_txt_snapshot(self, data: NewsData) -> Optional[str]: pass @abstractmethod def save_html_report(self, html_content: str, filename: str) -> Optional[str]: pass @abstractmethod def is_first_crawl_today(self, date: Optional[str] = None) -> bool: pass @abstractmethod def cleanup(self) -> None: pass @abstractmethod def cleanup_old_data(self, retention_days: int) -> int: pass @property @abstractmethod def backend_name(self) -> str: pass @property @abstractmethod def supports_txt(self) -> bool: pass # === 时间段执行记录(调度系统)=== def has_period_executed(self, date_str: str, period_key: str, action: str) -> bool: return False def record_period_execution(self, date_str: str, period_key: str, action: str) -> bool: return False # === AI 智能筛选(默认实现,子类通过 mixin 覆盖) === def begin_batch(self) -> None: pass def end_batch(self) -> None: pass def get_active_ai_filter_tags(self, date: Optional[str] = None, interests_file: str = "ai_interests.txt") -> List[Dict]: return [] def get_latest_prompt_hash(self, date: Optional[str] = None, interests_file: str = "ai_interests.txt") -> Optional[str]: return None def get_latest_ai_filter_tag_version(self, date: Optional[str] = None) -> int: return 0 def deprecate_all_ai_filter_tags(self, date: Optional[str] = None, interests_file: str = "ai_interests.txt") -> int: return 0 def save_ai_filter_tags(self, tags: List[Dict], version: int, prompt_hash: str, date: Optional[str] = None, interests_file: str = "ai_interests.txt") -> int: return 0 def save_ai_filter_results(self, results: List[Dict], date: Optional[str] = None) -> int: return 0 def get_active_ai_filter_results(self, date: Optional[str] = None, interests_file: str = "ai_interests.txt") -> List[Dict]: return [] def deprecate_specific_ai_filter_tags(self, tag_ids: List[int], date: Optional[str] = None) -> int: return 0 def update_ai_filter_tags_hash(self, interests_file: str, new_hash: str, date: Optional[str] = None) -> int: return 0 def update_ai_filter_tag_descriptions(self, tag_updates: List[Dict], date: Optional[str] = None, interests_file: str = "ai_interests.txt") -> int: return 0 def update_ai_filter_tag_priorities(self, tag_priorities: List[Dict], date: Optional[str] = None, interests_file: str = "ai_interests.txt") -> int: return 0 def save_analyzed_news(self, news_ids: List[str], source_type: str, interests_file: str, prompt_hash: str, matched_ids: Set[str], date: Optional[str] = None) -> int: return 0 def get_analyzed_news_ids(self, source_type: str = "hotlist", date: Optional[str] = None, interests_file: str = "ai_interests.txt") -> Set[str]: return set() def clear_analyzed_news(self, date: Optional[str] = None, interests_file: str = "ai_interests.txt") -> int: return 0 def clear_unmatched_analyzed_news(self, date: Optional[str] = None, interests_file: str = "ai_interests.txt") -> int: return 0 def get_all_news_ids(self, date: Optional[str] = None) -> List[Dict]: return [] def get_all_rss_ids(self, date: Optional[str] = None) -> List[Dict]: return [] def convert_crawl_results_to_news_data( results: Dict[str, Dict], id_to_name: Dict[str, str], failed_ids: List[str], crawl_time: str, crawl_date: str, ) -> NewsData: items = {} for source_id, titles_data in results.items(): source_name = id_to_name.get(source_id, source_id) news_list = [] for title, data in titles_data.items(): ranks = data.get("ranks", []) url = data.get("url", "") mobile_url = data.get("mobileUrl", "") rank = ranks[0] if ranks else 99 news_item = NewsItem( title=title, source_id=source_id, source_name=source_name, rank=rank, url=url, mobile_url=mobile_url, crawl_time=crawl_time, ranks=ranks, first_time=crawl_time, last_time=crawl_time, count=1, ) news_list.append(news_item) items[source_id] = news_list return NewsData( date=crawl_date, crawl_time=crawl_time, items=items, id_to_name=id_to_name, failed_ids=failed_ids, )
--- +++ @@ -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 # 来源平台ID(如 toutiao, baidu) @@ -26,6 +32,7 @@ # None 表示脱榜: [{"time": "11:00", "rank": None}] def to_dict(self) -> Dict[str, Any]: + """转换为字典""" return { "title": self.title, "source_id": self.source_id, @@ -43,6 +50,7 @@ @classmethod def from_dict(cls, data: Dict[str, Any]) -> "NewsItem": + """从字典创建""" return cls( title=data.get("title", ""), source_id=data.get("source_id", ""), @@ -61,6 +69,7 @@ @dataclass class RSSItem: + """RSS 条目数据模型""" title: str # 标题 feed_id: str # RSS 源 ID(如 "hacker-news") @@ -77,6 +86,7 @@ count: int = 1 # 抓取次数 def to_dict(self) -> Dict[str, Any]: + """转换为字典""" return { "title": self.title, "feed_id": self.feed_id, @@ -93,6 +103,7 @@ @classmethod def from_dict(cls, data: Dict[str, Any]) -> "RSSItem": + """从字典创建""" return cls( title=data.get("title", ""), feed_id=data.get("feed_id", ""), @@ -110,6 +121,16 @@ @dataclass class RSSData: + """ + RSS 数据集合 + + 结构: + - date: 日期(YYYY-MM-DD) + - crawl_time: 抓取时间(HH:MM) + - items: 按 feed_id 分组的 RSS 条目 + - id_to_name: feed_id 到名称的映射 + - failed_ids: 失败的 feed_id 列表 + """ date: str # 日期 crawl_time: str # 抓取时间 @@ -118,6 +139,7 @@ failed_ids: List[str] = field(default_factory=list) # 失败的ID def to_dict(self) -> Dict[str, Any]: + """转换为字典""" items_dict = {} for feed_id, rss_list in self.items.items(): items_dict[feed_id] = [item.to_dict() for item in rss_list] @@ -132,6 +154,7 @@ @classmethod def from_dict(cls, data: Dict[str, Any]) -> "RSSData": + """从字典创建""" items = {} items_data = data.get("items", {}) for feed_id, rss_list in items_data.items(): @@ -146,11 +169,22 @@ ) def get_total_count(self) -> int: + """获取条目总数""" return sum(len(rss_list) for rss_list in self.items.values()) @dataclass class NewsData: + """ + 新闻数据集合 + + 结构: + - date: 日期(YYYY-MM-DD) + - crawl_time: 抓取时间(HH时MM分) + - items: 按来源ID分组的新闻条目 + - id_to_name: 来源ID到名称的映射 + - failed_ids: 失败的来源ID列表 + """ date: str # 日期 crawl_time: str # 抓取时间 @@ -159,6 +193,7 @@ failed_ids: List[str] = field(default_factory=list) # 失败的ID def to_dict(self) -> Dict[str, Any]: + """转换为字典""" items_dict = {} for source_id, news_list in self.items.items(): items_dict[source_id] = [item.to_dict() for item in news_list] @@ -173,6 +208,7 @@ @classmethod def from_dict(cls, data: Dict[str, Any]) -> "NewsData": + """从字典创建""" items = {} items_data = data.get("items", {}) for source_id, news_list in items_data.items(): @@ -187,9 +223,18 @@ ) def get_total_count(self) -> int: + """获取新闻总数""" return sum(len(news_list) for news_list in self.items.values()) def merge_with(self, other: "NewsData") -> "NewsData": + """ + 合并另一个 NewsData 到当前数据 + + 合并规则: + - 相同 source_id + title 的新闻合并排名历史 + - 更新 last_time 和 count + - 保留较早的 first_time + """ merged_items = {} # 复制当前数据 @@ -251,67 +296,182 @@ class StorageBackend(ABC): + """ + 存储后端抽象基类 + + 所有存储后端都需要实现这些方法,以支持: + - 保存新闻数据 + - 读取当天所有数据 + - 检测新增新闻 + - 生成报告文件(TXT/HTML) + """ @abstractmethod def save_news_data(self, data: NewsData) -> bool: + """ + 保存新闻数据 + + Args: + data: 新闻数据 + + Returns: + 是否保存成功 + """ pass @abstractmethod def get_today_all_data(self, date: Optional[str] = None) -> Optional[NewsData]: + """ + 获取指定日期的所有新闻数据 + + Args: + date: 日期字符串(YYYY-MM-DD),默认为今天 + + Returns: + 合并后的新闻数据,如果没有数据返回 None + """ pass @abstractmethod def get_latest_crawl_data(self, date: Optional[str] = None) -> Optional[NewsData]: + """ + 获取最新一次抓取的数据 + + Args: + date: 日期字符串,默认为今天 + + Returns: + 最新抓取的新闻数据 + """ pass @abstractmethod def detect_new_titles(self, current_data: NewsData) -> Dict[str, Dict]: + """ + 检测新增的标题 + + Args: + current_data: 当前抓取的数据 + + Returns: + 新增的标题数据,格式: {source_id: {title: title_data}} + """ pass @abstractmethod def save_txt_snapshot(self, data: NewsData) -> Optional[str]: + """ + 保存 TXT 快照(可选功能,本地环境可用) + + Args: + data: 新闻数据 + + Returns: + 保存的文件路径,如果不支持返回 None + """ pass @abstractmethod def save_html_report(self, html_content: str, filename: str) -> Optional[str]: + """ + 保存 HTML 报告 + + Args: + html_content: HTML 内容 + filename: 文件名 + + Returns: + 保存的文件路径 + """ pass @abstractmethod def is_first_crawl_today(self, date: Optional[str] = None) -> bool: + """ + 检查是否是当天第一次抓取 + + Args: + date: 日期字符串,默认为今天 + + Returns: + 是否是第一次抓取 + """ pass @abstractmethod def cleanup(self) -> None: + """ + 清理资源(如临时文件、数据库连接等) + """ pass @abstractmethod def cleanup_old_data(self, retention_days: int) -> int: + """ + 清理过期数据 + + Args: + retention_days: 保留天数(0 表示不清理) + + Returns: + 删除的日期目录数量 + """ pass @property @abstractmethod def backend_name(self) -> str: + """ + 存储后端名称 + """ pass @property @abstractmethod def supports_txt(self) -> bool: + """ + 是否支持生成 TXT 快照 + """ pass # === 时间段执行记录(调度系统)=== def has_period_executed(self, date_str: str, period_key: str, action: str) -> bool: + """ + 检查指定时间段的某个 action 是否已执行 + + Args: + date_str: 日期字符串 YYYY-MM-DD + period_key: 时间段 key + action: 动作类型 (analyze / push) + + Returns: + 是否已执行 + """ return False def record_period_execution(self, date_str: str, period_key: str, action: str) -> bool: + """ + 记录时间段的 action 执行 + + Args: + date_str: 日期字符串 YYYY-MM-DD + period_key: 时间段 key + action: 动作类型 (analyze / push) + + Returns: + 是否记录成功 + """ return False # === AI 智能筛选(默认实现,子类通过 mixin 覆盖) === def begin_batch(self) -> None: + """开启批量模式(远程后端延迟上传,本地后端无操作)""" pass def end_batch(self) -> None: + """结束批量模式""" pass def get_active_ai_filter_tags(self, date: Optional[str] = None, interests_file: str = "ai_interests.txt") -> List[Dict]: @@ -373,6 +533,19 @@ crawl_time: str, crawl_date: str, ) -> NewsData: + """ + 将爬虫结果转换为 NewsData 格式 + + Args: + results: 爬虫返回的结果 {source_id: {title: {ranks: [], url: "", mobileUrl: ""}}} + id_to_name: 来源ID到名称的映射 + failed_ids: 失败的来源ID + crawl_time: 抓取时间(HH:MM) + crawl_date: 抓取日期(YYYY-MM-DD) + + Returns: + NewsData 对象 + """ items = {} for source_id, titles_data in results.items(): @@ -409,4 +582,4 @@ items=items, id_to_name=id_to_name, failed_ids=failed_ids, - )+ )
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.api_base = config.get("API_BASE", "") self.temperature = config.get("TEMPERATURE", 1.0) self.max_tokens = config.get("MAX_TOKENS", 5000) self.timeout = config.get("TIMEOUT", 120) self.num_retries = config.get("NUM_RETRIES", 2) self.fallback_models = config.get("FALLBACK_MODELS", []) def chat( self, messages: List[Dict[str, str]], **kwargs ) -> str: # 构建请求参数 params = { "model": self.model, "messages": messages, "temperature": kwargs.get("temperature", self.temperature), "timeout": kwargs.get("timeout", self.timeout), "num_retries": kwargs.get("num_retries", self.num_retries), } # 添加 API Key if self.api_key: params["api_key"] = self.api_key # 添加 API Base(如果配置了) if self.api_base: params["api_base"] = self.api_base # 添加 max_tokens(如果配置了且不为 0) max_tokens = kwargs.get("max_tokens", self.max_tokens) if max_tokens and max_tokens > 0: params["max_tokens"] = max_tokens # 添加 fallback 模型(如果配置了) if self.fallback_models: params["fallbacks"] = self.fallback_models # 合并其他额外参数 for key, value in kwargs.items(): if key not in params: params[key] = value # 调用 LiteLLM response = completion(**params) # 提取响应内容 # 某些模型/提供商返回 list(内容块)而非 str,统一转为 str content = response.choices[0].message.content if isinstance(content, list): content = "\n".join( item.get("text", str(item)) if isinstance(item, dict) else str(item) for item in content ) return content or "" def validate_config(self) -> tuple[bool, str]: if not self.model: return False, "未配置 AI 模型(model)" if not self.api_key: return False, "未配置 AI API Key,请在 config.yaml 或环境变量 AI_API_KEY 中设置" # 验证模型格式(应该包含 provider/model) if "/" not in self.model: return False, f"模型格式错误: {self.model},应为 'provider/model' 格式(如 'deepseek/deepseek-chat')" return True, ""
--- +++ @@ -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]): + """ + 初始化 AI 客户端 + + Args: + config: AI 配置字典 + - MODEL: 模型标识(格式: provider/model_name) + - API_KEY: API 密钥 + - API_BASE: API 基础 URL(可选) + - TEMPERATURE: 采样温度 + - MAX_TOKENS: 最大生成 token 数 + - TIMEOUT: 请求超时时间(秒) + - NUM_RETRIES: 重试次数(可选) + - FALLBACK_MODELS: 备用模型列表(可选) + """ self.model = config.get("MODEL", "deepseek/deepseek-chat") self.api_key = config.get("API_KEY") or os.environ.get("AI_API_KEY", "") self.api_base = config.get("API_BASE", "") @@ -23,6 +44,19 @@ messages: List[Dict[str, str]], **kwargs ) -> str: + """ + 调用 AI 模型进行对话 + + Args: + messages: 消息列表,格式: [{"role": "system/user/assistant", "content": "..."}] + **kwargs: 额外参数,会覆盖默认配置 + + Returns: + str: AI 响应内容 + + Raises: + Exception: API 调用失败时抛出异常 + """ # 构建请求参数 params = { "model": self.model, @@ -68,6 +102,12 @@ return content or "" def validate_config(self) -> tuple[bool, str]: + """ + 验证配置是否有效 + + Returns: + tuple: (是否有效, 错误信息) + """ if not self.model: return False, "未配置 AI 模型(model)" @@ -78,4 +118,4 @@ if "/" not in self.model: return False, f"模型格式错误: {self.model},应为 'provider/model' 格式(如 'deepseek/deepseek-chat')" - return True, ""+ return True, ""
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_info: Optional[Dict] = None, mode: str = "daily", separator: str = "---", region_order: Optional[List[str]] = None, get_time_func: Optional[Callable[[], datetime]] = None, rss_items: Optional[list] = None, show_new_section: bool = True, ) -> str: if region_order is None: region_order = DEFAULT_REGION_ORDER # 生成热点词汇统计部分 stats_content = "" if report_data["stats"]: stats_content += "📊 **热点词汇统计**\n\n" total_count = len(report_data["stats"]) for i, stat in enumerate(report_data["stats"]): word = stat["word"] count = stat["count"] sequence_display = f"<font color='grey'>[{i + 1}/{total_count}]</font>" if count >= 10: stats_content += f"🔥 {sequence_display} **{word}** : <font color='red'>{count}</font> 条\n\n" elif count >= 5: stats_content += f"📈 {sequence_display} **{word}** : <font color='orange'>{count}</font> 条\n\n" else: stats_content += f"📌 {sequence_display} **{word}** : {count} 条\n\n" for j, title_data in enumerate(stat["titles"], 1): formatted_title = format_title_for_platform( "feishu", title_data, show_source=True ) stats_content += f" {j}. {formatted_title}\n" if j < len(stat["titles"]): stats_content += "\n" if i < len(report_data["stats"]) - 1: stats_content += f"\n{separator}\n\n" # 生成新增新闻部分 new_titles_content = "" if show_new_section and report_data["new_titles"]: new_titles_content += ( f"🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n" ) for source_data in report_data["new_titles"]: new_titles_content += ( f"**{source_data['source_name']}** ({len(source_data['titles'])} 条):\n" ) for j, title_data in enumerate(source_data["titles"], 1): title_data_copy = title_data.copy() title_data_copy["is_new"] = False formatted_title = format_title_for_platform( "feishu", title_data_copy, show_source=False ) new_titles_content += f" {j}. {formatted_title}\n" new_titles_content += "\n" # RSS 内容 rss_content = "" if rss_items: rss_content = _render_rss_section_feishu(rss_items, separator) # 准备各区域内容映射 region_contents = { "hotlist": stats_content, "new_items": new_titles_content, "rss": rss_content, } # 按 region_order 顺序组装内容 text_content = "" for region in region_order: content = region_contents.get(region, "") if content: if text_content: text_content += f"\n{separator}\n\n" text_content += content if not text_content: if mode == "incremental": mode_text = "增量模式下暂无新增匹配的热点词汇" elif mode == "current": mode_text = "当前榜单模式下暂无匹配的热点词汇" else: mode_text = "暂无匹配的热点词汇" text_content = f"📭 {mode_text}\n\n" if report_data["failed_ids"]: if text_content and "暂无匹配" not in text_content: text_content += f"\n{separator}\n\n" text_content += "⚠️ **数据获取失败的平台:**\n\n" for i, id_value in enumerate(report_data["failed_ids"], 1): text_content += f" • <font color='red'>{id_value}</font>\n" # 获取当前时间 now = get_time_func() if get_time_func else datetime.now() text_content += ( f"\n\n<font color='grey'>更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}</font>" ) if update_info: text_content += f"\n<font color='grey'>TrendRadar 发现新版本 {update_info['remote_version']},当前 {update_info['current_version']}</font>" return text_content def render_dingtalk_content( report_data: Dict, update_info: Optional[Dict] = None, mode: str = "daily", region_order: Optional[List[str]] = None, get_time_func: Optional[Callable[[], datetime]] = None, rss_items: Optional[list] = None, show_new_section: bool = True, ) -> str: if region_order is None: region_order = DEFAULT_REGION_ORDER total_titles = sum( len(stat["titles"]) for stat in report_data["stats"] if stat["count"] > 0 ) now = get_time_func() if get_time_func else datetime.now() # 头部信息 header_content = f"**总新闻数:** {total_titles}\n\n" header_content += f"**时间:** {now.strftime('%Y-%m-%d %H:%M:%S')}\n\n" header_content += "**类型:** 热点分析报告\n\n" header_content += "---\n\n" # 生成热点词汇统计部分 stats_content = "" if report_data["stats"]: stats_content += "📊 **热点词汇统计**\n\n" total_count = len(report_data["stats"]) for i, stat in enumerate(report_data["stats"]): word = stat["word"] count = stat["count"] sequence_display = f"[{i + 1}/{total_count}]" if count >= 10: stats_content += f"🔥 {sequence_display} **{word}** : **{count}** 条\n\n" elif count >= 5: stats_content += f"📈 {sequence_display} **{word}** : **{count}** 条\n\n" else: stats_content += f"📌 {sequence_display} **{word}** : {count} 条\n\n" for j, title_data in enumerate(stat["titles"], 1): formatted_title = format_title_for_platform( "dingtalk", title_data, show_source=True ) stats_content += f" {j}. {formatted_title}\n" if j < len(stat["titles"]): stats_content += "\n" if i < len(report_data["stats"]) - 1: stats_content += "\n---\n\n" # 生成新增新闻部分 new_titles_content = "" if show_new_section and report_data["new_titles"]: new_titles_content += ( f"🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n" ) for source_data in report_data["new_titles"]: new_titles_content += f"**{source_data['source_name']}** ({len(source_data['titles'])} 条):\n\n" for j, title_data in enumerate(source_data["titles"], 1): title_data_copy = title_data.copy() title_data_copy["is_new"] = False formatted_title = format_title_for_platform( "dingtalk", title_data_copy, show_source=False ) new_titles_content += f" {j}. {formatted_title}\n" new_titles_content += "\n" # RSS 内容 rss_content = "" if rss_items: rss_content = _render_rss_section_markdown(rss_items) # 准备各区域内容映射 region_contents = { "hotlist": stats_content, "new_items": new_titles_content, "rss": rss_content, } # 按 region_order 顺序组装内容 text_content = header_content has_content = False for region in region_order: content = region_contents.get(region, "") if content: if has_content: text_content += "\n---\n\n" text_content += content has_content = True if not has_content: if mode == "incremental": mode_text = "增量模式下暂无新增匹配的热点词汇" elif mode == "current": mode_text = "当前榜单模式下暂无匹配的热点词汇" else: mode_text = "暂无匹配的热点词汇" text_content += f"📭 {mode_text}\n\n" if report_data["failed_ids"]: if "暂无匹配" not in text_content: text_content += "\n---\n\n" text_content += "⚠️ **数据获取失败的平台:**\n\n" for i, id_value in enumerate(report_data["failed_ids"], 1): text_content += f" • **{id_value}**\n" text_content += f"\n\n> 更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}" if update_info: text_content += f"\n> TrendRadar 发现新版本 **{update_info['remote_version']}**,当前 **{update_info['current_version']}**" return text_content def render_rss_feishu_content( rss_items: list, feeds_info: Optional[Dict] = None, separator: str = "---", get_time_func: Optional[Callable[[], datetime]] = None, ) -> str: if not rss_items: now = get_time_func() if get_time_func else datetime.now() return f"📭 暂无新的 RSS 订阅内容\n\n<font color='grey'>更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}</font>" # 按 feed_id 分组 feeds_map: Dict[str, list] = {} for item in rss_items: feed_id = item.get("feed_id", "unknown") if feed_id not in feeds_map: feeds_map[feed_id] = [] feeds_map[feed_id].append(item) text_content = f"📰 **RSS 订阅更新** (共 {len(rss_items)} 条)\n\n" text_content += f"{separator}\n\n" for feed_id, items in feeds_map.items(): feed_name = items[0].get("feed_name", feed_id) if items else feed_id if feeds_info and feed_id in feeds_info: feed_name = feeds_info[feed_id] text_content += f"**{feed_name}** ({len(items)} 条)\n\n" for i, item in enumerate(items, 1): title = item.get("title", "") url = item.get("url", "") published_at = item.get("published_at", "") if url: text_content += f" {i}. [{title}]({url})" else: text_content += f" {i}. {title}" if published_at: text_content += f" <font color='grey'>- {published_at}</font>" text_content += "\n" if i < len(items): text_content += "\n" text_content += f"\n{separator}\n\n" now = get_time_func() if get_time_func else datetime.now() text_content += f"<font color='grey'>更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}</font>" return text_content def render_rss_dingtalk_content( rss_items: list, feeds_info: Optional[Dict] = None, get_time_func: Optional[Callable[[], datetime]] = None, ) -> str: now = get_time_func() if get_time_func else datetime.now() if not rss_items: return f"📭 暂无新的 RSS 订阅内容\n\n> 更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}" # 按 feed_id 分组 feeds_map: Dict[str, list] = {} for item in rss_items: feed_id = item.get("feed_id", "unknown") if feed_id not in feeds_map: feeds_map[feed_id] = [] feeds_map[feed_id].append(item) # 头部信息 text_content = f"**总条目数:** {len(rss_items)}\n\n" text_content += f"**时间:** {now.strftime('%Y-%m-%d %H:%M:%S')}\n\n" text_content += "**类型:** RSS 订阅更新\n\n" text_content += "---\n\n" for feed_id, items in feeds_map.items(): feed_name = items[0].get("feed_name", feed_id) if items else feed_id if feeds_info and feed_id in feeds_info: feed_name = feeds_info[feed_id] text_content += f"📰 **{feed_name}** ({len(items)} 条)\n\n" for i, item in enumerate(items, 1): title = item.get("title", "") url = item.get("url", "") published_at = item.get("published_at", "") if url: text_content += f" {i}. [{title}]({url})" else: text_content += f" {i}. {title}" if published_at: text_content += f" - {published_at}" text_content += "\n" if i < len(items): text_content += "\n" text_content += "\n---\n\n" text_content += f"> 更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}" return text_content def render_rss_markdown_content( rss_items: list, feeds_info: Optional[Dict] = None, get_time_func: Optional[Callable[[], datetime]] = None, ) -> str: now = get_time_func() if get_time_func else datetime.now() if not rss_items: return f"📭 暂无新的 RSS 订阅内容\n\n更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}" # 按 feed_id 分组 feeds_map: Dict[str, list] = {} for item in rss_items: feed_id = item.get("feed_id", "unknown") if feed_id not in feeds_map: feeds_map[feed_id] = [] feeds_map[feed_id].append(item) text_content = f"📰 **RSS 订阅更新** (共 {len(rss_items)} 条)\n\n" for feed_id, items in feeds_map.items(): feed_name = items[0].get("feed_name", feed_id) if items else feed_id if feeds_info and feed_id in feeds_info: feed_name = feeds_info[feed_id] text_content += f"**{feed_name}** ({len(items)} 条)\n" for i, item in enumerate(items, 1): title = item.get("title", "") url = item.get("url", "") published_at = item.get("published_at", "") if url: text_content += f" {i}. [{title}]({url})" else: text_content += f" {i}. {title}" if published_at: text_content += f" `{published_at}`" text_content += "\n" text_content += "\n" text_content += f"更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}" return text_content # === RSS 内容渲染辅助函数(用于合并推送) === def _render_rss_section_feishu(rss_items: list, separator: str = "---") -> str: if not rss_items: return "" # 按 feed_id 分组 feeds_map: Dict[str, list] = {} for item in rss_items: feed_id = item.get("feed_id", "unknown") if feed_id not in feeds_map: feeds_map[feed_id] = [] feeds_map[feed_id].append(item) text_content = f"📰 **RSS 订阅更新** (共 {len(rss_items)} 条)\n\n" for feed_id, items in feeds_map.items(): feed_name = items[0].get("feed_name", feed_id) if items else feed_id text_content += f"**{feed_name}** ({len(items)} 条)\n\n" for i, item in enumerate(items, 1): title = item.get("title", "") url = item.get("url", "") published_at = item.get("published_at", "") if url: text_content += f" {i}. [{title}]({url})" else: text_content += f" {i}. {title}" if published_at: text_content += f" <font color='grey'>- {published_at}</font>" text_content += "\n" if i < len(items): text_content += "\n" text_content += "\n" return text_content.rstrip("\n") def _render_rss_section_markdown(rss_items: list) -> str: if not rss_items: return "" # 按 feed_id 分组 feeds_map: Dict[str, list] = {} for item in rss_items: feed_id = item.get("feed_id", "unknown") if feed_id not in feeds_map: feeds_map[feed_id] = [] feeds_map[feed_id].append(item) text_content = f"📰 **RSS 订阅更新** (共 {len(rss_items)} 条)\n\n" for feed_id, items in feeds_map.items(): feed_name = items[0].get("feed_name", feed_id) if items else feed_id text_content += f"**{feed_name}** ({len(items)} 条)\n" for i, item in enumerate(items, 1): title = item.get("title", "") url = item.get("url", "") published_at = item.get("published_at", "") if url: text_content += f" {i}. [{title}]({url})" else: text_content += f" {i}. {title}" if published_at: text_content += f" `{published_at}`" text_content += "\n" text_content += "\n" return text_content.rstrip("\n")
--- +++ @@ -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: + report_data: 报告数据字典,包含 stats, new_titles, failed_ids, total_new_count + update_info: 版本更新信息(可选) + mode: 报告模式 ("daily", "incremental", "current") + separator: 内容分隔符 + region_order: 区域显示顺序列表 + get_time_func: 获取当前时间的函数(可选,默认使用 datetime.now()) + rss_items: RSS 条目列表(可选,用于合并推送) + show_new_section: 是否显示新增热点区域 + + Returns: + 格式化的飞书消息内容 + """ if region_order is None: region_order = DEFAULT_REGION_ORDER @@ -136,6 +156,20 @@ rss_items: Optional[list] = None, show_new_section: bool = True, ) -> str: + """渲染钉钉通知内容(支持热榜+RSS合并) + + Args: + report_data: 报告数据字典,包含 stats, new_titles, failed_ids, total_new_count + update_info: 版本更新信息(可选) + mode: 报告模式 ("daily", "incremental", "current") + region_order: 区域显示顺序列表 + get_time_func: 获取当前时间的函数(可选,默认使用 datetime.now()) + rss_items: RSS 条目列表(可选,用于合并推送) + show_new_section: 是否显示新增热点区域 + + Returns: + 格式化的钉钉消息内容 + """ if region_order is None: region_order = DEFAULT_REGION_ORDER @@ -256,6 +290,24 @@ separator: str = "---", get_time_func: Optional[Callable[[], datetime]] = None, ) -> str: + """渲染 RSS 飞书通知内容 + + Args: + rss_items: RSS 条目列表,每个条目包含: + - title: 标题 + - feed_id: RSS 源 ID + - feed_name: RSS 源名称 + - url: 链接 + - published_at: 发布时间 + - summary: 摘要(可选) + - author: 作者(可选) + feeds_info: RSS 源 ID 到名称的映射 + separator: 内容分隔符 + get_time_func: 获取当前时间的函数(可选) + + Returns: + 格式化的飞书消息内容 + """ if not rss_items: now = get_time_func() if get_time_func else datetime.now() return f"📭 暂无新的 RSS 订阅内容\n\n<font color='grey'>更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}</font>" @@ -310,6 +362,16 @@ feeds_info: Optional[Dict] = None, get_time_func: Optional[Callable[[], datetime]] = None, ) -> str: + """渲染 RSS 钉钉通知内容 + + Args: + rss_items: RSS 条目列表 + feeds_info: RSS 源 ID 到名称的映射 + get_time_func: 获取当前时间的函数(可选) + + Returns: + 格式化的钉钉消息内容 + """ now = get_time_func() if get_time_func else datetime.now() if not rss_items: @@ -367,6 +429,16 @@ feeds_info: Optional[Dict] = None, get_time_func: Optional[Callable[[], datetime]] = None, ) -> str: + """渲染 RSS 通用 Markdown 格式内容(企业微信、Bark、ntfy、Slack) + + Args: + rss_items: RSS 条目列表 + feeds_info: RSS 源 ID 到名称的映射 + get_time_func: 获取当前时间的函数(可选) + + Returns: + 格式化的 Markdown 消息内容 + """ now = get_time_func() if get_time_func else datetime.now() if not rss_items: @@ -414,6 +486,7 @@ # === RSS 内容渲染辅助函数(用于合并推送) === def _render_rss_section_feishu(rss_items: list, separator: str = "---") -> str: + """渲染 RSS 内容区块(飞书格式,用于合并推送)""" if not rss_items: return "" @@ -456,6 +529,7 @@ def _render_rss_section_markdown(rss_items: list) -> str: + """渲染 RSS 内容区块(通用 Markdown 格式,用于合并推送)""" if not rss_items: return "" @@ -491,4 +565,4 @@ text_content += "\n" - return text_content.rstrip("\n")+ return text_content.rstrip("\n")
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_controversy: str = "" # 舆论风向与争议 signals: str = "" # 异动与弱信号 rss_insights: str = "" # RSS 深度洞察 outlook_strategy: str = "" # 研判与策略建议 standalone_summaries: Dict[str, str] = field(default_factory=dict) # 独立展示区概括 {源ID: 概括} # 基础元数据 raw_response: str = "" # 原始响应 success: bool = False # 是否成功 error: str = "" # 错误信息 # 新闻数量统计 total_news: int = 0 # 总新闻数(热榜+RSS) analyzed_news: int = 0 # 实际分析的新闻数 max_news_limit: int = 0 # 分析上限配置值 hotlist_count: int = 0 # 热榜新闻数 rss_count: int = 0 # RSS 新闻数 ai_mode: str = "" # AI 分析使用的模式 (daily/current/incremental) class AIAnalyzer: def __init__( self, ai_config: Dict[str, Any], analysis_config: Dict[str, Any], get_time_func: Callable, debug: bool = False, ): self.ai_config = ai_config self.analysis_config = analysis_config self.get_time_func = get_time_func self.debug = debug # 创建 AI 客户端(基于 LiteLLM) self.client = AIClient(ai_config) # 验证配置 valid, error = self.client.validate_config() if not valid: print(f"[AI] 配置警告: {error}") # 从分析配置获取功能参数 self.max_news = analysis_config.get("MAX_NEWS_FOR_ANALYSIS", 50) self.include_rss = analysis_config.get("INCLUDE_RSS", True) self.include_rank_timeline = analysis_config.get("INCLUDE_RANK_TIMELINE", False) self.include_standalone = analysis_config.get("INCLUDE_STANDALONE", False) self.language = analysis_config.get("LANGUAGE", "Chinese") # 加载提示词模板 self.system_prompt, self.user_prompt_template = self._load_prompt_template( analysis_config.get("PROMPT_FILE", "ai_analysis_prompt.txt") ) def _load_prompt_template(self, prompt_file: str) -> tuple: config_dir = Path(__file__).parent.parent.parent / "config" prompt_path = config_dir / prompt_file if not prompt_path.exists(): print(f"[AI] 提示词文件不存在: {prompt_path}") return "", "" content = prompt_path.read_text(encoding="utf-8") # 解析 [system] 和 [user] 部分 system_prompt = "" user_prompt = "" if "[system]" in content and "[user]" in content: parts = content.split("[user]") system_part = parts[0] user_part = parts[1] if len(parts) > 1 else "" # 提取 system 内容 if "[system]" in system_part: system_prompt = system_part.split("[system]")[1].strip() user_prompt = user_part.strip() else: # 整个文件作为 user prompt user_prompt = content return system_prompt, user_prompt def analyze( self, stats: List[Dict], rss_stats: Optional[List[Dict]] = None, report_mode: str = "daily", report_type: str = "当日汇总", platforms: Optional[List[str]] = None, keywords: Optional[List[str]] = None, standalone_data: Optional[Dict] = None, ) -> AIAnalysisResult: # 打印配置信息方便调试 model = self.ai_config.get("MODEL", "unknown") api_key = self.client.api_key or "" api_base = self.ai_config.get("API_BASE", "") masked_key = f"{api_key[:5]}******" if len(api_key) >= 5 else "******" model_display = model.replace("/", "/\u200b") if model else "unknown" print(f"[AI] 模型: {model_display}") print(f"[AI] Key : {masked_key}") if api_base: print(f"[AI] 接口: 存在自定义 API 端点") timeout = self.ai_config.get("TIMEOUT", 120) max_tokens = self.ai_config.get("MAX_TOKENS", 5000) print(f"[AI] 参数: timeout={timeout}, max_tokens={max_tokens}") if not self.client.api_key: return AIAnalysisResult( success=False, error="未配置 AI API Key,请在 config.yaml 或环境变量 AI_API_KEY 中设置" ) # 准备新闻内容并获取统计数据 news_content, rss_content, hotlist_total, rss_total, analyzed_count = self._prepare_news_content(stats, rss_stats) total_news = hotlist_total + rss_total if not news_content and not rss_content: return AIAnalysisResult( success=False, error="没有可分析的新闻内容", total_news=total_news, hotlist_count=hotlist_total, rss_count=rss_total, analyzed_news=0, max_news_limit=self.max_news ) # 构建提示词 current_time = self.get_time_func().strftime("%Y-%m-%d %H:%M:%S") # 提取关键词 if not keywords: keywords = [s.get("word", "") for s in stats if s.get("word")] if stats else [] # 使用安全的字符串替换,避免模板中其他花括号(如 JSON 示例)被误解析 user_prompt = self.user_prompt_template user_prompt = user_prompt.replace("{report_mode}", report_mode) user_prompt = user_prompt.replace("{report_type}", report_type) user_prompt = user_prompt.replace("{current_time}", current_time) user_prompt = user_prompt.replace("{news_count}", str(hotlist_total)) user_prompt = user_prompt.replace("{rss_count}", str(rss_total)) user_prompt = user_prompt.replace("{platforms}", ", ".join(platforms) if platforms else "多平台") user_prompt = user_prompt.replace("{keywords}", ", ".join(keywords[:20]) if keywords else "无") user_prompt = user_prompt.replace("{news_content}", news_content) user_prompt = user_prompt.replace("{rss_content}", rss_content) user_prompt = user_prompt.replace("{language}", self.language) # 构建独立展示区内容 standalone_content = "" if self.include_standalone and standalone_data: standalone_content = self._prepare_standalone_content(standalone_data) user_prompt = user_prompt.replace("{standalone_content}", standalone_content) if self.debug: print("\n" + "=" * 80) print("[AI 调试] 发送给 AI 的完整提示词") print("=" * 80) if self.system_prompt: print("\n--- System Prompt ---") print(self.system_prompt) print("\n--- User Prompt ---") print(user_prompt) print("=" * 80 + "\n") # 调用 AI API(使用 LiteLLM) try: response = self._call_ai(user_prompt) result = self._parse_response(response) # JSON 解析失败时的重试兜底(仅重试一次) if result.error and "JSON 解析错误" in result.error: print(f"[AI] JSON 解析失败,尝试让 AI 修复...") retry_result = self._retry_fix_json(response, result.error) if retry_result and retry_result.success and not retry_result.error: print("[AI] JSON 修复成功") retry_result.raw_response = response result = retry_result else: print("[AI] JSON 修复失败,使用原始文本兜底") # 如果配置未启用 RSS 分析,强制清空 AI 返回的 RSS 洞察 if not self.include_rss: result.rss_insights = "" # 如果配置未启用 standalone 分析,强制清空 if not self.include_standalone: result.standalone_summaries = {} # 填充统计数据 result.total_news = total_news result.hotlist_count = hotlist_total result.rss_count = rss_total result.analyzed_news = analyzed_count result.max_news_limit = self.max_news return result except Exception as e: error_type = type(e).__name__ error_msg = str(e) # 截断过长的错误消息 if len(error_msg) > 200: error_msg = error_msg[:200] + "..." friendly_msg = f"AI 分析失败 ({error_type}): {error_msg}" return AIAnalysisResult( success=False, error=friendly_msg ) def _prepare_news_content( self, stats: List[Dict], rss_stats: Optional[List[Dict]] = None, ) -> tuple: news_lines = [] rss_lines = [] news_count = 0 rss_count = 0 # 计算总新闻数 hotlist_total = sum(len(s.get("titles", [])) for s in stats) if stats else 0 rss_total = sum(len(s.get("titles", [])) for s in rss_stats) if rss_stats else 0 # 热榜内容 if stats: for stat in stats: word = stat.get("word", "") titles = stat.get("titles", []) if word and titles: news_lines.append(f"\n**{word}** ({len(titles)}条)") for t in titles: if not isinstance(t, dict): continue title = t.get("title", "") if not title: continue # 来源 source = t.get("source_name", t.get("source", "")) # 构建行 if source: line = f"- [{source}] {title}" else: line = f"- {title}" # 始终显示简化格式:排名范围 + 时间范围 + 出现次数 ranks = t.get("ranks", []) if ranks: min_rank = min(ranks) max_rank = max(ranks) rank_str = f"{min_rank}" if min_rank == max_rank else f"{min_rank}-{max_rank}" else: rank_str = "-" first_time = t.get("first_time", "") last_time = t.get("last_time", "") time_str = self._format_time_range(first_time, last_time) appear_count = t.get("count", 1) line += f" | 排名:{rank_str} | 时间:{time_str} | 出现:{appear_count}次" # 开启完整时间线时,额外添加轨迹 if self.include_rank_timeline: rank_timeline = t.get("rank_timeline", []) timeline_str = self._format_rank_timeline(rank_timeline) line += f" | 轨迹:{timeline_str}" news_lines.append(line) news_count += 1 if news_count >= self.max_news: break if news_count >= self.max_news: break # RSS 内容(仅在启用时构建) if self.include_rss and rss_stats: remaining = self.max_news - news_count for stat in rss_stats: if rss_count >= remaining: break word = stat.get("word", "") titles = stat.get("titles", []) if word and titles: rss_lines.append(f"\n**{word}** ({len(titles)}条)") for t in titles: if not isinstance(t, dict): continue title = t.get("title", "") if not title: continue # 来源 source = t.get("source_name", t.get("feed_name", "")) # 发布时间 time_display = t.get("time_display", "") # 构建行:[来源] 标题 | 发布时间 if source: line = f"- [{source}] {title}" else: line = f"- {title}" if time_display: line += f" | {time_display}" rss_lines.append(line) rss_count += 1 if rss_count >= remaining: break news_content = "\n".join(news_lines) if news_lines else "" rss_content = "\n".join(rss_lines) if rss_lines else "" total_count = news_count + rss_count return news_content, rss_content, hotlist_total, rss_total, total_count def _call_ai(self, user_prompt: str) -> str: messages = [] if self.system_prompt: messages.append({"role": "system", "content": self.system_prompt}) messages.append({"role": "user", "content": user_prompt}) return self.client.chat(messages) def _retry_fix_json(self, original_response: str, error_msg: str) -> Optional[AIAnalysisResult]: messages = [ { "role": "system", "content": ( "你是一个 JSON 修复助手。用户会提供一段格式有误的 JSON 和错误信息," "你需要修复 JSON 格式错误并返回正确的 JSON。\n" "常见问题:字符串值内的双引号未转义、缺少逗号、字符串未正确闭合等。\n" "只返回纯 JSON,不要包含 markdown 代码块标记(如 ```json)或任何说明文字。" ), }, { "role": "user", "content": ( f"以下 JSON 解析失败:\n\n" f"错误:{error_msg}\n\n" f"原始内容:\n{original_response}\n\n" f"请修复以上 JSON 中的格式问题(如值中的双引号改用中文引号「」或转义 \\\"、" f"缺少逗号、不完整的字符串等),保持原始内容语义不变,只修复格式。" f"直接返回修复后的纯 JSON。" ), }, ] try: response = self.client.chat(messages) return self._parse_response(response) except Exception as e: print(f"[AI] 重试修复 JSON 异常: {type(e).__name__}: {e}") return None def _format_time_range(self, first_time: str, last_time: str) -> str: def extract_time(time_str: str) -> str: if not time_str: return "-" # 尝试提取 HH:MM 部分 if " " in time_str: parts = time_str.split(" ") if len(parts) >= 2: time_part = parts[1] if ":" in time_part: return time_part[:5] # HH:MM elif ":" in time_str: return time_str[:5] # 处理 HH-MM 格式 result = time_str[:5] if len(time_str) >= 5 else time_str if len(result) == 5 and result[2] == '-': result = result.replace('-', ':') return result first = extract_time(first_time) last = extract_time(last_time) if first == last or last == "-": return first return f"{first}~{last}" def _format_rank_timeline(self, rank_timeline: List[Dict]) -> str: if not rank_timeline: return "-" parts = [] for item in rank_timeline: time_str = item.get("time", "") if len(time_str) == 5 and time_str[2] == '-': time_str = time_str.replace('-', ':') rank = item.get("rank") if rank is None: parts.append(f"0({time_str})") else: parts.append(f"{rank}({time_str})") return "→".join(parts) def _prepare_standalone_content(self, standalone_data: Dict) -> str: lines = [] # 热榜平台 for platform in standalone_data.get("platforms", []): platform_id = platform.get("id", "") platform_name = platform.get("name", platform_id) items = platform.get("items", []) if not items: continue lines.append(f"### [{platform_name}]") for item in items: title = item.get("title", "") if not title: continue line = f"- {title}" # 排名信息 ranks = item.get("ranks", []) if ranks: min_rank = min(ranks) max_rank = max(ranks) rank_str = f"{min_rank}" if min_rank == max_rank else f"{min_rank}-{max_rank}" line += f" | 排名:{rank_str}" # 时间范围 first_time = item.get("first_time", "") last_time = item.get("last_time", "") if first_time: time_str = self._format_time_range(first_time, last_time) line += f" | 时间:{time_str}" # 出现次数 count = item.get("count", 1) if count > 1: line += f" | 出现:{count}次" # 排名轨迹(如果启用) if self.include_rank_timeline: rank_timeline = item.get("rank_timeline", []) if rank_timeline: timeline_str = self._format_rank_timeline(rank_timeline) line += f" | 轨迹:{timeline_str}" lines.append(line) lines.append("") # RSS 源 for feed in standalone_data.get("rss_feeds", []): feed_id = feed.get("id", "") feed_name = feed.get("name", feed_id) items = feed.get("items", []) if not items: continue lines.append(f"### [{feed_name}]") for item in items: title = item.get("title", "") if not title: continue line = f"- {title}" published_at = item.get("published_at", "") if published_at: line += f" | {published_at}" lines.append(line) lines.append("") return "\n".join(lines) def _parse_response(self, response: str) -> AIAnalysisResult: result = AIAnalysisResult(raw_response=response) if not response or not response.strip(): result.error = "AI 返回空响应" return result # 提取 JSON 文本(去掉 markdown 代码块标记) json_str = response if "```json" in response: parts = response.split("```json", 1) if len(parts) > 1: code_block = parts[1] end_idx = code_block.find("```") if end_idx != -1: json_str = code_block[:end_idx] else: json_str = code_block elif "```" in response: parts = response.split("```", 2) if len(parts) >= 2: json_str = parts[1] json_str = json_str.strip() if not json_str: result.error = "提取的 JSON 内容为空" result.core_trends = response[:500] + "..." if len(response) > 500 else response result.success = True return result # 第一步:标准 JSON 解析 data = None parse_error = None try: data = json.loads(json_str) except json.JSONDecodeError as e: parse_error = e # 第二步:json_repair 本地修复 if data is None: try: from json_repair import repair_json repaired = repair_json(json_str, return_objects=True) if isinstance(repaired, dict): data = repaired print("[AI] JSON 本地修复成功(json_repair)") except Exception: pass # 两步都失败,记录错误(后续由 analyze 方法的重试机制处理) if data is None: if parse_error: error_context = json_str[max(0, parse_error.pos - 30):parse_error.pos + 30] if json_str and parse_error.pos else "" result.error = f"JSON 解析错误 (位置 {parse_error.pos}): {parse_error.msg}" if error_context: result.error += f",上下文: ...{error_context}..." else: result.error = "JSON 解析失败" # 兜底:使用已提取的 json_str(不含 markdown 标记),避免推送中出现 ```json result.core_trends = json_str[:500] + "..." if len(json_str) > 500 else json_str result.success = True return result # 解析成功,提取字段 try: result.core_trends = data.get("core_trends", "") result.sentiment_controversy = data.get("sentiment_controversy", "") result.signals = data.get("signals", "") result.rss_insights = data.get("rss_insights", "") result.outlook_strategy = data.get("outlook_strategy", "") # 解析独立展示区概括 summaries = data.get("standalone_summaries", {}) if isinstance(summaries, dict): result.standalone_summaries = { str(k): str(v) for k, v in summaries.items() } result.success = True except (KeyError, TypeError, AttributeError) as e: result.error = f"字段提取错误: {type(e).__name__}: {e}" result.core_trends = json_str[:500] + "..." if len(json_str) > 500 else json_str result.success = True return result
--- +++ @@ -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 = "" # 核心热点与舆情态势 sentiment_controversy: str = "" # 舆论风向与争议 @@ -33,6 +40,7 @@ class AIAnalyzer: + """AI 分析器""" def __init__( self, @@ -41,6 +49,15 @@ get_time_func: Callable, debug: bool = False, ): + """ + 初始化 AI 分析器 + + Args: + ai_config: AI 模型配置(LiteLLM 格式) + analysis_config: AI 分析功能配置(language, prompt_file 等) + get_time_func: 获取当前时间的函数 + debug: 是否开启调试模式 + """ self.ai_config = ai_config self.analysis_config = analysis_config self.get_time_func = get_time_func @@ -67,6 +84,7 @@ ) def _load_prompt_template(self, prompt_file: str) -> tuple: + """加载提示词模板""" config_dir = Path(__file__).parent.parent.parent / "config" prompt_path = config_dir / prompt_file @@ -106,6 +124,20 @@ keywords: Optional[List[str]] = None, standalone_data: Optional[Dict] = None, ) -> AIAnalysisResult: + """ + 执行 AI 分析 + + Args: + stats: 热榜统计数据 + rss_stats: RSS 统计数据 + report_mode: 报告模式 + report_type: 报告类型 + platforms: 平台列表 + keywords: 关键词列表 + + Returns: + AIAnalysisResult: 分析结果 + """ # 打印配置信息方便调试 model = self.ai_config.get("MODEL", "unknown") @@ -232,6 +264,15 @@ stats: List[Dict], rss_stats: Optional[List[Dict]] = None, ) -> tuple: + """ + 准备新闻内容文本(增强版) + + 热榜新闻包含:来源、标题、排名范围、时间范围、出现次数 + RSS 包含:来源、标题、发布时间 + + Returns: + tuple: (news_content, rss_content, hotlist_total, rss_total, analyzed_count) + """ news_lines = [] rss_lines = [] news_count = 0 @@ -338,6 +379,7 @@ return news_content, rss_content, hotlist_total, rss_total, total_count def _call_ai(self, user_prompt: str) -> str: + """调用 AI API(使用 LiteLLM)""" messages = [] if self.system_prompt: messages.append({"role": "system", "content": self.system_prompt}) @@ -346,6 +388,18 @@ return self.client.chat(messages) def _retry_fix_json(self, original_response: str, error_msg: str) -> Optional[AIAnalysisResult]: + """ + JSON 解析失败时,请求 AI 修复 JSON(仅重试一次) + + 使用轻量 prompt,不重复原始分析的 system prompt,节省 token。 + + Args: + original_response: AI 原始响应(JSON 格式有误) + error_msg: JSON 解析的错误信息 + + Returns: + 修复后的分析结果,失败时返回 None + """ messages = [ { "role": "system", @@ -377,6 +431,7 @@ return None def _format_time_range(self, first_time: str, last_time: str) -> str: + """格式化时间范围(简化显示,只保留时分)""" def extract_time(time_str: str) -> str: if not time_str: return "-" @@ -403,6 +458,7 @@ return f"{first}~{last}" def _format_rank_timeline(self, rank_timeline: List[Dict]) -> str: + """格式化排名时间线""" if not rank_timeline: return "-" @@ -420,6 +476,15 @@ return "→".join(parts) def _prepare_standalone_content(self, standalone_data: Dict) -> str: + """ + 将独立展示区数据转为文本,注入 AI 分析 prompt + + Args: + standalone_data: 独立展示区数据 {"platforms": [...], "rss_feeds": [...]} + + Returns: + 格式化的文本内容 + """ lines = [] # 热榜平台 @@ -493,6 +558,7 @@ return "\n".join(lines) def _parse_response(self, response: str) -> AIAnalysisResult: + """解析 AI 响应""" result = AIAnalysisResult(raw_response=response) if not response or not response.strip(): @@ -578,4 +644,4 @@ result.core_trends = json_str[:500] + "..." if len(json_str) > 500 else json_str result.success = True - return result+ return result
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, med_config = 'configs/med_config.json', image_size = 384, vit = 'base', vit_grad_ckpt = False, vit_ckpt_layer = 0, embed_dim = 256, queue_size = 57600, momentum = 0.995, negative_all_rank = False, ): super().__init__() self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer) self.tokenizer = init_tokenizer() med_config = BertConfig.from_json_file(med_config) med_config.encoder_width = vision_width self.text_encoder = BertModel(config=med_config, add_pooling_layer=False) text_width = self.text_encoder.config.hidden_size self.vision_proj = nn.Linear(vision_width, embed_dim) self.text_proj = nn.Linear(text_width, embed_dim) self.itm_head = nn.Linear(text_width, 2) # create momentum encoders self.visual_encoder_m, vision_width = create_vit(vit,image_size) self.vision_proj_m = nn.Linear(vision_width, embed_dim) self.text_encoder_m = BertModel(config=med_config, add_pooling_layer=False) self.text_proj_m = nn.Linear(text_width, embed_dim) self.model_pairs = [[self.visual_encoder,self.visual_encoder_m], [self.vision_proj,self.vision_proj_m], [self.text_encoder,self.text_encoder_m], [self.text_proj,self.text_proj_m], ] self.copy_params() # create the queue self.register_buffer("image_queue", torch.randn(embed_dim, queue_size)) self.register_buffer("text_queue", torch.randn(embed_dim, queue_size)) self.register_buffer("idx_queue", torch.full((1,queue_size),-100)) self.register_buffer("ptr_queue", torch.zeros(1, dtype=torch.long)) self.image_queue = nn.functional.normalize(self.image_queue, dim=0) self.text_queue = nn.functional.normalize(self.text_queue, dim=0) self.queue_size = queue_size self.momentum = momentum self.temp = nn.Parameter(0.07*torch.ones([])) self.negative_all_rank = negative_all_rank def forward(self, image, caption, alpha, idx): with torch.no_grad(): self.temp.clamp_(0.001,0.5) image_embeds = self.visual_encoder(image) image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device) image_feat = F.normalize(self.vision_proj(image_embeds[:,0,:]),dim=-1) text = self.tokenizer(caption, padding='max_length', truncation=True, max_length=35, return_tensors="pt").to(image.device) text_output = self.text_encoder(text.input_ids, attention_mask = text.attention_mask, return_dict = True, mode = 'text') text_feat = F.normalize(self.text_proj(text_output.last_hidden_state[:,0,:]),dim=-1) ###============== Image-text Contrastive Learning ===================### idx = idx.view(-1,1) idx_all = torch.cat([idx.t(), self.idx_queue.clone().detach()],dim=1) pos_idx = torch.eq(idx, idx_all).float() sim_targets = pos_idx / pos_idx.sum(1,keepdim=True) # get momentum features with torch.no_grad(): self._momentum_update() image_embeds_m = self.visual_encoder_m(image) image_feat_m = F.normalize(self.vision_proj_m(image_embeds_m[:,0,:]),dim=-1) image_feat_m_all = torch.cat([image_feat_m.t(),self.image_queue.clone().detach()],dim=1) text_output_m = self.text_encoder_m(text.input_ids, attention_mask = text.attention_mask, return_dict = True, mode = 'text') text_feat_m = F.normalize(self.text_proj_m(text_output_m.last_hidden_state[:,0,:]),dim=-1) text_feat_m_all = torch.cat([text_feat_m.t(),self.text_queue.clone().detach()],dim=1) sim_i2t_m = image_feat_m @ text_feat_m_all / self.temp sim_t2i_m = text_feat_m @ image_feat_m_all / self.temp sim_i2t_targets = alpha * F.softmax(sim_i2t_m, dim=1) + (1 - alpha) * sim_targets sim_t2i_targets = alpha * F.softmax(sim_t2i_m, dim=1) + (1 - alpha) * sim_targets sim_i2t = image_feat @ text_feat_m_all / self.temp sim_t2i = text_feat @ image_feat_m_all / self.temp loss_i2t = -torch.sum(F.log_softmax(sim_i2t, dim=1)*sim_i2t_targets,dim=1).mean() loss_t2i = -torch.sum(F.log_softmax(sim_t2i, dim=1)*sim_t2i_targets,dim=1).mean() loss_ita = (loss_i2t+loss_t2i)/2 idxs = concat_all_gather(idx) self._dequeue_and_enqueue(image_feat_m, text_feat_m, idxs) ###============== Image-text Matching ===================### encoder_input_ids = text.input_ids.clone() encoder_input_ids[:,0] = self.tokenizer.enc_token_id # forward the positve image-text pair bs = image.size(0) output_pos = self.text_encoder(encoder_input_ids, attention_mask = text.attention_mask, encoder_hidden_states = image_embeds, encoder_attention_mask = image_atts, return_dict = True, ) if self.negative_all_rank: # compute sample similarity with torch.no_grad(): mask = torch.eq(idx, idxs.t()) image_feat_world = concat_all_gather(image_feat) text_feat_world = concat_all_gather(text_feat) sim_i2t = image_feat @ text_feat_world.t() / self.temp sim_t2i = text_feat @ image_feat_world.t() / self.temp weights_i2t = F.softmax(sim_i2t,dim=1) weights_i2t.masked_fill_(mask, 0) weights_t2i = F.softmax(sim_t2i,dim=1) weights_t2i.masked_fill_(mask, 0) image_embeds_world = all_gather_with_grad(image_embeds) # select a negative image (from all ranks) for each text image_embeds_neg = [] for b in range(bs): neg_idx = torch.multinomial(weights_t2i[b], 1).item() image_embeds_neg.append(image_embeds_world[neg_idx]) image_embeds_neg = torch.stack(image_embeds_neg,dim=0) # select a negative text (from all ranks) for each image input_ids_world = concat_all_gather(encoder_input_ids) att_mask_world = concat_all_gather(text.attention_mask) text_ids_neg = [] text_atts_neg = [] for b in range(bs): neg_idx = torch.multinomial(weights_i2t[b], 1).item() text_ids_neg.append(input_ids_world[neg_idx]) text_atts_neg.append(att_mask_world[neg_idx]) else: with torch.no_grad(): mask = torch.eq(idx, idx.t()) sim_i2t = image_feat @ text_feat.t() / self.temp sim_t2i = text_feat @ image_feat.t() / self.temp weights_i2t = F.softmax(sim_i2t,dim=1) weights_i2t.masked_fill_(mask, 0) weights_t2i = F.softmax(sim_t2i,dim=1) weights_t2i.masked_fill_(mask, 0) # select a negative image (from same rank) for each text image_embeds_neg = [] for b in range(bs): neg_idx = torch.multinomial(weights_t2i[b], 1).item() image_embeds_neg.append(image_embeds[neg_idx]) image_embeds_neg = torch.stack(image_embeds_neg,dim=0) # select a negative text (from same rank) for each image text_ids_neg = [] text_atts_neg = [] for b in range(bs): neg_idx = torch.multinomial(weights_i2t[b], 1).item() text_ids_neg.append(encoder_input_ids[neg_idx]) text_atts_neg.append(text.attention_mask[neg_idx]) text_ids_neg = torch.stack(text_ids_neg,dim=0) text_atts_neg = torch.stack(text_atts_neg,dim=0) text_ids_all = torch.cat([encoder_input_ids, text_ids_neg],dim=0) text_atts_all = torch.cat([text.attention_mask, text_atts_neg],dim=0) image_embeds_all = torch.cat([image_embeds_neg,image_embeds],dim=0) image_atts_all = torch.cat([image_atts,image_atts],dim=0) output_neg = self.text_encoder(text_ids_all, attention_mask = text_atts_all, encoder_hidden_states = image_embeds_all, encoder_attention_mask = image_atts_all, return_dict = True, ) vl_embeddings = torch.cat([output_pos.last_hidden_state[:,0,:], output_neg.last_hidden_state[:,0,:]],dim=0) vl_output = self.itm_head(vl_embeddings) itm_labels = torch.cat([torch.ones(bs,dtype=torch.long),torch.zeros(2*bs,dtype=torch.long)], dim=0).to(image.device) loss_itm = F.cross_entropy(vl_output, itm_labels) return loss_ita, loss_itm @torch.no_grad() def copy_params(self): for model_pair in self.model_pairs: for param, param_m in zip(model_pair[0].parameters(), model_pair[1].parameters()): param_m.data.copy_(param.data) # initialize param_m.requires_grad = False # not update by gradient @torch.no_grad() def _momentum_update(self): for model_pair in self.model_pairs: for param, param_m in zip(model_pair[0].parameters(), model_pair[1].parameters()): param_m.data = param_m.data * self.momentum + param.data * (1. - self.momentum) @torch.no_grad() def _dequeue_and_enqueue(self, image_feat, text_feat, idxs): # gather keys before updating queue image_feats = concat_all_gather(image_feat) text_feats = concat_all_gather(text_feat) batch_size = image_feats.shape[0] ptr = int(self.ptr_queue) assert self.queue_size % batch_size == 0 # for simplicity # replace the keys at ptr (dequeue and enqueue) self.image_queue[:, ptr:ptr + batch_size] = image_feats.T self.text_queue[:, ptr:ptr + batch_size] = text_feats.T self.idx_queue[:, ptr:ptr + batch_size] = idxs.T ptr = (ptr + batch_size) % self.queue_size # move pointer self.ptr_queue[0] = ptr def blip_retrieval(pretrained='',**kwargs): model = BLIP_Retrieval(**kwargs) if pretrained: model,msg = load_checkpoint(model,pretrained) print("missing keys:") print(msg.missing_keys) return model @torch.no_grad() def concat_all_gather(tensor): tensors_gather = [torch.ones_like(tensor) for _ in range(torch.distributed.get_world_size())] torch.distributed.all_gather(tensors_gather, tensor, async_op=False) output = torch.cat(tensors_gather, dim=0) return output class GatherLayer(torch.autograd.Function): @staticmethod def forward(ctx, x): output = [torch.zeros_like(x) for _ in range(torch.distributed.get_world_size())] torch.distributed.all_gather(output, x) return tuple(output) @staticmethod def backward(ctx, *grads): all_gradients = torch.stack(grads) torch.distributed.all_reduce(all_gradients) return all_gradients[torch.distributed.get_rank()] def all_gather_with_grad(tensors): # Queue the gathered tensors world_size = torch.distributed.get_world_size() # There is no need for reduction in the single-proc case if world_size == 1: return tensors tensor_all = GatherLayer.apply(tensors) return torch.cat(tensor_all, dim=0)
--- +++ @@ -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 (str): model size of vision transformer + """ super().__init__() self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer) @@ -266,6 +272,10 @@ @torch.no_grad() def concat_all_gather(tensor): + """ + Performs all_gather operation on the provided tensors. + *** Warning ***: torch.distributed.all_gather has no gradient. + """ tensors_gather = [torch.ones_like(tensor) for _ in range(torch.distributed.get_world_size())] torch.distributed.all_gather(tensors_gather, tensor, async_op=False) @@ -275,6 +285,10 @@ class GatherLayer(torch.autograd.Function): + """ + Gather tensors from all workers with support for backward propagation: + This implementation does not cut the gradients as torch.distributed.all_gather does. + """ @staticmethod def forward(ctx, x): @@ -290,6 +304,10 @@ def all_gather_with_grad(tensors): + """ + Performs all_gather operation on the provided tensors. + Graph remains connected for backward grad computation. + """ # Queue the gathered tensors world_size = torch.distributed.get_world_size() # There is no need for reduction in the single-proc case @@ -298,4 +316,4 @@ tensor_all = GatherLayer.apply(tensors) - return torch.cat(tensor_all, dim=0)+ return torch.cat(tensor_all, dim=0)
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 import ACT2FN from transformers.file_utils import ( ModelOutput, ) from transformers.modeling_outputs import ( BaseModelOutputWithPastAndCrossAttentions, BaseModelOutputWithPoolingAndCrossAttentions, CausalLMOutputWithCrossAttentions, MaskedLMOutput, MultipleChoiceModelOutput, NextSentencePredictorOutput, QuestionAnsweringModelOutput, SequenceClassifierOutput, TokenClassifierOutput, ) from transformers.modeling_utils import ( PreTrainedModel, apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer, ) from transformers.utils import logging from transformers.models.bert.configuration_bert import BertConfig logger = logging.get_logger(__name__) class BertEmbeddings(nn.Module): def __init__(self, config): super().__init__() self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size) # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load # any TensorFlow checkpoint file self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) # position_ids (1, len position emb) is contiguous in memory and exported when serialized self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))) self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") self.config = config def forward( self, input_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0 ): if input_ids is not None: input_shape = input_ids.size() else: input_shape = inputs_embeds.size()[:-1] seq_length = input_shape[1] if position_ids is None: position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length] if inputs_embeds is None: inputs_embeds = self.word_embeddings(input_ids) embeddings = inputs_embeds if self.position_embedding_type == "absolute": position_embeddings = self.position_embeddings(position_ids) embeddings += position_embeddings embeddings = self.LayerNorm(embeddings) embeddings = self.dropout(embeddings) return embeddings class BertSelfAttention(nn.Module): def __init__(self, config, is_cross_attention): super().__init__() self.config = config if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( "The hidden size (%d) is not a multiple of the number of attention " "heads (%d)" % (config.hidden_size, config.num_attention_heads) ) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query = nn.Linear(config.hidden_size, self.all_head_size) if is_cross_attention: self.key = nn.Linear(config.encoder_width, self.all_head_size) self.value = nn.Linear(config.encoder_width, self.all_head_size) else: self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": self.max_position_embeddings = config.max_position_embeddings self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size) self.save_attention = False def save_attn_gradients(self, attn_gradients): self.attn_gradients = attn_gradients def get_attn_gradients(self): return self.attn_gradients def save_attention_map(self, attention_map): self.attention_map = attention_map def get_attention_map(self): return self.attention_map def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_value=None, output_attentions=False, ): mixed_query_layer = self.query(hidden_states) # If this is instantiated as a cross-attention module, the keys # and values come from an encoder; the attention mask needs to be # such that the encoder's padding tokens are not attended to. is_cross_attention = encoder_hidden_states is not None if is_cross_attention: key_layer = self.transpose_for_scores(self.key(encoder_hidden_states)) value_layer = self.transpose_for_scores(self.value(encoder_hidden_states)) attention_mask = encoder_attention_mask elif past_key_value is not None: key_layer = self.transpose_for_scores(self.key(hidden_states)) value_layer = self.transpose_for_scores(self.value(hidden_states)) key_layer = torch.cat([past_key_value[0], key_layer], dim=2) value_layer = torch.cat([past_key_value[1], value_layer], dim=2) else: key_layer = self.transpose_for_scores(self.key(hidden_states)) value_layer = self.transpose_for_scores(self.value(hidden_states)) query_layer = self.transpose_for_scores(mixed_query_layer) past_key_value = (key_layer, value_layer) # Take the dot product between "query" and "key" to get the raw attention scores. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": seq_length = hidden_states.size()[1] position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1) position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1) distance = position_ids_l - position_ids_r positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1) positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility if self.position_embedding_type == "relative_key": relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) attention_scores = attention_scores + relative_position_scores elif self.position_embedding_type == "relative_key_query": relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding) attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key attention_scores = attention_scores / math.sqrt(self.attention_head_size) if attention_mask is not None: # Apply the attention mask is (precomputed for all layers in BertModel forward() function) attention_scores = attention_scores + attention_mask # Normalize the attention scores to probabilities. attention_probs = nn.Softmax(dim=-1)(attention_scores) if is_cross_attention and self.save_attention: self.save_attention_map(attention_probs) attention_probs.register_hook(self.save_attn_gradients) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs_dropped = self.dropout(attention_probs) # Mask heads if we want to if head_mask is not None: attention_probs_dropped = attention_probs_dropped * head_mask context_layer = torch.matmul(attention_probs_dropped, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) context_layer = context_layer.view(*new_context_layer_shape) outputs = (context_layer, attention_probs) if output_attentions else (context_layer,) outputs = outputs + (past_key_value,) return outputs class BertSelfOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states class BertAttention(nn.Module): def __init__(self, config, is_cross_attention=False): super().__init__() self.self = BertSelfAttention(config, is_cross_attention) self.output = BertSelfOutput(config) self.pruned_heads = set() def prune_heads(self, heads): if len(heads) == 0: return heads, index = find_pruneable_heads_and_indices( heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads ) # Prune linear layers self.self.query = prune_linear_layer(self.self.query, index) self.self.key = prune_linear_layer(self.self.key, index) self.self.value = prune_linear_layer(self.self.value, index) self.output.dense = prune_linear_layer(self.output.dense, index, dim=1) # Update hyper params and store pruned heads self.self.num_attention_heads = self.self.num_attention_heads - len(heads) self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads self.pruned_heads = self.pruned_heads.union(heads) def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_value=None, output_attentions=False, ): self_outputs = self.self( hidden_states, attention_mask, head_mask, encoder_hidden_states, encoder_attention_mask, past_key_value, output_attentions, ) attention_output = self.output(self_outputs[0], hidden_states) outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them return outputs class BertIntermediate(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.intermediate_act_fn = config.hidden_act def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.intermediate_act_fn(hidden_states) return hidden_states class BertOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states class BertLayer(nn.Module): def __init__(self, config, layer_num): super().__init__() self.config = config self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = BertAttention(config) self.layer_num = layer_num if self.config.add_cross_attention: self.crossattention = BertAttention(config, is_cross_attention=self.config.add_cross_attention) self.intermediate = BertIntermediate(config) self.output = BertOutput(config) def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_value=None, output_attentions=False, mode=None, ): # decoder uni-directional self-attention cached key/values tuple is at positions 1,2 self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None self_attention_outputs = self.attention( hidden_states, attention_mask, head_mask, output_attentions=output_attentions, past_key_value=self_attn_past_key_value, ) attention_output = self_attention_outputs[0] outputs = self_attention_outputs[1:-1] present_key_value = self_attention_outputs[-1] if mode=='multimodal': assert encoder_hidden_states is not None, "encoder_hidden_states must be given for cross-attention layers" cross_attention_outputs = self.crossattention( attention_output, attention_mask, head_mask, encoder_hidden_states, encoder_attention_mask, output_attentions=output_attentions, ) attention_output = cross_attention_outputs[0] outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights layer_output = apply_chunking_to_forward( self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output ) outputs = (layer_output,) + outputs outputs = outputs + (present_key_value,) return outputs def feed_forward_chunk(self, attention_output): intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output) return layer_output class BertEncoder(nn.Module): def __init__(self, config): super().__init__() self.config = config self.layer = nn.ModuleList([BertLayer(config,i) for i in range(config.num_hidden_layers)]) self.gradient_checkpointing = False def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, use_cache=None, output_attentions=False, output_hidden_states=False, return_dict=True, mode='multimodal', ): all_hidden_states = () if output_hidden_states else None all_self_attentions = () if output_attentions else None all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None next_decoder_cache = () if use_cache else None for i in range(self.config.num_hidden_layers): layer_module = self.layer[i] if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) layer_head_mask = head_mask[i] if head_mask is not None else None past_key_value = past_key_values[i] if past_key_values is not None else None if self.gradient_checkpointing and self.training: if use_cache: logger.warn( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." ) use_cache = False def create_custom_forward(module): def custom_forward(*inputs): return module(*inputs, past_key_value, output_attentions) return custom_forward layer_outputs = torch.utils.checkpoint.checkpoint( create_custom_forward(layer_module), hidden_states, attention_mask, layer_head_mask, encoder_hidden_states, encoder_attention_mask, mode=mode, ) else: layer_outputs = layer_module( hidden_states, attention_mask, layer_head_mask, encoder_hidden_states, encoder_attention_mask, past_key_value, output_attentions, mode=mode, ) hidden_states = layer_outputs[0] if use_cache: next_decoder_cache += (layer_outputs[-1],) if output_attentions: all_self_attentions = all_self_attentions + (layer_outputs[1],) if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if not return_dict: return tuple( v for v in [ hidden_states, next_decoder_cache, all_hidden_states, all_self_attentions, all_cross_attentions, ] if v is not None ) return BaseModelOutputWithPastAndCrossAttentions( last_hidden_state=hidden_states, past_key_values=next_decoder_cache, hidden_states=all_hidden_states, attentions=all_self_attentions, cross_attentions=all_cross_attentions, ) class BertPooler(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.activation = nn.Tanh() def forward(self, hidden_states): # We "pool" the model by simply taking the hidden state corresponding # to the first token. first_token_tensor = hidden_states[:, 0] pooled_output = self.dense(first_token_tensor) pooled_output = self.activation(pooled_output) return pooled_output class BertPredictionHeadTransform(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) if isinstance(config.hidden_act, str): self.transform_act_fn = ACT2FN[config.hidden_act] else: self.transform_act_fn = config.hidden_act self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.transform_act_fn(hidden_states) hidden_states = self.LayerNorm(hidden_states) return hidden_states class BertLMPredictionHead(nn.Module): def __init__(self, config): super().__init__() self.transform = BertPredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = self.decoder(hidden_states) return hidden_states class BertOnlyMLMHead(nn.Module): def __init__(self, config): super().__init__() self.predictions = BertLMPredictionHead(config) def forward(self, sequence_output): prediction_scores = self.predictions(sequence_output) return prediction_scores class BertPreTrainedModel(PreTrainedModel): config_class = BertConfig base_model_prefix = "bert" _keys_to_ignore_on_load_missing = [r"position_ids"] def _init_weights(self, module): if isinstance(module, (nn.Linear, nn.Embedding)): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) elif isinstance(module, nn.LayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) if isinstance(module, nn.Linear) and module.bias is not None: module.bias.data.zero_() class BertModel(BertPreTrainedModel): def __init__(self, config, add_pooling_layer=True): super().__init__(config) self.config = config self.embeddings = BertEmbeddings(config) self.encoder = BertEncoder(config) self.pooler = BertPooler(config) if add_pooling_layer else None self.init_weights() def get_input_embeddings(self): return self.embeddings.word_embeddings def set_input_embeddings(self, value): self.embeddings.word_embeddings = value def _prune_heads(self, heads_to_prune): for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(heads) def get_extended_attention_mask(self, attention_mask: Tensor, input_shape: Tuple[int], device: device, is_decoder: bool) -> Tensor: # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. if attention_mask.dim() == 3: extended_attention_mask = attention_mask[:, None, :, :] elif attention_mask.dim() == 2: # Provided a padding mask of dimensions [batch_size, seq_length] # - if the model is a decoder, apply a causal mask in addition to the padding mask # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length] if is_decoder: batch_size, seq_length = input_shape seq_ids = torch.arange(seq_length, device=device) causal_mask = seq_ids[None, None, :].repeat(batch_size, seq_length, 1) <= seq_ids[None, :, None] # in case past_key_values are used we need to add a prefix ones mask to the causal mask # causal and attention masks must have same type with pytorch version < 1.3 causal_mask = causal_mask.to(attention_mask.dtype) if causal_mask.shape[1] < attention_mask.shape[1]: prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1] causal_mask = torch.cat( [ torch.ones((batch_size, seq_length, prefix_seq_len), device=device, dtype=causal_mask.dtype), causal_mask, ], axis=-1, ) extended_attention_mask = causal_mask[:, None, :, :] * attention_mask[:, None, None, :] else: extended_attention_mask = attention_mask[:, None, None, :] else: raise ValueError( "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format( input_shape, attention_mask.shape ) ) # Since attention_mask is 1.0 for positions we want to attend and 0.0 for # masked positions, this operation will create a tensor which is 0.0 for # positions we want to attend and -10000.0 for masked positions. # Since we are adding it to the raw scores before the softmax, this is # effectively the same as removing these entirely. extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0 return extended_attention_mask def forward( self, input_ids=None, attention_mask=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None, is_decoder=False, mode='multimodal', ): output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict if is_decoder: use_cache = use_cache if use_cache is not None else self.config.use_cache else: use_cache = False if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_shape = input_ids.size() batch_size, seq_length = input_shape device = input_ids.device elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] batch_size, seq_length = input_shape device = inputs_embeds.device elif encoder_embeds is not None: input_shape = encoder_embeds.size()[:-1] batch_size, seq_length = input_shape device = encoder_embeds.device else: raise ValueError("You have to specify either input_ids or inputs_embeds or encoder_embeds") # past_key_values_length past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0 if attention_mask is None: attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape, device, is_decoder) # If a 2D or 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_hidden_states is not None: if type(encoder_hidden_states) == list: encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[0].size() else: encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size() encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) if type(encoder_attention_mask) == list: encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask] elif encoder_attention_mask is None: encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) else: encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) else: encoder_extended_attention_mask = None # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) if encoder_embeds is None: embedding_output = self.embeddings( input_ids=input_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, past_key_values_length=past_key_values_length, ) else: embedding_output = encoder_embeds encoder_outputs = self.encoder( embedding_output, attention_mask=extended_attention_mask, head_mask=head_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_extended_attention_mask, past_key_values=past_key_values, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, mode=mode, ) sequence_output = encoder_outputs[0] pooled_output = self.pooler(sequence_output) if self.pooler is not None else None if not return_dict: return (sequence_output, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndCrossAttentions( last_hidden_state=sequence_output, pooler_output=pooled_output, past_key_values=encoder_outputs.past_key_values, hidden_states=encoder_outputs.hidden_states, attentions=encoder_outputs.attentions, cross_attentions=encoder_outputs.cross_attentions, ) class BertLMHeadModel(BertPreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"] def __init__(self, config): super().__init__(config) self.bert = BertModel(config, add_pooling_layer=False) self.cls = BertOnlyMLMHead(config) self.init_weights() def get_output_embeddings(self): return self.cls.predictions.decoder def set_output_embeddings(self, new_embeddings): self.cls.predictions.decoder = new_embeddings def forward( self, input_ids=None, attention_mask=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, labels=None, past_key_values=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None, return_logits=False, is_decoder=True, reduction='mean', mode='multimodal', ): return_dict = return_dict if return_dict is not None else self.config.use_return_dict if labels is not None: use_cache = False outputs = self.bert( input_ids, attention_mask=attention_mask, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, past_key_values=past_key_values, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, is_decoder=is_decoder, mode=mode, ) sequence_output = outputs[0] prediction_scores = self.cls(sequence_output) if return_logits: return prediction_scores[:, :-1, :].contiguous() lm_loss = None if labels is not None: # we are doing next-token prediction; shift prediction scores and input ids by one shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous() labels = labels[:, 1:].contiguous() loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=0.1) lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) if reduction=='none': lm_loss = lm_loss.view(prediction_scores.size(0),-1).sum(1) if not return_dict: output = (prediction_scores,) + outputs[2:] return ((lm_loss,) + output) if lm_loss is not None else output return CausalLMOutputWithCrossAttentions( loss=lm_loss, logits=prediction_scores, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions, ) def prepare_inputs_for_generation(self, input_ids, past=None, attention_mask=None, **model_kwargs): input_shape = input_ids.shape # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly if attention_mask is None: attention_mask = input_ids.new_ones(input_shape) # cut decoder_input_ids if past is used if past is not None: input_ids = input_ids[:, -1:] return { "input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past, "encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None), "encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None), "is_decoder": True, } def _reorder_cache(self, past, beam_idx): reordered_past = () for layer_past in past: reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),) return reordered_past
--- +++ @@ -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://github.com/huggingface/transformers/blob/v4.15.0/src/transformers/models/bert +''' import math import os @@ -41,6 +50,7 @@ class BertEmbeddings(nn.Module): + """Construct the embeddings from word and position embeddings.""" def __init__(self, config): super().__init__() @@ -536,12 +546,17 @@ class BertPreTrainedModel(PreTrainedModel): + """ + An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained + models. + """ config_class = BertConfig base_model_prefix = "bert" _keys_to_ignore_on_load_missing = [r"position_ids"] def _init_weights(self, module): + """ Initialize the weights """ if isinstance(module, (nn.Linear, nn.Embedding)): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 @@ -554,6 +569,14 @@ class BertModel(BertPreTrainedModel): + """ + The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of + cross-attention is added between the self-attention layers, following the architecture described in `Attention is + all you need <https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, + Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. + argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an + input to the forward pass. + """ def __init__(self, config, add_pooling_layer=True): super().__init__(config) @@ -575,11 +598,29 @@ self.embeddings.word_embeddings = value def _prune_heads(self, heads_to_prune): + """ + Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base + class PreTrainedModel + """ for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(heads) def get_extended_attention_mask(self, attention_mask: Tensor, input_shape: Tuple[int], device: device, is_decoder: bool) -> Tensor: + """ + Makes broadcastable attention and causal masks so that future and masked tokens are ignored. + + Arguments: + attention_mask (:obj:`torch.Tensor`): + Mask with ones indicating tokens to attend to, zeros for tokens to ignore. + input_shape (:obj:`Tuple[int]`): + The shape of the input to the model. + device: (:obj:`torch.device`): + The device of the input to the model. + + Returns: + :obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`. + """ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. if attention_mask.dim() == 3: @@ -644,6 +685,24 @@ is_decoder=False, mode='multimodal', ): + r""" + encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): + Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if + the model is configured as a decoder. + encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): + Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in + the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``: + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): + Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. + If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` + (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` + instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`. + use_cache (:obj:`bool`, `optional`): + If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up + decoding (see :obj:`past_key_values`). + """ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states @@ -788,6 +847,38 @@ reduction='mean', mode='multimodal', ): + r""" + encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): + Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if + the model is configured as a decoder. + encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): + Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in + the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``: + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): + Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in + ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are + ignored (masked), the loss is only computed for the tokens with labels n ``[0, ..., config.vocab_size]`` + past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): + Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. + If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` + (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` + instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`. + use_cache (:obj:`bool`, `optional`): + If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up + decoding (see :obj:`past_key_values`). + Returns: + Example:: + >>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig + >>> import torch + >>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased') + >>> config = BertConfig.from_pretrained("bert-base-cased") + >>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config) + >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") + >>> outputs = model(**inputs) + >>> prediction_logits = outputs.logits + """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict if labels is not None: use_cache = False @@ -861,4 +952,4 @@ reordered_past = () for layer_past in past: reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),) - return reordered_past+ return reordered_past
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_conv def checkpoint_wrapper(x): return x class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop) def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x class Attention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads # NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights self.scale = qk_scale or head_dim ** -0.5 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) self.attn_gradients = None self.attention_map = None def save_attn_gradients(self, attn_gradients): self.attn_gradients = attn_gradients def get_attn_gradients(self): return self.attn_gradients def save_attention_map(self, attention_map): self.attention_map = attention_map def get_attention_map(self): return self.attention_map def forward(self, x, register_hook=False): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple) attn = (q @ k.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) if register_hook: self.save_attention_map(attn) attn.register_hook(self.save_attn_gradients) x = (attn @ v).transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x class Block(nn.Module): def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, use_grad_checkpointing=False): super().__init__() self.norm1 = norm_layer(dim) self.attn = Attention( dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) if use_grad_checkpointing: self.attn = checkpoint_wrapper(self.attn) self.mlp = checkpoint_wrapper(self.mlp) def forward(self, x, register_hook=False): x = x + self.drop_path(self.attn(self.norm1(x), register_hook=register_hook)) x = x + self.drop_path(self.mlp(self.norm2(x))) return x class VisionTransformer(nn.Module): def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4., qkv_bias=True, qk_scale=None, representation_size=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0., norm_layer=None, use_grad_checkpointing=False, ckpt_layer=0): super().__init__() self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6) self.patch_embed = PatchEmbed( img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) num_patches = self.patch_embed.num_patches self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim)) self.pos_drop = nn.Dropout(p=drop_rate) dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule self.blocks = nn.ModuleList([ Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, use_grad_checkpointing=(use_grad_checkpointing and i>=depth-ckpt_layer) ) for i in range(depth)]) self.norm = norm_layer(embed_dim) trunc_normal_(self.pos_embed, std=.02) trunc_normal_(self.cls_token, std=.02) self.apply(self._init_weights) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) @torch.jit.ignore def no_weight_decay(self): return {'pos_embed', 'cls_token'} def forward(self, x, register_blk=-1): B = x.shape[0] x = self.patch_embed(x) cls_tokens = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks x = torch.cat((cls_tokens, x), dim=1) x = x + self.pos_embed[:,:x.size(1),:] x = self.pos_drop(x) for i,blk in enumerate(self.blocks): x = blk(x, register_blk==i) x = self.norm(x) return x @torch.jit.ignore() def load_pretrained(self, checkpoint_path, prefix=''): _load_weights(self, checkpoint_path, prefix) @torch.no_grad() def _load_weights(model: VisionTransformer, checkpoint_path: str, prefix: str = ''): import numpy as np def _n2p(w, t=True): if w.ndim == 4 and w.shape[0] == w.shape[1] == w.shape[2] == 1: w = w.flatten() if t: if w.ndim == 4: w = w.transpose([3, 2, 0, 1]) elif w.ndim == 3: w = w.transpose([2, 0, 1]) elif w.ndim == 2: w = w.transpose([1, 0]) return torch.from_numpy(w) w = np.load(checkpoint_path) if not prefix and 'opt/target/embedding/kernel' in w: prefix = 'opt/target/' if hasattr(model.patch_embed, 'backbone'): # hybrid backbone = model.patch_embed.backbone stem_only = not hasattr(backbone, 'stem') stem = backbone if stem_only else backbone.stem stem.conv.weight.copy_(adapt_input_conv(stem.conv.weight.shape[1], _n2p(w[f'{prefix}conv_root/kernel']))) stem.norm.weight.copy_(_n2p(w[f'{prefix}gn_root/scale'])) stem.norm.bias.copy_(_n2p(w[f'{prefix}gn_root/bias'])) if not stem_only: for i, stage in enumerate(backbone.stages): for j, block in enumerate(stage.blocks): bp = f'{prefix}block{i + 1}/unit{j + 1}/' for r in range(3): getattr(block, f'conv{r + 1}').weight.copy_(_n2p(w[f'{bp}conv{r + 1}/kernel'])) getattr(block, f'norm{r + 1}').weight.copy_(_n2p(w[f'{bp}gn{r + 1}/scale'])) getattr(block, f'norm{r + 1}').bias.copy_(_n2p(w[f'{bp}gn{r + 1}/bias'])) if block.downsample is not None: block.downsample.conv.weight.copy_(_n2p(w[f'{bp}conv_proj/kernel'])) block.downsample.norm.weight.copy_(_n2p(w[f'{bp}gn_proj/scale'])) block.downsample.norm.bias.copy_(_n2p(w[f'{bp}gn_proj/bias'])) embed_conv_w = _n2p(w[f'{prefix}embedding/kernel']) else: embed_conv_w = adapt_input_conv( model.patch_embed.proj.weight.shape[1], _n2p(w[f'{prefix}embedding/kernel'])) model.patch_embed.proj.weight.copy_(embed_conv_w) model.patch_embed.proj.bias.copy_(_n2p(w[f'{prefix}embedding/bias'])) model.cls_token.copy_(_n2p(w[f'{prefix}cls'], t=False)) pos_embed_w = _n2p(w[f'{prefix}Transformer/posembed_input/pos_embedding'], t=False) if pos_embed_w.shape != model.pos_embed.shape: pos_embed_w = resize_pos_embed( # resize pos embedding when different size from pretrained weights pos_embed_w, model.pos_embed, getattr(model, 'num_tokens', 1), model.patch_embed.grid_size) model.pos_embed.copy_(pos_embed_w) model.norm.weight.copy_(_n2p(w[f'{prefix}Transformer/encoder_norm/scale'])) model.norm.bias.copy_(_n2p(w[f'{prefix}Transformer/encoder_norm/bias'])) # if isinstance(model.head, nn.Linear) and model.head.bias.shape[0] == w[f'{prefix}head/bias'].shape[-1]: # model.head.weight.copy_(_n2p(w[f'{prefix}head/kernel'])) # model.head.bias.copy_(_n2p(w[f'{prefix}head/bias'])) # if isinstance(getattr(model.pre_logits, 'fc', None), nn.Linear) and f'{prefix}pre_logits/bias' in w: # model.pre_logits.fc.weight.copy_(_n2p(w[f'{prefix}pre_logits/kernel'])) # model.pre_logits.fc.bias.copy_(_n2p(w[f'{prefix}pre_logits/bias'])) for i, block in enumerate(model.blocks.children()): block_prefix = f'{prefix}Transformer/encoderblock_{i}/' mha_prefix = block_prefix + 'MultiHeadDotProductAttention_1/' block.norm1.weight.copy_(_n2p(w[f'{block_prefix}LayerNorm_0/scale'])) block.norm1.bias.copy_(_n2p(w[f'{block_prefix}LayerNorm_0/bias'])) block.attn.qkv.weight.copy_(torch.cat([ _n2p(w[f'{mha_prefix}{n}/kernel'], t=False).flatten(1).T for n in ('query', 'key', 'value')])) block.attn.qkv.bias.copy_(torch.cat([ _n2p(w[f'{mha_prefix}{n}/bias'], t=False).reshape(-1) for n in ('query', 'key', 'value')])) block.attn.proj.weight.copy_(_n2p(w[f'{mha_prefix}out/kernel']).flatten(1)) block.attn.proj.bias.copy_(_n2p(w[f'{mha_prefix}out/bias'])) for r in range(2): getattr(block.mlp, f'fc{r + 1}').weight.copy_(_n2p(w[f'{block_prefix}MlpBlock_3/Dense_{r}/kernel'])) getattr(block.mlp, f'fc{r + 1}').bias.copy_(_n2p(w[f'{block_prefix}MlpBlock_3/Dense_{r}/bias'])) block.norm2.weight.copy_(_n2p(w[f'{block_prefix}LayerNorm_2/scale'])) block.norm2.bias.copy_(_n2p(w[f'{block_prefix}LayerNorm_2/bias'])) def interpolate_pos_embed(pos_embed_checkpoint, visual_encoder): # interpolate position embedding embedding_size = pos_embed_checkpoint.shape[-1] num_patches = visual_encoder.patch_embed.num_patches num_extra_tokens = visual_encoder.pos_embed.shape[-2] - num_patches # height (== width) for the checkpoint position embedding orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5) # height (== width) for the new position embedding new_size = int(num_patches ** 0.5) if orig_size!=new_size: # class_token and dist_token are kept unchanged extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens] # only the position tokens are interpolated pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:] pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2) pos_tokens = torch.nn.functional.interpolate( pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False) pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2) new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1) print('reshape position embedding from %d to %d'%(orig_size ** 2,new_size ** 2)) return new_pos_embed else: return pos_embed_checkpoint
--- +++ @@ -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.com/rwightman/pytorch-image-models/tree/master/timm +''' import torch import torch.nn as nn @@ -15,6 +24,8 @@ class Mlp(nn.Module): + """ MLP as used in Vision Transformer, MLP-Mixer and related networks + """ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features @@ -103,10 +114,32 @@ class VisionTransformer(nn.Module): + """ Vision Transformer + A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` - + https://arxiv.org/abs/2010.11929 + """ def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4., qkv_bias=True, qk_scale=None, representation_size=None, drop_rate=0., attn_drop_rate=0., drop_path_rate=0., norm_layer=None, use_grad_checkpointing=False, ckpt_layer=0): + """ + Args: + img_size (int, tuple): input image size + patch_size (int, tuple): patch size + in_chans (int): number of input channels + num_classes (int): number of classes for classification head + embed_dim (int): embedding dimension + depth (int): depth of transformer + num_heads (int): number of attention heads + mlp_ratio (int): ratio of mlp hidden dim to embedding dim + qkv_bias (bool): enable bias for qkv if True + qk_scale (float): override default qk scale of head_dim ** -0.5 if set + representation_size (Optional[int]): enable and set representation layer (pre-logits) to this value if set + drop_rate (float): dropout rate + attn_drop_rate (float): attention dropout rate + drop_path_rate (float): stochastic depth rate + norm_layer: (nn.Module): normalization layer + """ super().__init__() self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6) @@ -170,6 +203,8 @@ @torch.no_grad() def _load_weights(model: VisionTransformer, checkpoint_path: str, prefix: str = ''): + """ Load weights from .npz checkpoints for official Google Brain Flax implementation + """ import numpy as np def _n2p(w, t=True):
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 = parts[0].strip() # 只有当 => 右边有内容时才作为 display_name if len(parts) > 1 and parts[1].strip(): display_name = parts[1].strip() else: word_config = word.strip() # 2. 解析正则表达式 # 规则:以 / 开头,以 / 结尾(可能跟 flags),中间内容贪婪提取 # [a-z]*$ 表示允许末尾有 flags (如 i, g),但在下面代码中会被忽略 regex_match = re.match(r'^/(.+)/[a-z]*$', word_config) if regex_match: pattern_str = regex_match.group(1) try: pattern = re.compile(pattern_str, re.IGNORECASE) return { "word": pattern_str, "is_regex": True, "pattern": pattern, "display_name": display_name, } except re.error as e: print(f"Warning: Invalid regex pattern '/{pattern_str}/': {e}") pass return { "word": word_config, "is_regex": False, "pattern": None, "display_name": display_name } def _word_matches(word_config: Union[str, Dict], title_lower: str) -> bool: if isinstance(word_config, str): # 向后兼容:纯字符串 return word_config.lower() in title_lower if word_config.get("is_regex") and word_config.get("pattern"): # 正则匹配 return bool(word_config["pattern"].search(title_lower)) else: # 子字符串匹配 return word_config["word"].lower() in title_lower def load_frequency_words( frequency_file: Optional[str] = None, ) -> Tuple[List[Dict], List[str], List[str]]: if frequency_file is None: frequency_file = os.environ.get( "FREQUENCY_WORDS_PATH", "config/frequency_words.txt" ) frequency_path = Path(frequency_file) if not frequency_path.exists(): # 尝试作为短文件名,拼接 config/custom/keyword/ 前缀 custom_path = Path("config/custom/keyword") / frequency_file if custom_path.exists(): frequency_path = custom_path else: raise FileNotFoundError(f"频率词文件 {frequency_file} 不存在") with open(frequency_path, "r", encoding="utf-8") as f: content = f.read() word_groups = [group.strip() for group in content.split("\n\n") if group.strip()] processed_groups = [] filter_words = [] global_filters = [] # 默认区域(向后兼容) current_section = "WORD_GROUPS" for group in word_groups: # 过滤空行和注释行(# 开头) lines = [line.strip() for line in group.split("\n") if line.strip() and not line.strip().startswith("#")] if not lines: continue # 检查是否为区域标记 if lines[0].startswith("[") and lines[0].endswith("]"): section_name = lines[0][1:-1].upper() if section_name in ("GLOBAL_FILTER", "WORD_GROUPS"): current_section = section_name lines = lines[1:] # 移除标记行 # 处理全局过滤区域 if current_section == "GLOBAL_FILTER": # 直接添加所有非空行到全局过滤列表 for line in lines: # 忽略特殊语法前缀,只提取纯文本 if line.startswith(("!", "+", "@")): continue # 全局过滤区不支持特殊语法 if line: global_filters.append(line) continue # 处理词组区域 words = lines group_alias = None # 组别名([别名] 语法) # 检查第一行是否为组别名(非区域标记) if words and words[0].startswith("[") and words[0].endswith("]"): potential_alias = words[0][1:-1].strip() # 排除区域标记(GLOBAL_FILTER, WORD_GROUPS) if potential_alias.upper() not in ("GLOBAL_FILTER", "WORD_GROUPS"): group_alias = potential_alias words = words[1:] # 移除组别名行 group_required_words = [] group_normal_words = [] group_max_count = 0 # 默认不限制 for word in words: if word.startswith("@"): # 解析最大显示数量(只接受正整数) try: count = int(word[1:]) if count > 0: group_max_count = count except (ValueError, IndexError): pass # 忽略无效的@数字格式 elif word.startswith("!"): # 过滤词(支持正则语法) filter_word = word[1:] parsed = _parse_word(filter_word) filter_words.append(parsed) elif word.startswith("+"): # 必须词(支持正则语法) req_word = word[1:] group_required_words.append(_parse_word(req_word)) else: # 普通词(支持正则语法) group_normal_words.append(_parse_word(word)) if group_required_words or group_normal_words: if group_normal_words: group_key = " ".join(w["word"] for w in group_normal_words) else: group_key = " ".join(w["word"] for w in group_required_words) # 生成显示名称 # 优先级:组别名 > 行别名拼接 > 关键词拼接 if group_alias: # 有组别名,直接使用 display_name = group_alias else: # 没有组别名,拼接每行的显示名(行别名或关键词本身) all_words = group_normal_words + group_required_words display_parts = [] for w in all_words: # 优先使用行别名,否则使用关键词本身 part = w.get("display_name") or w["word"] display_parts.append(part) # 用 " / " 拼接多个词 display_name = " / ".join(display_parts) if display_parts else None processed_groups.append( { "required": group_required_words, "normal": group_normal_words, "group_key": group_key, "display_name": display_name, # 可能为 None "max_count": group_max_count, } ) return processed_groups, filter_words, global_filters def matches_word_groups( title: str, word_groups: List[Dict], filter_words: List, global_filters: Optional[List[str]] = None ) -> bool: # 防御性类型检查:确保 title 是有效字符串 if not isinstance(title, str): title = str(title) if title is not None else "" if not title.strip(): return False title_lower = title.lower() # 全局过滤检查(优先级最高) if global_filters: if any(global_word.lower() in title_lower for global_word in global_filters): return False # 如果没有配置词组,则匹配所有标题(支持显示全部新闻) if not word_groups: return True # 过滤词检查(兼容新旧格式) for filter_item in filter_words: if _word_matches(filter_item, title_lower): return False # 词组匹配检查 for group in word_groups: required_words = group["required"] normal_words = group["normal"] # 必须词检查 if required_words: all_required_present = all( _word_matches(req_item, title_lower) for req_item in required_words ) if not all_required_present: continue # 普通词检查 if normal_words: any_normal_present = any( _word_matches(normal_item, title_lower) for normal_item in normal_words ) if not any_normal_present: continue return True return False
--- +++ @@ -1,4 +1,17 @@ # coding=utf-8 +""" +频率词配置加载模块 + +负责从配置文件加载频率词规则,支持: +- 普通词组 +- 必须词(+前缀) +- 过滤词(!前缀) +- 全局过滤词([GLOBAL_FILTER] 区域) +- 最大显示数量(@前缀) +- 正则表达式(/pattern/ 语法) +- 显示名称(=> 别名 语法) +- 组别名([组别名] 语法,作为词组第一行) +""" import os import re @@ -7,6 +20,15 @@ def _parse_word(word: str) -> Dict: + """ + 解析单个词,识别是否为正则表达式,支持显示名称 + + Args: + word: 原始配置行 (e.g. "/京东|刘强东/ => 京东") + + Returns: + Dict: 包含 word, is_regex, pattern, display_name + """ display_name = None # 1. 优先处理显示名称 (=>) @@ -49,6 +71,16 @@ def _word_matches(word_config: Union[str, Dict], title_lower: str) -> bool: + """ + 检查词是否在标题中匹配 + + Args: + word_config: 词配置(字符串或字典) + title_lower: 小写的标题 + + Returns: + 是否匹配 + """ if isinstance(word_config, str): # 向后兼容:纯字符串 return word_config.lower() in title_lower @@ -64,6 +96,29 @@ def load_frequency_words( frequency_file: Optional[str] = None, ) -> Tuple[List[Dict], List[str], List[str]]: + """ + 加载频率词配置 + + 配置文件格式说明: + - 每个词组由空行分隔 + - [GLOBAL_FILTER] 区域定义全局过滤词 + - [WORD_GROUPS] 区域定义词组(默认) + + 词组语法: + - 普通词:直接写入,任意匹配即可 + - +词:必须词,所有必须词都要匹配 + - !词:过滤词,匹配则排除 + - @数字:该词组最多显示的条数 + + Args: + frequency_file: 频率词配置文件路径,默认从环境变量 FREQUENCY_WORDS_PATH 获取或使用 config/frequency_words.txt,短文件名从 config/custom/keyword/ 查找 + + Returns: + (词组列表, 词组内过滤词, 全局过滤词) + + Raises: + FileNotFoundError: 频率词文件不存在 + """ if frequency_file is None: frequency_file = os.environ.get( "FREQUENCY_WORDS_PATH", "config/frequency_words.txt" @@ -194,6 +249,18 @@ filter_words: List, global_filters: Optional[List[str]] = None ) -> bool: + """ + 检查标题是否匹配词组规则 + + Args: + title: 标题文本 + word_groups: 词组列表 + filter_words: 过滤词列表(可以是字符串列表或字典列表) + global_filters: 全局过滤词列表 + + Returns: + 是否匹配 + """ # 防御性类型检查:确保 title 是有效字符串 if not isinstance(title, str): title = str(title) if title is not None else "" @@ -239,4 +306,4 @@ return True - return False+ return False
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.72990036, 92.20410156]] DEFAULT_CROP_SIZE = (96, 112) class FaceWarpException(Exception): def __str__(self): return 'In File {}:{}'.format(__file__, super.__str__(self)) def get_reference_facial_points(output_size=None, inner_padding_factor=0.0, outer_padding=(0, 0), default_square=False): tmp_5pts = np.array(REFERENCE_FACIAL_POINTS) tmp_crop_size = np.array(DEFAULT_CROP_SIZE) # 0) make the inner region a square if default_square: size_diff = max(tmp_crop_size) - tmp_crop_size tmp_5pts += size_diff / 2 tmp_crop_size += size_diff if (output_size and output_size[0] == tmp_crop_size[0] and output_size[1] == tmp_crop_size[1]): return tmp_5pts if (inner_padding_factor == 0 and outer_padding == (0, 0)): if output_size is None: return tmp_5pts else: raise FaceWarpException('No paddings to do, output_size must be None or {}'.format(tmp_crop_size)) # check output size if not (0 <= inner_padding_factor <= 1.0): raise FaceWarpException('Not (0 <= inner_padding_factor <= 1.0)') if ((inner_padding_factor > 0 or outer_padding[0] > 0 or outer_padding[1] > 0) and output_size is None): output_size = tmp_crop_size * \ (1 + inner_padding_factor * 2).astype(np.int32) output_size += np.array(outer_padding) if not (outer_padding[0] < output_size[0] and outer_padding[1] < output_size[1]): raise FaceWarpException('Not (outer_padding[0] < output_size[0] and outer_padding[1] < output_size[1])') # 1) pad the inner region according inner_padding_factor if inner_padding_factor > 0: size_diff = tmp_crop_size * inner_padding_factor * 2 tmp_5pts += size_diff / 2 tmp_crop_size += np.round(size_diff).astype(np.int32) # 2) resize the padded inner region size_bf_outer_pad = np.array(output_size) - np.array(outer_padding) * 2 if size_bf_outer_pad[0] * tmp_crop_size[1] != size_bf_outer_pad[1] * tmp_crop_size[0]: raise FaceWarpException('Must have (output_size - outer_padding)' '= some_scale * (crop_size * (1.0 + inner_padding_factor)') scale_factor = size_bf_outer_pad[0].astype(np.float32) / tmp_crop_size[0] tmp_5pts = tmp_5pts * scale_factor # size_diff = tmp_crop_size * (scale_factor - min(scale_factor)) # tmp_5pts = tmp_5pts + size_diff / 2 tmp_crop_size = size_bf_outer_pad # 3) add outer_padding to make output_size reference_5point = tmp_5pts + np.array(outer_padding) tmp_crop_size = output_size return reference_5point def get_affine_transform_matrix(src_pts, dst_pts): tfm = np.float32([[1, 0, 0], [0, 1, 0]]) n_pts = src_pts.shape[0] ones = np.ones((n_pts, 1), src_pts.dtype) src_pts_ = np.hstack([src_pts, ones]) dst_pts_ = np.hstack([dst_pts, ones]) A, res, rank, s = np.linalg.lstsq(src_pts_, dst_pts_) if rank == 3: tfm = np.float32([[A[0, 0], A[1, 0], A[2, 0]], [A[0, 1], A[1, 1], A[2, 1]]]) elif rank == 2: tfm = np.float32([[A[0, 0], A[1, 0], 0], [A[0, 1], A[1, 1], 0]]) return tfm def warp_and_crop_face(src_img, facial_pts, reference_pts=None, crop_size=(96, 112), align_type='smilarity'): if reference_pts is None: if crop_size[0] == 96 and crop_size[1] == 112: reference_pts = REFERENCE_FACIAL_POINTS else: default_square = False inner_padding_factor = 0 outer_padding = (0, 0) output_size = crop_size reference_pts = get_reference_facial_points(output_size, inner_padding_factor, outer_padding, default_square) ref_pts = np.float32(reference_pts) ref_pts_shp = ref_pts.shape if max(ref_pts_shp) < 3 or min(ref_pts_shp) != 2: raise FaceWarpException('reference_pts.shape must be (K,2) or (2,K) and K>2') if ref_pts_shp[0] == 2: ref_pts = ref_pts.T src_pts = np.float32(facial_pts) src_pts_shp = src_pts.shape if max(src_pts_shp) < 3 or min(src_pts_shp) != 2: raise FaceWarpException('facial_pts.shape must be (K,2) or (2,K) and K>2') if src_pts_shp[0] == 2: src_pts = src_pts.T if src_pts.shape != ref_pts.shape: raise FaceWarpException('facial_pts and reference_pts must have the same shape') if align_type == 'cv2_affine': tfm = cv2.getAffineTransform(src_pts[0:3], ref_pts[0:3]) elif align_type == 'affine': tfm = get_affine_transform_matrix(src_pts, ref_pts) else: tfm = get_similarity_transform_for_cv2(src_pts, ref_pts) face_img = cv2.warpAffine(src_img, tfm, (crop_size[0], crop_size[1])) return face_img
--- +++ @@ -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_square: + crop_size = (112, 112) + else: + crop_size = (96, 112) + 1. Pad the crop_size by inner_padding_factor in each side; + 2. Resize crop_size into (output_size - outer_padding*2), + pad into output_size with outer_padding; + 3. Output reference_5point; + Parameters: + ---------- + @output_size: (w, h) or None + size of aligned face image + @inner_padding_factor: (w_factor, h_factor) + padding factor for inner (w, h) + @outer_padding: (w_pad, h_pad) + each row is a pair of coordinates (x, y) + @default_square: True or False + if True: + default crop_size = (112, 112) + else: + default crop_size = (96, 112); + !!! make sure, if output_size is not None: + (output_size - outer_padding) + = some_scale * (default crop_size * (1.0 + + inner_padding_factor)) + Returns: + ---------- + @reference_5point: 5x2 np.array + each row is a pair of transformed coordinates (x, y) + """ tmp_5pts = np.array(REFERENCE_FACIAL_POINTS) tmp_crop_size = np.array(DEFAULT_CROP_SIZE) @@ -75,6 +110,21 @@ def get_affine_transform_matrix(src_pts, dst_pts): + """ + Function: + ---------- + get affine transform matrix 'tfm' from src_pts to dst_pts + Parameters: + ---------- + @src_pts: Kx2 np.array + source points matrix, each row is a pair of coordinates (x, y) + @dst_pts: Kx2 np.array + destination points matrix, each row is a pair of coordinates (x, y) + Returns: + ---------- + @tfm: 2x3 np.array + transform matrix from src_pts to dst_pts + """ tfm = np.float32([[1, 0, 0], [0, 1, 0]]) n_pts = src_pts.shape[0] @@ -93,6 +143,38 @@ def warp_and_crop_face(src_img, facial_pts, reference_pts=None, crop_size=(96, 112), align_type='smilarity'): + """ + Function: + ---------- + apply affine transform 'trans' to uv + Parameters: + ---------- + @src_img: 3x3 np.array + input image + @facial_pts: could be + 1)a list of K coordinates (x,y) + or + 2) Kx2 or 2xK np.array + each row or col is a pair of coordinates (x, y) + @reference_pts: could be + 1) a list of K coordinates (x,y) + or + 2) Kx2 or 2xK np.array + each row or col is a pair of coordinates (x, y) + or + 3) None + if None, use default reference facial points + @crop_size: (w, h) + output face image size + @align_type: transform type, could be one of + 1) 'similarity': use similarity transform + 2) 'cv2_affine': use the first 3 points to do affine transform, + by calling cv2.getAffineTransform() + 3) 'affine': use all points to do affine transform + Returns: + ---------- + @face_img: output face image with size (w, h) = @crop_size + """ if reference_pts is None: if crop_size[0] == 96 and crop_size[1] == 112: @@ -134,4 +216,4 @@ face_img = cv2.warpAffine(src_img, tfm, (crop_size[0], crop_size[1])) - return face_img+ return face_img
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'] self.clip = cfg['clip'] self.image_size = image_size self.feature_maps = [[ceil(self.image_size[0] / step), ceil(self.image_size[1] / step)] for step in self.steps] self.name = 's' def forward(self): anchors = [] for k, f in enumerate(self.feature_maps): min_sizes = self.min_sizes[k] for i, j in product(range(f[0]), range(f[1])): for min_size in min_sizes: s_kx = min_size / self.image_size[1] s_ky = min_size / self.image_size[0] dense_cx = [x * self.steps[k] / self.image_size[1] for x in [j + 0.5]] dense_cy = [y * self.steps[k] / self.image_size[0] for y in [i + 0.5]] for cy, cx in product(dense_cy, dense_cx): anchors += [cx, cy, s_kx, s_ky] # back to torch land output = torch.Tensor(anchors).view(-1, 4) if self.clip: output.clamp_(max=1, min=0) return output def py_cpu_nms(dets, thresh): keep = torchvision.ops.nms( boxes=torch.Tensor(dets[:, :4]), scores=torch.Tensor(dets[:, 4]), iou_threshold=thresh, ) return list(keep) def point_form(boxes): return torch.cat( ( boxes[:, :2] - boxes[:, 2:] / 2, # xmin, ymin boxes[:, :2] + boxes[:, 2:] / 2), 1) # xmax, ymax def center_size(boxes): return torch.cat( (boxes[:, 2:] + boxes[:, :2]) / 2, # cx, cy boxes[:, 2:] - boxes[:, :2], 1) # w, h def intersect(box_a, box_b): A = box_a.size(0) B = box_b.size(0) max_xy = torch.min(box_a[:, 2:].unsqueeze(1).expand(A, B, 2), box_b[:, 2:].unsqueeze(0).expand(A, B, 2)) min_xy = torch.max(box_a[:, :2].unsqueeze(1).expand(A, B, 2), box_b[:, :2].unsqueeze(0).expand(A, B, 2)) inter = torch.clamp((max_xy - min_xy), min=0) return inter[:, :, 0] * inter[:, :, 1] def jaccard(box_a, box_b): inter = intersect(box_a, box_b) area_a = ((box_a[:, 2] - box_a[:, 0]) * (box_a[:, 3] - box_a[:, 1])).unsqueeze(1).expand_as(inter) # [A,B] area_b = ((box_b[:, 2] - box_b[:, 0]) * (box_b[:, 3] - box_b[:, 1])).unsqueeze(0).expand_as(inter) # [A,B] union = area_a + area_b - inter return inter / union # [A,B] def matrix_iou(a, b): lt = np.maximum(a[:, np.newaxis, :2], b[:, :2]) rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:]) area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2) area_a = np.prod(a[:, 2:] - a[:, :2], axis=1) area_b = np.prod(b[:, 2:] - b[:, :2], axis=1) return area_i / (area_a[:, np.newaxis] + area_b - area_i) def matrix_iof(a, b): lt = np.maximum(a[:, np.newaxis, :2], b[:, :2]) rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:]) area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2) area_a = np.prod(a[:, 2:] - a[:, :2], axis=1) return area_i / np.maximum(area_a[:, np.newaxis], 1) def match(threshold, truths, priors, variances, labels, landms, loc_t, conf_t, landm_t, idx): # jaccard index overlaps = jaccard(truths, point_form(priors)) # (Bipartite Matching) # [1,num_objects] best prior for each ground truth best_prior_overlap, best_prior_idx = overlaps.max(1, keepdim=True) # ignore hard gt valid_gt_idx = best_prior_overlap[:, 0] >= 0.2 best_prior_idx_filter = best_prior_idx[valid_gt_idx, :] if best_prior_idx_filter.shape[0] <= 0: loc_t[idx] = 0 conf_t[idx] = 0 return # [1,num_priors] best ground truth for each prior best_truth_overlap, best_truth_idx = overlaps.max(0, keepdim=True) best_truth_idx.squeeze_(0) best_truth_overlap.squeeze_(0) best_prior_idx.squeeze_(1) best_prior_idx_filter.squeeze_(1) best_prior_overlap.squeeze_(1) best_truth_overlap.index_fill_(0, best_prior_idx_filter, 2) # ensure best prior # TODO refactor: index best_prior_idx with long tensor # ensure every gt matches with its prior of max overlap for j in range(best_prior_idx.size(0)): # 判别此anchor是预测哪一个boxes best_truth_idx[best_prior_idx[j]] = j matches = truths[best_truth_idx] # Shape: [num_priors,4] 此处为每一个anchor对应的bbox取出来 conf = labels[best_truth_idx] # Shape: [num_priors] 此处为每一个anchor对应的label取出来 conf[best_truth_overlap < threshold] = 0 # label as background overlap<0.35的全部作为负样本 loc = encode(matches, priors, variances) matches_landm = landms[best_truth_idx] landm = encode_landm(matches_landm, priors, variances) loc_t[idx] = loc # [num_priors,4] encoded offsets to learn conf_t[idx] = conf # [num_priors] top class label for each prior landm_t[idx] = landm def encode(matched, priors, variances): # dist b/t match center and prior's center g_cxcy = (matched[:, :2] + matched[:, 2:]) / 2 - priors[:, :2] # encode variance g_cxcy /= (variances[0] * priors[:, 2:]) # match wh / prior wh g_wh = (matched[:, 2:] - matched[:, :2]) / priors[:, 2:] g_wh = torch.log(g_wh) / variances[1] # return target for smooth_l1_loss return torch.cat([g_cxcy, g_wh], 1) # [num_priors,4] def encode_landm(matched, priors, variances): # dist b/t match center and prior's center matched = torch.reshape(matched, (matched.size(0), 5, 2)) priors_cx = priors[:, 0].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2) priors_cy = priors[:, 1].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2) priors_w = priors[:, 2].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2) priors_h = priors[:, 3].unsqueeze(1).expand(matched.size(0), 5).unsqueeze(2) priors = torch.cat([priors_cx, priors_cy, priors_w, priors_h], dim=2) g_cxcy = matched[:, :, :2] - priors[:, :, :2] # encode variance g_cxcy /= (variances[0] * priors[:, :, 2:]) # g_cxcy /= priors[:, :, 2:] g_cxcy = g_cxcy.reshape(g_cxcy.size(0), -1) # return target for smooth_l1_loss return g_cxcy # Adapted from https://github.com/Hakuyume/chainer-ssd def decode(loc, priors, variances): boxes = torch.cat((priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:], priors[:, 2:] * torch.exp(loc[:, 2:] * variances[1])), 1) boxes[:, :2] -= boxes[:, 2:] / 2 boxes[:, 2:] += boxes[:, :2] return boxes def decode_landm(pre, priors, variances): tmp = ( priors[:, :2] + pre[:, :2] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 2:4] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 4:6] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 6:8] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 8:10] * variances[0] * priors[:, 2:], ) landms = torch.cat(tmp, dim=1) return landms def batched_decode(b_loc, priors, variances): boxes = ( priors[:, :, :2] + b_loc[:, :, :2] * variances[0] * priors[:, :, 2:], priors[:, :, 2:] * torch.exp(b_loc[:, :, 2:] * variances[1]), ) boxes = torch.cat(boxes, dim=2) boxes[:, :, :2] -= boxes[:, :, 2:] / 2 boxes[:, :, 2:] += boxes[:, :, :2] return boxes def batched_decode_landm(pre, priors, variances): landms = ( priors[:, :, :2] + pre[:, :, :2] * variances[0] * priors[:, :, 2:], priors[:, :, :2] + pre[:, :, 2:4] * variances[0] * priors[:, :, 2:], priors[:, :, :2] + pre[:, :, 4:6] * variances[0] * priors[:, :, 2:], priors[:, :, :2] + pre[:, :, 6:8] * variances[0] * priors[:, :, 2:], priors[:, :, :2] + pre[:, :, 8:10] * variances[0] * priors[:, :, 2:], ) landms = torch.cat(landms, dim=2) return landms def log_sum_exp(x): x_max = x.data.max() return torch.log(torch.sum(torch.exp(x - x_max), 1, keepdim=True)) + x_max # Original author: Francisco Massa: # https://github.com/fmassa/object-detection.torch # Ported to PyTorch by Max deGroot (02/01/2017) def nms(boxes, scores, overlap=0.5, top_k=200): keep = torch.Tensor(scores.size(0)).fill_(0).long() if boxes.numel() == 0: return keep x1 = boxes[:, 0] y1 = boxes[:, 1] x2 = boxes[:, 2] y2 = boxes[:, 3] area = torch.mul(x2 - x1, y2 - y1) v, idx = scores.sort(0) # sort in ascending order # I = I[v >= 0.01] idx = idx[-top_k:] # indices of the top-k largest vals xx1 = boxes.new() yy1 = boxes.new() xx2 = boxes.new() yy2 = boxes.new() w = boxes.new() h = boxes.new() # keep = torch.Tensor() count = 0 while idx.numel() > 0: i = idx[-1] # index of current largest val # keep.append(i) keep[count] = i count += 1 if idx.size(0) == 1: break idx = idx[:-1] # remove kept element from view # load bboxes of next highest vals torch.index_select(x1, 0, idx, out=xx1) torch.index_select(y1, 0, idx, out=yy1) torch.index_select(x2, 0, idx, out=xx2) torch.index_select(y2, 0, idx, out=yy2) # store element-wise max with next highest score xx1 = torch.clamp(xx1, min=x1[i]) yy1 = torch.clamp(yy1, min=y1[i]) xx2 = torch.clamp(xx2, max=x2[i]) yy2 = torch.clamp(yy2, max=y2[i]) w.resize_as_(xx2) h.resize_as_(yy2) w = xx2 - xx1 h = yy2 - yy1 # check sizes of xx1 and xx2.. after each iteration w = torch.clamp(w, min=0.0) h = torch.clamp(h, min=0.0) inter = w * h # IoU = i / (area(a) + area(b) - i) rem_areas = torch.index_select(area, 0, idx) # load remaining areas) union = (rem_areas - inter) + area[i] IoU = inter / union # store result in iou # keep only elements with an IoU <= overlap idx = idx[IoU.le(overlap)] return keep, count
--- +++ @@ -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) + representation for comparison to point form ground truth data. + Args: + boxes: (tensor) center-size default boxes from priorbox layers. + Return: + boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes. + """ return torch.cat( ( boxes[:, :2] - boxes[:, 2:] / 2, # xmin, ymin @@ -55,6 +63,13 @@ def center_size(boxes): + """ Convert prior_boxes to (cx, cy, w, h) + representation for comparison to center-size form ground truth data. + Args: + boxes: (tensor) point_form boxes + Return: + boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes. + """ return torch.cat( (boxes[:, 2:] + boxes[:, :2]) / 2, # cx, cy boxes[:, 2:] - boxes[:, :2], @@ -62,6 +77,16 @@ def intersect(box_a, box_b): + """ We resize both tensors to [A,B,2] without new malloc: + [A,2] -> [A,1,2] -> [A,B,2] + [B,2] -> [1,B,2] -> [A,B,2] + Then we compute the area of intersect between box_a and box_b. + Args: + box_a: (tensor) bounding boxes, Shape: [A,4]. + box_b: (tensor) bounding boxes, Shape: [B,4]. + Return: + (tensor) intersection area, Shape: [A,B]. + """ A = box_a.size(0) B = box_b.size(0) max_xy = torch.min(box_a[:, 2:].unsqueeze(1).expand(A, B, 2), box_b[:, 2:].unsqueeze(0).expand(A, B, 2)) @@ -71,6 +96,17 @@ def jaccard(box_a, box_b): + """Compute the jaccard overlap of two sets of boxes. The jaccard overlap + is simply the intersection over union of two boxes. Here we operate on + ground truth boxes and default boxes. + E.g.: + A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B) + Args: + box_a: (tensor) Ground truth bounding boxes, Shape: [num_objects,4] + box_b: (tensor) Prior boxes from priorbox layers, Shape: [num_priors,4] + Return: + jaccard overlap: (tensor) Shape: [box_a.size(0), box_b.size(0)] + """ inter = intersect(box_a, box_b) area_a = ((box_a[:, 2] - box_a[:, 0]) * (box_a[:, 3] - box_a[:, 1])).unsqueeze(1).expand_as(inter) # [A,B] area_b = ((box_b[:, 2] - box_b[:, 0]) * (box_b[:, 3] - box_b[:, 1])).unsqueeze(0).expand_as(inter) # [A,B] @@ -79,6 +115,9 @@ def matrix_iou(a, b): + """ + return iou of a and b, numpy version for data augenmentation + """ lt = np.maximum(a[:, np.newaxis, :2], b[:, :2]) rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:]) @@ -89,6 +128,9 @@ def matrix_iof(a, b): + """ + return iof of a and b, numpy version for data augenmentation + """ lt = np.maximum(a[:, np.newaxis, :2], b[:, :2]) rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:]) @@ -98,6 +140,25 @@ def match(threshold, truths, priors, variances, labels, landms, loc_t, conf_t, landm_t, idx): + """Match each prior box with the ground truth box of the highest jaccard + overlap, encode the bounding boxes, then return the matched indices + corresponding to both confidence and location preds. + Args: + threshold: (float) The overlap threshold used when matching boxes. + truths: (tensor) Ground truth boxes, Shape: [num_obj, 4]. + priors: (tensor) Prior boxes from priorbox layers, Shape: [n_priors,4]. + variances: (tensor) Variances corresponding to each prior coord, + Shape: [num_priors, 4]. + labels: (tensor) All the class labels for the image, Shape: [num_obj]. + landms: (tensor) Ground truth landms, Shape [num_obj, 10]. + loc_t: (tensor) Tensor to be filled w/ encoded location targets. + conf_t: (tensor) Tensor to be filled w/ matched indices for conf preds. + landm_t: (tensor) Tensor to be filled w/ encoded landm targets. + idx: (int) current batch index + Return: + The matched indices corresponding to 1)location 2)confidence + 3)landm preds. + """ # jaccard index overlaps = jaccard(truths, point_form(priors)) # (Bipartite Matching) @@ -137,6 +198,17 @@ def encode(matched, priors, variances): + """Encode the variances from the priorbox layers into the ground truth boxes + we have matched (based on jaccard overlap) with the prior boxes. + Args: + matched: (tensor) Coords of ground truth for each prior in point-form + Shape: [num_priors, 4]. + priors: (tensor) Prior boxes in center-offset form + Shape: [num_priors,4]. + variances: (list[float]) Variances of priorboxes + Return: + encoded boxes (tensor), Shape: [num_priors, 4] + """ # dist b/t match center and prior's center g_cxcy = (matched[:, :2] + matched[:, 2:]) / 2 - priors[:, :2] @@ -150,6 +222,17 @@ def encode_landm(matched, priors, variances): + """Encode the variances from the priorbox layers into the ground truth boxes + we have matched (based on jaccard overlap) with the prior boxes. + Args: + matched: (tensor) Coords of ground truth for each prior in point-form + Shape: [num_priors, 10]. + priors: (tensor) Prior boxes in center-offset form + Shape: [num_priors,4]. + variances: (list[float]) Variances of priorboxes + Return: + encoded landm (tensor), Shape: [num_priors, 10] + """ # dist b/t match center and prior's center matched = torch.reshape(matched, (matched.size(0), 5, 2)) @@ -169,6 +252,17 @@ # Adapted from https://github.com/Hakuyume/chainer-ssd def decode(loc, priors, variances): + """Decode locations from predictions using priors to undo + the encoding we did for offset regression at train time. + Args: + loc (tensor): location predictions for loc layers, + Shape: [num_priors,4] + priors (tensor): Prior boxes in center-offset form. + Shape: [num_priors,4]. + variances: (list[float]) Variances of priorboxes + Return: + decoded bounding box predictions + """ boxes = torch.cat((priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:], priors[:, 2:] * torch.exp(loc[:, 2:] * variances[1])), 1) @@ -178,6 +272,17 @@ def decode_landm(pre, priors, variances): + """Decode landm from predictions using priors to undo + the encoding we did for offset regression at train time. + Args: + pre (tensor): landm predictions for loc layers, + Shape: [num_priors,10] + priors (tensor): Prior boxes in center-offset form. + Shape: [num_priors,4]. + variances: (list[float]) Variances of priorboxes + Return: + decoded landm predictions + """ tmp = ( priors[:, :2] + pre[:, :2] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 2:4] * variances[0] * priors[:, 2:], @@ -190,6 +295,17 @@ def batched_decode(b_loc, priors, variances): + """Decode locations from predictions using priors to undo + the encoding we did for offset regression at train time. + Args: + b_loc (tensor): location predictions for loc layers, + Shape: [num_batches,num_priors,4] + priors (tensor): Prior boxes in center-offset form. + Shape: [1,num_priors,4]. + variances: (list[float]) Variances of priorboxes + Return: + decoded bounding box predictions + """ boxes = ( priors[:, :, :2] + b_loc[:, :, :2] * variances[0] * priors[:, :, 2:], priors[:, :, 2:] * torch.exp(b_loc[:, :, 2:] * variances[1]), @@ -202,6 +318,17 @@ def batched_decode_landm(pre, priors, variances): + """Decode landm from predictions using priors to undo + the encoding we did for offset regression at train time. + Args: + pre (tensor): landm predictions for loc layers, + Shape: [num_batches,num_priors,10] + priors (tensor): Prior boxes in center-offset form. + Shape: [1,num_priors,4]. + variances: (list[float]) Variances of priorboxes + Return: + decoded landm predictions + """ landms = ( priors[:, :, :2] + pre[:, :, :2] * variances[0] * priors[:, :, 2:], priors[:, :, :2] + pre[:, :, 2:4] * variances[0] * priors[:, :, 2:], @@ -214,6 +341,12 @@ def log_sum_exp(x): + """Utility function for computing log_sum_exp while determining + This will be used to determine unaveraged confidence loss across + all examples in a batch. + Args: + x (Variable(tensor)): conf_preds from conf layers + """ x_max = x.data.max() return torch.log(torch.sum(torch.exp(x - x_max), 1, keepdim=True)) + x_max @@ -222,6 +355,16 @@ # https://github.com/fmassa/object-detection.torch # Ported to PyTorch by Max deGroot (02/01/2017) def nms(boxes, scores, overlap=0.5, top_k=200): + """Apply non-maximum suppression at test time to avoid detecting too many + overlapping bounding boxes for a given object. + Args: + boxes: (tensor) The location preds for the img, Shape: [num_priors,4]. + scores: (tensor) The class predscores for the img, Shape:[num_priors]. + overlap: (float) The overlap thresh for suppressing unnecessary boxes. + top_k: (int) The Maximum number of box preds to consider. + Return: + The indices of the kept boxes with respect to num_priors. + """ keep = torch.Tensor(scores.size(0)).fill_(0).long() if boxes.numel() == 0: @@ -275,4 +418,4 @@ IoU = inter / union # store result in iou # keep only elements with an IoU <= overlap idx = idx[IoU.le(overlap)] - return keep, count+ return keep, count
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.append(match.group(0)) return f"@@URLTOKEN{len(protected_urls) - 1}@@" text = re.sub(r'https?://[^\s<>\]]+', _protect_url, text) # 去除粗体 **text** 或 __text__ text = re.sub(r'\*\*(.+?)\*\*', r'\1', text) text = re.sub(r'(?<!\w)__(?!\s)(.+?)(?<!\s)__(?!\w)', r'\1', text) # 去除斜体 *text* 或 _text_ text = re.sub(r'\*(.+?)\*', r'\1', text) text = re.sub(r'(?<!\w)_(?!\s)(.+?)(?<!\s)_(?!\w)', r'\1', text) # 去除删除线 ~~text~~ text = re.sub(r'~~(.+?)~~', r'\1', text) # 去除图片 ![alt](url) -> alt text = re.sub(r'!\[(.+?)\]\(.+?\)', r'\1', text) # 去除行内代码 `code` text = re.sub(r'`(.+?)`', r'\1', text) # 去除引用符号 > text = re.sub(r'^>\s*', '', text, flags=re.MULTILINE) # 去除标题符号 # ## ### 等 text = re.sub(r'^#+\s*', '', text, flags=re.MULTILINE) # 去除水平分割线 --- 或 *** text = re.sub(r'^[\-\*]{3,}\s*$', '', text, flags=re.MULTILINE) # 去除 HTML 标签 <font color='xxx'>text</font> -> text text = re.sub(r'<font[^>]*>(.+?)</font>', r'\1', text) text = re.sub(r'<[^>]+>', '', text) # 清理多余的空行(保留最多两个连续空行) text = re.sub(r'\n{3,}', '\n\n', text) # 还原之前保护的 URL for idx, url in enumerate(protected_urls): text = text.replace(f"@@URLTOKEN{idx}@@", url) return text.strip() def convert_markdown_to_mrkdwn(content: str) -> str: # 1. 转换链接格式: [文本](url) → <url|文本> content = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<\2|\1>', content) # 2. 转换粗体: **文本** → *文本* content = re.sub(r'\*\*([^*]+)\*\*', r'*\1*', content) return content
--- +++ @@ -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.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'\1 \2', text) @@ -57,10 +70,24 @@ def convert_markdown_to_mrkdwn(content: str) -> str: + """ + 将标准 Markdown 转换为 Slack 的 mrkdwn 格式 + + 转换规则: + - **粗体** → *粗体* + - [文本](url) → <url|文本> + - 保留其他格式(代码块、列表等) + + Args: + content: Markdown 格式的内容 + + Returns: + Slack mrkdwn 格式的内容 + """ # 1. 转换链接格式: [文本](url) → <url|文本> content = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<\2|\1>', content) # 2. 转换粗体: **文本** → *文本* content = re.sub(r'\*\*([^*]+)\*\*', r'*\1*', content) - return content+ return content
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_to_dingtalk, send_to_email, send_to_feishu, send_to_ntfy, send_to_slack, send_to_telegram, send_to_wework, send_to_generic_webhook, ) from .renderer import ( render_rss_feishu_content, render_rss_dingtalk_content, render_rss_markdown_content, ) # 类型检查时导入,运行时不导入(避免循环导入) if TYPE_CHECKING: from trendradar.ai import AIAnalysisResult, AITranslator class NotificationDispatcher: def __init__( self, config: Dict[str, Any], get_time_func: Callable, split_content_func: Callable, translator: Optional["AITranslator"] = None, ): self.config = config self.get_time_func = get_time_func self.split_content_func = split_content_func self.max_accounts = config.get("MAX_ACCOUNTS_PER_CHANNEL", 3) self.translator = translator def _translate_content( self, report_data: Dict, rss_items: Optional[List[Dict]] = None, rss_new_items: Optional[List[Dict]] = None, standalone_data: Optional[Dict] = None, display_regions: Optional[Dict] = None, ) -> tuple: if not self.translator or not self.translator.enabled: return report_data, rss_items, rss_new_items, standalone_data import copy print(f"[翻译] 开始翻译内容到 {self.translator.target_language}...") scope = self.translator.scope display_regions = display_regions or {} # 深拷贝避免修改原始数据 report_data = copy.deepcopy(report_data) rss_items = copy.deepcopy(rss_items) if rss_items else None rss_new_items = copy.deepcopy(rss_new_items) if rss_new_items else None standalone_data = copy.deepcopy(standalone_data) if standalone_data else None # 收集所有需要翻译的标题 titles_to_translate = [] title_locations = [] # 记录标题位置,用于回填 # 1. 热榜标题(scope 开启 且 区域展示) if scope.get("HOTLIST", True) and display_regions.get("HOTLIST", True): for stat_idx, stat in enumerate(report_data.get("stats", [])): for title_idx, title_data in enumerate(stat.get("titles", [])): titles_to_translate.append(title_data.get("title", "")) title_locations.append(("stats", stat_idx, title_idx)) # 2. 新增热点标题 for source_idx, source in enumerate(report_data.get("new_titles", [])): for title_idx, title_data in enumerate(source.get("titles", [])): titles_to_translate.append(title_data.get("title", "")) title_locations.append(("new_titles", source_idx, title_idx)) # 3. RSS 统计标题(结构与 stats 一致:[{word, count, titles: [{title, ...}]}]) if rss_items and scope.get("RSS", True) and display_regions.get("RSS", True): for stat_idx, stat in enumerate(rss_items): for title_idx, title_data in enumerate(stat.get("titles", [])): titles_to_translate.append(title_data.get("title", "")) title_locations.append(("rss_items", stat_idx, title_idx)) # 4. RSS 新增标题(结构与 stats 一致) if rss_new_items and scope.get("RSS", True) and display_regions.get("RSS", True) and display_regions.get("NEW_ITEMS", True): for stat_idx, stat in enumerate(rss_new_items): for title_idx, title_data in enumerate(stat.get("titles", [])): titles_to_translate.append(title_data.get("title", "")) title_locations.append(("rss_new_items", stat_idx, title_idx)) # 5. 独立展示区 - 热榜平台 if standalone_data and scope.get("STANDALONE", True) and display_regions.get("STANDALONE", False): for plat_idx, platform in enumerate(standalone_data.get("platforms", [])): for item_idx, item in enumerate(platform.get("items", [])): titles_to_translate.append(item.get("title", "")) title_locations.append(("standalone_platforms", plat_idx, item_idx)) # 6. 独立展示区 - RSS 源 for feed_idx, feed in enumerate(standalone_data.get("rss_feeds", [])): for item_idx, item in enumerate(feed.get("items", [])): titles_to_translate.append(item.get("title", "")) title_locations.append(("standalone_rss", feed_idx, item_idx)) if not titles_to_translate: print("[翻译] 没有需要翻译的内容") return report_data, rss_items, rss_new_items, standalone_data print(f"[翻译] 共 {len(titles_to_translate)} 条标题待翻译") # 批量翻译 result = self.translator.translate_batch(titles_to_translate) if result.success_count == 0: print(f"[翻译] 翻译失败: {result.results[0].error if result.results else '未知错误'}") return report_data, rss_items, rss_new_items, standalone_data print(f"[翻译] 翻译完成: {result.success_count}/{result.total_count} 成功") # debug 模式:输出完整 prompt、AI 原始响应、逐条对照 if self.config.get("DEBUG", False): if result.prompt: print(f"[翻译][DEBUG] === 发送给 AI 的 Prompt ===") print(result.prompt) print(f"[翻译][DEBUG] === Prompt 结束 ===") if result.raw_response: print(f"[翻译][DEBUG] === AI 原始响应 ===") print(result.raw_response) print(f"[翻译][DEBUG] === 响应结束 ===") # 行数不匹配警告 expected = len(titles_to_translate) if result.parsed_count != expected: print(f"[翻译][DEBUG] ⚠️ 行数不匹配:期望 {expected} 条,AI 返回 {result.parsed_count} 条") # 逐条对照 unchanged_count = 0 for i, res in enumerate(result.results): if not res.success and res.error: print(f"[翻译][DEBUG] [{i+1}] !! 失败: {res.error}") elif res.original_text == res.translated_text: unchanged_count += 1 else: print(f"[翻译][DEBUG] [{i+1}] {res.original_text} => {res.translated_text}") if unchanged_count > 0: print(f"[翻译][DEBUG] (另有 {unchanged_count} 条未变化,已省略)") # 回填翻译结果 for i, (loc_type, idx1, idx2) in enumerate(title_locations): if i < len(result.results) and result.results[i].success: translated = result.results[i].translated_text if loc_type == "stats": report_data["stats"][idx1]["titles"][idx2]["title"] = translated elif loc_type == "new_titles": report_data["new_titles"][idx1]["titles"][idx2]["title"] = translated elif loc_type == "rss_items" and rss_items: rss_items[idx1]["titles"][idx2]["title"] = translated elif loc_type == "rss_new_items" and rss_new_items: rss_new_items[idx1]["titles"][idx2]["title"] = translated elif loc_type == "standalone_platforms" and standalone_data: standalone_data["platforms"][idx1]["items"][idx2]["title"] = translated elif loc_type == "standalone_rss" and standalone_data: standalone_data["rss_feeds"][idx1]["items"][idx2]["title"] = translated return report_data, rss_items, rss_new_items, standalone_data def dispatch_all( self, report_data: Dict, report_type: str, update_info: Optional[Dict] = None, proxy_url: Optional[str] = None, mode: str = "daily", html_file_path: Optional[str] = None, rss_items: Optional[List[Dict]] = None, rss_new_items: Optional[List[Dict]] = None, ai_analysis: Optional[AIAnalysisResult] = None, standalone_data: Optional[Dict] = None, ) -> Dict[str, bool]: results = {} # 获取区域显示配置 display_regions = self.config.get("DISPLAY", {}).get("REGIONS", {}) # 执行翻译(如果启用,根据 display_regions 跳过不展示的区域) report_data, rss_items, rss_new_items, standalone_data = self._translate_content( report_data, rss_items, rss_new_items, standalone_data, display_regions ) # 飞书 if self.config.get("FEISHU_WEBHOOK_URL"): results["feishu"] = self._send_feishu( report_data, report_type, update_info, proxy_url, mode, rss_items, rss_new_items, ai_analysis, display_regions, standalone_data ) # 钉钉 if self.config.get("DINGTALK_WEBHOOK_URL"): results["dingtalk"] = self._send_dingtalk( report_data, report_type, update_info, proxy_url, mode, rss_items, rss_new_items, ai_analysis, display_regions, standalone_data ) # 企业微信 if self.config.get("WEWORK_WEBHOOK_URL"): results["wework"] = self._send_wework( report_data, report_type, update_info, proxy_url, mode, rss_items, rss_new_items, ai_analysis, display_regions, standalone_data ) # Telegram(需要配对验证) if self.config.get("TELEGRAM_BOT_TOKEN") and self.config.get("TELEGRAM_CHAT_ID"): results["telegram"] = self._send_telegram( report_data, report_type, update_info, proxy_url, mode, rss_items, rss_new_items, ai_analysis, display_regions, standalone_data ) # ntfy(需要配对验证) if self.config.get("NTFY_SERVER_URL") and self.config.get("NTFY_TOPIC"): results["ntfy"] = self._send_ntfy( report_data, report_type, update_info, proxy_url, mode, rss_items, rss_new_items, ai_analysis, display_regions, standalone_data ) # Bark if self.config.get("BARK_URL"): results["bark"] = self._send_bark( report_data, report_type, update_info, proxy_url, mode, rss_items, rss_new_items, ai_analysis, display_regions, standalone_data ) # Slack if self.config.get("SLACK_WEBHOOK_URL"): results["slack"] = self._send_slack( report_data, report_type, update_info, proxy_url, mode, rss_items, rss_new_items, ai_analysis, display_regions, standalone_data ) # 通用 Webhook if self.config.get("GENERIC_WEBHOOK_URL"): results["generic_webhook"] = self._send_generic_webhook( report_data, report_type, update_info, proxy_url, mode, rss_items, rss_new_items, ai_analysis, display_regions, standalone_data ) # 邮件(保持原有逻辑,已支持多收件人,AI 分析已嵌入 HTML) if ( self.config.get("EMAIL_FROM") and self.config.get("EMAIL_PASSWORD") and self.config.get("EMAIL_TO") ): results["email"] = self._send_email(report_type, html_file_path) return results def _send_to_multi_accounts( self, channel_name: str, config_value: str, send_func: Callable[..., bool], **kwargs, ) -> bool: accounts = parse_multi_account_config(config_value) if not accounts: return False accounts = limit_accounts(accounts, self.max_accounts, channel_name) results = [] for i, account in enumerate(accounts): if account: account_label = f"账号{i+1}" if len(accounts) > 1 else "" result = send_func(account, account_label=account_label, **kwargs) results.append(result) return any(results) if results else False def _send_feishu( self, report_data: Dict, report_type: str, update_info: Optional[Dict], proxy_url: Optional[str], mode: str, rss_items: Optional[List[Dict]] = None, rss_new_items: Optional[List[Dict]] = None, ai_analysis: Optional[AIAnalysisResult] = None, display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: display_regions = display_regions or {} if not display_regions.get("HOTLIST", True): report_data = {"stats": [], "failed_ids": [], "new_titles": [], "id_to_name": {}} return self._send_to_multi_accounts( channel_name="飞书", config_value=self.config["FEISHU_WEBHOOK_URL"], send_func=lambda url, account_label: send_to_feishu( webhook_url=url, report_data=report_data, report_type=report_type, update_info=update_info, proxy_url=proxy_url, mode=mode, account_label=account_label, batch_size=self.config.get("FEISHU_BATCH_SIZE", 29000), batch_interval=self.config.get("BATCH_SEND_INTERVAL", 1.0), split_content_func=self.split_content_func, get_time_func=self.get_time_func, rss_items=rss_items if display_regions.get("RSS", True) else None, rss_new_items=rss_new_items if (display_regions.get("RSS", True) and display_regions.get("NEW_ITEMS", True)) else None, ai_analysis=ai_analysis if display_regions.get("AI_ANALYSIS", True) else None, display_regions=display_regions, standalone_data=standalone_data if display_regions.get("STANDALONE", False) else None, ), ) def _send_dingtalk( self, report_data: Dict, report_type: str, update_info: Optional[Dict], proxy_url: Optional[str], mode: str, rss_items: Optional[List[Dict]] = None, rss_new_items: Optional[List[Dict]] = None, ai_analysis: Optional[AIAnalysisResult] = None, display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: display_regions = display_regions or {} if not display_regions.get("HOTLIST", True): report_data = {"stats": [], "failed_ids": [], "new_titles": [], "id_to_name": {}} return self._send_to_multi_accounts( channel_name="钉钉", config_value=self.config["DINGTALK_WEBHOOK_URL"], send_func=lambda url, account_label: send_to_dingtalk( webhook_url=url, report_data=report_data, report_type=report_type, update_info=update_info, proxy_url=proxy_url, mode=mode, account_label=account_label, batch_size=self.config.get("DINGTALK_BATCH_SIZE", 20000), batch_interval=self.config.get("BATCH_SEND_INTERVAL", 1.0), split_content_func=self.split_content_func, rss_items=rss_items if display_regions.get("RSS", True) else None, rss_new_items=rss_new_items if (display_regions.get("RSS", True) and display_regions.get("NEW_ITEMS", True)) else None, ai_analysis=ai_analysis if display_regions.get("AI_ANALYSIS", True) else None, display_regions=display_regions, standalone_data=standalone_data if display_regions.get("STANDALONE", False) else None, ), ) def _send_wework( self, report_data: Dict, report_type: str, update_info: Optional[Dict], proxy_url: Optional[str], mode: str, rss_items: Optional[List[Dict]] = None, rss_new_items: Optional[List[Dict]] = None, ai_analysis: Optional[AIAnalysisResult] = None, display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: display_regions = display_regions or {} if not display_regions.get("HOTLIST", True): report_data = {"stats": [], "failed_ids": [], "new_titles": [], "id_to_name": {}} return self._send_to_multi_accounts( channel_name="企业微信", config_value=self.config["WEWORK_WEBHOOK_URL"], send_func=lambda url, account_label: send_to_wework( webhook_url=url, report_data=report_data, report_type=report_type, update_info=update_info, proxy_url=proxy_url, mode=mode, account_label=account_label, batch_size=self.config.get("MESSAGE_BATCH_SIZE", 4000), batch_interval=self.config.get("BATCH_SEND_INTERVAL", 1.0), msg_type=self.config.get("WEWORK_MSG_TYPE", "markdown"), split_content_func=self.split_content_func, rss_items=rss_items if display_regions.get("RSS", True) else None, rss_new_items=rss_new_items if (display_regions.get("RSS", True) and display_regions.get("NEW_ITEMS", True)) else None, ai_analysis=ai_analysis if display_regions.get("AI_ANALYSIS", True) else None, display_regions=display_regions, standalone_data=standalone_data if display_regions.get("STANDALONE", False) else None, ), ) def _send_telegram( self, report_data: Dict, report_type: str, update_info: Optional[Dict], proxy_url: Optional[str], mode: str, rss_items: Optional[List[Dict]] = None, rss_new_items: Optional[List[Dict]] = None, ai_analysis: Optional[AIAnalysisResult] = None, display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: display_regions = display_regions or {} if not display_regions.get("HOTLIST", True): report_data = {"stats": [], "failed_ids": [], "new_titles": [], "id_to_name": {}} telegram_tokens = parse_multi_account_config(self.config["TELEGRAM_BOT_TOKEN"]) telegram_chat_ids = parse_multi_account_config(self.config["TELEGRAM_CHAT_ID"]) if not telegram_tokens or not telegram_chat_ids: return False valid, count = validate_paired_configs( {"bot_token": telegram_tokens, "chat_id": telegram_chat_ids}, "Telegram", required_keys=["bot_token", "chat_id"], ) if not valid or count == 0: return False telegram_tokens = limit_accounts(telegram_tokens, self.max_accounts, "Telegram") telegram_chat_ids = telegram_chat_ids[: len(telegram_tokens)] results = [] for i in range(len(telegram_tokens)): token = telegram_tokens[i] chat_id = telegram_chat_ids[i] if token and chat_id: account_label = f"账号{i+1}" if len(telegram_tokens) > 1 else "" result = send_to_telegram( bot_token=token, chat_id=chat_id, report_data=report_data, report_type=report_type, update_info=update_info, proxy_url=proxy_url, mode=mode, account_label=account_label, batch_size=self.config.get("MESSAGE_BATCH_SIZE", 4000), batch_interval=self.config.get("BATCH_SEND_INTERVAL", 1.0), split_content_func=self.split_content_func, rss_items=rss_items if display_regions.get("RSS", True) else None, rss_new_items=rss_new_items if (display_regions.get("RSS", True) and display_regions.get("NEW_ITEMS", True)) else None, ai_analysis=ai_analysis if display_regions.get("AI_ANALYSIS", True) else None, display_regions=display_regions, standalone_data=standalone_data if display_regions.get("STANDALONE", False) else None, ) results.append(result) return any(results) if results else False def _send_ntfy( self, report_data: Dict, report_type: str, update_info: Optional[Dict], proxy_url: Optional[str], mode: str, rss_items: Optional[List[Dict]] = None, rss_new_items: Optional[List[Dict]] = None, ai_analysis: Optional[AIAnalysisResult] = None, display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: display_regions = display_regions or {} if not display_regions.get("HOTLIST", True): report_data = {"stats": [], "failed_ids": [], "new_titles": [], "id_to_name": {}} ntfy_server_url = self.config["NTFY_SERVER_URL"] ntfy_topics = parse_multi_account_config(self.config["NTFY_TOPIC"]) ntfy_tokens = parse_multi_account_config(self.config.get("NTFY_TOKEN", "")) if not ntfy_server_url or not ntfy_topics: return False if ntfy_tokens and len(ntfy_tokens) != len(ntfy_topics): print( f"❌ ntfy 配置错误:topic 数量({len(ntfy_topics)})与 token 数量({len(ntfy_tokens)})不一致,跳过 ntfy 推送" ) return False ntfy_topics = limit_accounts(ntfy_topics, self.max_accounts, "ntfy") if ntfy_tokens: ntfy_tokens = ntfy_tokens[: len(ntfy_topics)] results = [] for i, topic in enumerate(ntfy_topics): if topic: token = get_account_at_index(ntfy_tokens, i, "") if ntfy_tokens else "" account_label = f"账号{i+1}" if len(ntfy_topics) > 1 else "" result = send_to_ntfy( server_url=ntfy_server_url, topic=topic, token=token, report_data=report_data, report_type=report_type, update_info=update_info, proxy_url=proxy_url, mode=mode, account_label=account_label, batch_size=3800, split_content_func=self.split_content_func, rss_items=rss_items if display_regions.get("RSS", True) else None, rss_new_items=rss_new_items if (display_regions.get("RSS", True) and display_regions.get("NEW_ITEMS", True)) else None, ai_analysis=ai_analysis if display_regions.get("AI_ANALYSIS", True) else None, display_regions=display_regions, standalone_data=standalone_data if display_regions.get("STANDALONE", False) else None, ) results.append(result) return any(results) if results else False def _send_bark( self, report_data: Dict, report_type: str, update_info: Optional[Dict], proxy_url: Optional[str], mode: str, rss_items: Optional[List[Dict]] = None, rss_new_items: Optional[List[Dict]] = None, ai_analysis: Optional[AIAnalysisResult] = None, display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: display_regions = display_regions or {} if not display_regions.get("HOTLIST", True): report_data = {"stats": [], "failed_ids": [], "new_titles": [], "id_to_name": {}} return self._send_to_multi_accounts( channel_name="Bark", config_value=self.config["BARK_URL"], send_func=lambda url, account_label: send_to_bark( bark_url=url, report_data=report_data, report_type=report_type, update_info=update_info, proxy_url=proxy_url, mode=mode, account_label=account_label, batch_size=self.config.get("BARK_BATCH_SIZE", 3600), batch_interval=self.config.get("BATCH_SEND_INTERVAL", 1.0), split_content_func=self.split_content_func, rss_items=rss_items if display_regions.get("RSS", True) else None, rss_new_items=rss_new_items if (display_regions.get("RSS", True) and display_regions.get("NEW_ITEMS", True)) else None, ai_analysis=ai_analysis if display_regions.get("AI_ANALYSIS", True) else None, display_regions=display_regions, standalone_data=standalone_data if display_regions.get("STANDALONE", False) else None, ), ) def _send_slack( self, report_data: Dict, report_type: str, update_info: Optional[Dict], proxy_url: Optional[str], mode: str, rss_items: Optional[List[Dict]] = None, rss_new_items: Optional[List[Dict]] = None, ai_analysis: Optional[AIAnalysisResult] = None, display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: display_regions = display_regions or {} if not display_regions.get("HOTLIST", True): report_data = {"stats": [], "failed_ids": [], "new_titles": [], "id_to_name": {}} return self._send_to_multi_accounts( channel_name="Slack", config_value=self.config["SLACK_WEBHOOK_URL"], send_func=lambda url, account_label: send_to_slack( webhook_url=url, report_data=report_data, report_type=report_type, update_info=update_info, proxy_url=proxy_url, mode=mode, account_label=account_label, batch_size=self.config.get("SLACK_BATCH_SIZE", 4000), batch_interval=self.config.get("BATCH_SEND_INTERVAL", 1.0), split_content_func=self.split_content_func, rss_items=rss_items if display_regions.get("RSS", True) else None, rss_new_items=rss_new_items if (display_regions.get("RSS", True) and display_regions.get("NEW_ITEMS", True)) else None, ai_analysis=ai_analysis if display_regions.get("AI_ANALYSIS", True) else None, display_regions=display_regions, standalone_data=standalone_data if display_regions.get("STANDALONE", False) else None, ), ) def _send_generic_webhook( self, report_data: Dict, report_type: str, update_info: Optional[Dict], proxy_url: Optional[str], mode: str, rss_items: Optional[List[Dict]] = None, rss_new_items: Optional[List[Dict]] = None, ai_analysis: Optional[AIAnalysisResult] = None, display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: display_regions = display_regions or {} if not display_regions.get("HOTLIST", True): report_data = {"stats": [], "failed_ids": [], "new_titles": [], "id_to_name": {}} urls = parse_multi_account_config(self.config.get("GENERIC_WEBHOOK_URL", "")) templates = parse_multi_account_config(self.config.get("GENERIC_WEBHOOK_TEMPLATE", "")) if not urls: return False urls = limit_accounts(urls, self.max_accounts, "通用Webhook") results = [] for i, url in enumerate(urls): if not url: continue template = "" if templates: if i < len(templates): template = templates[i] elif len(templates) == 1: template = templates[0] account_label = f"账号{i+1}" if len(urls) > 1 else "" result = send_to_generic_webhook( webhook_url=url, payload_template=template, report_data=report_data, report_type=report_type, update_info=update_info, proxy_url=proxy_url, mode=mode, account_label=account_label, batch_size=self.config.get("MESSAGE_BATCH_SIZE", 4000), batch_interval=self.config.get("BATCH_SEND_INTERVAL", 1.0), split_content_func=self.split_content_func, rss_items=rss_items if display_regions.get("RSS", True) else None, rss_new_items=rss_new_items if (display_regions.get("RSS", True) and display_regions.get("NEW_ITEMS", True)) else None, ai_analysis=ai_analysis if display_regions.get("AI_ANALYSIS", True) else None, display_regions=display_regions, standalone_data=standalone_data if display_regions.get("STANDALONE", False) else None, ) results.append(result) return any(results) if results else False def _send_email( self, report_type: str, html_file_path: Optional[str], ) -> bool: return send_to_email( from_email=self.config["EMAIL_FROM"], password=self.config["EMAIL_PASSWORD"], to_email=self.config["EMAIL_TO"], report_type=report_type, html_file_path=html_file_path, custom_smtp_server=self.config.get("EMAIL_SMTP_SERVER", ""), custom_smtp_port=self.config.get("EMAIL_SMTP_PORT", ""), get_time_func=self.get_time_func, ) # === RSS 通知方法 === def dispatch_rss( self, rss_items: List[Dict], feeds_info: Optional[Dict[str, str]] = None, proxy_url: Optional[str] = None, html_file_path: Optional[str] = None, ) -> Dict[str, bool]: if not rss_items: print("[RSS通知] 没有 RSS 内容,跳过通知") return {} results = {} report_type = "RSS 订阅更新" # 飞书 if self.config.get("FEISHU_WEBHOOK_URL"): results["feishu"] = self._send_rss_feishu( rss_items, feeds_info, proxy_url ) # 钉钉 if self.config.get("DINGTALK_WEBHOOK_URL"): results["dingtalk"] = self._send_rss_dingtalk( rss_items, feeds_info, proxy_url ) # 企业微信 if self.config.get("WEWORK_WEBHOOK_URL"): results["wework"] = self._send_rss_markdown( rss_items, feeds_info, proxy_url, "wework" ) # Telegram if self.config.get("TELEGRAM_BOT_TOKEN") and self.config.get("TELEGRAM_CHAT_ID"): results["telegram"] = self._send_rss_markdown( rss_items, feeds_info, proxy_url, "telegram" ) # ntfy if self.config.get("NTFY_SERVER_URL") and self.config.get("NTFY_TOPIC"): results["ntfy"] = self._send_rss_markdown( rss_items, feeds_info, proxy_url, "ntfy" ) # Bark if self.config.get("BARK_URL"): results["bark"] = self._send_rss_markdown( rss_items, feeds_info, proxy_url, "bark" ) # Slack if self.config.get("SLACK_WEBHOOK_URL"): results["slack"] = self._send_rss_markdown( rss_items, feeds_info, proxy_url, "slack" ) # 邮件 if ( self.config.get("EMAIL_FROM") and self.config.get("EMAIL_PASSWORD") and self.config.get("EMAIL_TO") ): results["email"] = self._send_email(report_type, html_file_path) return results def _send_rss_feishu( self, rss_items: List[Dict], feeds_info: Optional[Dict[str, str]], proxy_url: Optional[str], ) -> bool: import requests content = render_rss_feishu_content( rss_items=rss_items, feeds_info=feeds_info, get_time_func=self.get_time_func, ) webhooks = parse_multi_account_config(self.config["FEISHU_WEBHOOK_URL"]) webhooks = limit_accounts(webhooks, self.max_accounts, "飞书") results = [] for i, webhook_url in enumerate(webhooks): if not webhook_url: continue account_label = f"账号{i+1}" if len(webhooks) > 1 else "" try: # 分批发送 batches = self.split_content_func( content, self.config.get("FEISHU_BATCH_SIZE", 29000) ) for batch_idx, batch_content in enumerate(batches): payload = { "msg_type": "interactive", "card": { "header": { "title": { "tag": "plain_text", "content": f"📰 RSS 订阅更新 {f'({batch_idx + 1}/{len(batches)})' if len(batches) > 1 else ''}", }, "template": "green", }, "elements": [ {"tag": "markdown", "content": batch_content} ], }, } proxies = {"http": proxy_url, "https": proxy_url} if proxy_url else None resp = requests.post(webhook_url, json=payload, proxies=proxies, timeout=30) resp.raise_for_status() print(f"✅ 飞书{account_label} RSS 通知发送成功") results.append(True) except Exception as e: print(f"❌ 飞书{account_label} RSS 通知发送失败: {e}") results.append(False) return any(results) if results else False def _send_rss_dingtalk( self, rss_items: List[Dict], feeds_info: Optional[Dict[str, str]], proxy_url: Optional[str], ) -> bool: import requests content = render_rss_dingtalk_content( rss_items=rss_items, feeds_info=feeds_info, get_time_func=self.get_time_func, ) webhooks = parse_multi_account_config(self.config["DINGTALK_WEBHOOK_URL"]) webhooks = limit_accounts(webhooks, self.max_accounts, "钉钉") results = [] for i, webhook_url in enumerate(webhooks): if not webhook_url: continue account_label = f"账号{i+1}" if len(webhooks) > 1 else "" try: batches = self.split_content_func( content, self.config.get("DINGTALK_BATCH_SIZE", 20000) ) for batch_idx, batch_content in enumerate(batches): title = f"📰 RSS 订阅更新 {f'({batch_idx + 1}/{len(batches)})' if len(batches) > 1 else ''}" payload = { "msgtype": "markdown", "markdown": { "title": title, "text": batch_content, }, } proxies = {"http": proxy_url, "https": proxy_url} if proxy_url else None resp = requests.post(webhook_url, json=payload, proxies=proxies, timeout=30) resp.raise_for_status() print(f"✅ 钉钉{account_label} RSS 通知发送成功") results.append(True) except Exception as e: print(f"❌ 钉钉{account_label} RSS 通知发送失败: {e}") results.append(False) return any(results) if results else False def _send_rss_markdown( self, rss_items: List[Dict], feeds_info: Optional[Dict[str, str]], proxy_url: Optional[str], channel: str, ) -> bool: content = render_rss_markdown_content( rss_items=rss_items, feeds_info=feeds_info, get_time_func=self.get_time_func, ) try: if channel == "wework": return self._send_rss_wework(content, proxy_url) elif channel == "telegram": return self._send_rss_telegram(content, proxy_url) elif channel == "ntfy": return self._send_rss_ntfy(content, proxy_url) elif channel == "bark": return self._send_rss_bark(content, proxy_url) elif channel == "slack": return self._send_rss_slack(content, proxy_url) except Exception as e: print(f"❌ {channel} RSS 通知发送失败: {e}") return False return False def _send_rss_wework(self, content: str, proxy_url: Optional[str]) -> bool: import requests webhooks = parse_multi_account_config(self.config["WEWORK_WEBHOOK_URL"]) webhooks = limit_accounts(webhooks, self.max_accounts, "企业微信") results = [] for i, webhook_url in enumerate(webhooks): if not webhook_url: continue account_label = f"账号{i+1}" if len(webhooks) > 1 else "" try: batches = self.split_content_func( content, self.config.get("MESSAGE_BATCH_SIZE", 4000) ) for batch_content in batches: payload = { "msgtype": "markdown", "markdown": {"content": batch_content}, } proxies = {"http": proxy_url, "https": proxy_url} if proxy_url else None resp = requests.post(webhook_url, json=payload, proxies=proxies, timeout=30) resp.raise_for_status() print(f"✅ 企业微信{account_label} RSS 通知发送成功") results.append(True) except Exception as e: print(f"❌ 企业微信{account_label} RSS 通知发送失败: {e}") results.append(False) return any(results) if results else False def _send_rss_telegram(self, content: str, proxy_url: Optional[str]) -> bool: import requests tokens = parse_multi_account_config(self.config["TELEGRAM_BOT_TOKEN"]) chat_ids = parse_multi_account_config(self.config["TELEGRAM_CHAT_ID"]) if not tokens or not chat_ids: return False results = [] for i in range(min(len(tokens), len(chat_ids), self.max_accounts)): token = tokens[i] chat_id = chat_ids[i] if not token or not chat_id: continue account_label = f"账号{i+1}" if len(tokens) > 1 else "" try: batches = self.split_content_func( content, self.config.get("MESSAGE_BATCH_SIZE", 4000) ) for batch_content in batches: url = f"https://api.telegram.org/bot{token}/sendMessage" payload = { "chat_id": chat_id, "text": batch_content, "parse_mode": "Markdown", } proxies = {"http": proxy_url, "https": proxy_url} if proxy_url else None resp = requests.post(url, json=payload, proxies=proxies, timeout=30) resp.raise_for_status() print(f"✅ Telegram{account_label} RSS 通知发送成功") results.append(True) except Exception as e: print(f"❌ Telegram{account_label} RSS 通知发送失败: {e}") results.append(False) return any(results) if results else False def _send_rss_ntfy(self, content: str, proxy_url: Optional[str]) -> bool: import requests server_url = self.config["NTFY_SERVER_URL"] topics = parse_multi_account_config(self.config["NTFY_TOPIC"]) tokens = parse_multi_account_config(self.config.get("NTFY_TOKEN", "")) if not server_url or not topics: return False topics = limit_accounts(topics, self.max_accounts, "ntfy") results = [] for i, topic in enumerate(topics): if not topic: continue token = tokens[i] if tokens and i < len(tokens) else "" account_label = f"账号{i+1}" if len(topics) > 1 else "" try: batches = self.split_content_func(content, 3800) for batch_content in batches: url = f"{server_url.rstrip('/')}/{topic}" headers = {"Title": "RSS 订阅更新", "Markdown": "yes"} if token: headers["Authorization"] = f"Bearer {token}" proxies = {"http": proxy_url, "https": proxy_url} if proxy_url else None resp = requests.post( url, data=batch_content.encode("utf-8"), headers=headers, proxies=proxies, timeout=30 ) resp.raise_for_status() print(f"✅ ntfy{account_label} RSS 通知发送成功") results.append(True) except Exception as e: print(f"❌ ntfy{account_label} RSS 通知发送失败: {e}") results.append(False) return any(results) if results else False def _send_rss_bark(self, content: str, proxy_url: Optional[str]) -> bool: import requests import urllib.parse urls = parse_multi_account_config(self.config["BARK_URL"]) urls = limit_accounts(urls, self.max_accounts, "Bark") results = [] for i, bark_url in enumerate(urls): if not bark_url: continue account_label = f"账号{i+1}" if len(urls) > 1 else "" try: batches = self.split_content_func( content, self.config.get("BARK_BATCH_SIZE", 3600) ) for batch_content in batches: title = urllib.parse.quote("📰 RSS 订阅更新") body = urllib.parse.quote(batch_content) url = f"{bark_url.rstrip('/')}/{title}/{body}" proxies = {"http": proxy_url, "https": proxy_url} if proxy_url else None resp = requests.get(url, proxies=proxies, timeout=30) resp.raise_for_status() print(f"✅ Bark{account_label} RSS 通知发送成功") results.append(True) except Exception as e: print(f"❌ Bark{account_label} RSS 通知发送失败: {e}") results.append(False) return any(results) if results else False def _send_rss_slack(self, content: str, proxy_url: Optional[str]) -> bool: import requests webhooks = parse_multi_account_config(self.config["SLACK_WEBHOOK_URL"]) webhooks = limit_accounts(webhooks, self.max_accounts, "Slack") results = [] for i, webhook_url in enumerate(webhooks): if not webhook_url: continue account_label = f"账号{i+1}" if len(webhooks) > 1 else "" try: batches = self.split_content_func( content, self.config.get("SLACK_BATCH_SIZE", 4000) ) for batch_content in batches: payload = { "blocks": [ { "type": "section", "text": { "type": "mrkdwn", "text": batch_content, }, } ] } proxies = {"http": proxy_url, "https": proxy_url} if proxy_url else None resp = requests.post(webhook_url, json=payload, proxies=proxies, timeout=30) resp.raise_for_status() print(f"✅ Slack{account_label} RSS 通知发送成功") results.append(True) except Exception as e: print(f"❌ Slack{account_label} RSS 通知发送失败: {e}") results.append(False) return any(results) if results else False
--- +++ @@ -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 +44,12 @@ class NotificationDispatcher: + """ + 统一的多账号通知调度器 + + 将多账号发送逻辑封装,提供简洁的 dispatch_all 接口。 + 内部处理账号解析、数量限制、配对验证等逻辑。 + """ def __init__( self, @@ -42,6 +58,15 @@ split_content_func: Callable, translator: Optional["AITranslator"] = None, ): + """ + 初始化通知调度器 + + Args: + config: 完整的配置字典,包含所有通知渠道的配置 + get_time_func: 获取当前时间的函数 + split_content_func: 内容分批函数 + translator: AI 翻译器实例(可选) + """ self.config = config self.get_time_func = get_time_func self.split_content_func = split_content_func @@ -56,6 +81,19 @@ standalone_data: Optional[Dict] = None, display_regions: Optional[Dict] = None, ) -> tuple: + """ + 翻译推送内容 + + Args: + report_data: 报告数据 + rss_items: RSS 统计条目 + rss_new_items: RSS 新增条目 + standalone_data: 独立展示区数据 + display_regions: 区域显示配置(不展示的区域跳过翻译) + + Returns: + tuple: (翻译后的 report_data, rss_items, rss_new_items, standalone_data) + """ if not self.translator or not self.translator.enabled: return report_data, rss_items, rss_new_items, standalone_data @@ -188,6 +226,24 @@ ai_analysis: Optional[AIAnalysisResult] = None, standalone_data: Optional[Dict] = None, ) -> Dict[str, bool]: + """ + 分发通知到所有已配置的渠道(支持热榜+RSS合并推送+AI分析+独立展示区) + + Args: + report_data: 报告数据(由 prepare_report_data 生成) + report_type: 报告类型(如 "全天汇总"、"当前榜单"、"增量分析") + update_info: 版本更新信息(可选) + proxy_url: 代理 URL(可选) + mode: 报告模式 (daily/current/incremental) + html_file_path: HTML 报告文件路径(邮件使用) + rss_items: RSS 统计条目列表(用于 RSS 统计区块) + rss_new_items: RSS 新增条目列表(用于 RSS 新增区块) + ai_analysis: AI 分析结果(可选) + standalone_data: 独立展示区数据(可选) + + Returns: + Dict[str, bool]: 每个渠道的发送结果,key 为渠道名,value 为是否成功 + """ results = {} # 获取区域显示配置 @@ -271,6 +327,18 @@ send_func: Callable[..., bool], **kwargs, ) -> bool: + """ + 通用多账号发送逻辑 + + Args: + channel_name: 渠道名称(用于日志和账号数量限制提示) + config_value: 配置值(可能包含多个账号,用 ; 分隔) + send_func: 发送函数,签名为 (account, account_label=..., **kwargs) -> bool + **kwargs: 传递给发送函数的其他参数 + + Returns: + bool: 任一账号发送成功则返回 True + """ accounts = parse_multi_account_config(config_value) if not accounts: return False @@ -299,6 +367,7 @@ display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: + """发送到飞书(多账号,支持热榜+RSS合并+AI分析+独立展示区)""" display_regions = display_regions or {} if not display_regions.get("HOTLIST", True): report_data = {"stats": [], "failed_ids": [], "new_titles": [], "id_to_name": {}} @@ -339,6 +408,7 @@ display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: + """发送到钉钉(多账号,支持热榜+RSS合并+AI分析+独立展示区)""" display_regions = display_regions or {} if not display_regions.get("HOTLIST", True): report_data = {"stats": [], "failed_ids": [], "new_titles": [], "id_to_name": {}} @@ -378,6 +448,7 @@ display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: + """发送到企业微信(多账号,支持热榜+RSS合并+AI分析+独立展示区)""" display_regions = display_regions or {} if not display_regions.get("HOTLIST", True): report_data = {"stats": [], "failed_ids": [], "new_titles": [], "id_to_name": {}} @@ -418,6 +489,7 @@ display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: + """发送到 Telegram(多账号,需验证 token 和 chat_id 配对,支持热榜+RSS合并+AI分析+独立展示区)""" display_regions = display_regions or {} if not display_regions.get("HOTLIST", True): report_data = {"stats": [], "failed_ids": [], "new_titles": [], "id_to_name": {}} @@ -480,6 +552,7 @@ display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: + """发送到 ntfy(多账号,需验证 topic 和 token 配对,支持热榜+RSS合并+AI分析+独立展示区)""" display_regions = display_regions or {} if not display_regions.get("HOTLIST", True): report_data = {"stats": [], "failed_ids": [], "new_titles": [], "id_to_name": {}} @@ -541,6 +614,7 @@ display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: + """发送到 Bark(多账号,支持热榜+RSS合并+AI分析+独立展示区)""" display_regions = display_regions or {} if not display_regions.get("HOTLIST", True): report_data = {"stats": [], "failed_ids": [], "new_titles": [], "id_to_name": {}} @@ -580,6 +654,7 @@ display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: + """发送到 Slack(多账号,支持热榜+RSS合并+AI分析+独立展示区)""" display_regions = display_regions or {} if not display_regions.get("HOTLIST", True): report_data = {"stats": [], "failed_ids": [], "new_titles": [], "id_to_name": {}} @@ -619,6 +694,7 @@ display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: + """发送到通用 Webhook(多账号,支持热榜+RSS合并+AI分析+独立展示区)""" display_regions = display_regions or {} if not display_regions.get("HOTLIST", True): report_data = {"stats": [], "failed_ids": [], "new_titles": [], "id_to_name": {}} @@ -672,6 +748,11 @@ report_type: str, html_file_path: Optional[str], ) -> bool: + """发送邮件(保持原有逻辑,已支持多收件人) + + Note: + AI 分析内容已在 HTML 生成时嵌入,无需在此传递 + """ return send_to_email( from_email=self.config["EMAIL_FROM"], password=self.config["EMAIL_PASSWORD"], @@ -692,6 +773,25 @@ proxy_url: Optional[str] = None, html_file_path: Optional[str] = None, ) -> Dict[str, bool]: + """ + 分发 RSS 通知到所有已配置的渠道 + + Args: + rss_items: RSS 条目列表,每个条目包含: + - title: 标题 + - feed_id: RSS 源 ID + - feed_name: RSS 源名称 + - url: 链接 + - published_at: 发布时间 + - summary: 摘要(可选) + - author: 作者(可选) + feeds_info: RSS 源 ID 到名称的映射 + proxy_url: 代理 URL(可选) + html_file_path: HTML 报告文件路径(邮件使用) + + Returns: + Dict[str, bool]: 每个渠道的发送结果 + """ if not rss_items: print("[RSS通知] 没有 RSS 内容,跳过通知") return {} @@ -757,6 +857,7 @@ feeds_info: Optional[Dict[str, str]], proxy_url: Optional[str], ) -> bool: + """发送 RSS 到飞书""" import requests content = render_rss_feishu_content( @@ -815,6 +916,7 @@ feeds_info: Optional[Dict[str, str]], proxy_url: Optional[str], ) -> bool: + """发送 RSS 到钉钉""" import requests content = render_rss_dingtalk_content( @@ -866,6 +968,7 @@ proxy_url: Optional[str], channel: str, ) -> bool: + """发送 RSS 到 Markdown 兼容渠道(企业微信、Telegram、ntfy、Bark、Slack)""" content = render_rss_markdown_content( rss_items=rss_items, @@ -891,6 +994,7 @@ return False def _send_rss_wework(self, content: str, proxy_url: Optional[str]) -> bool: + """发送 RSS 到企业微信""" import requests webhooks = parse_multi_account_config(self.config["WEWORK_WEBHOOK_URL"]) @@ -926,6 +1030,7 @@ return any(results) if results else False def _send_rss_telegram(self, content: str, proxy_url: Optional[str]) -> bool: + """发送 RSS 到 Telegram""" import requests tokens = parse_multi_account_config(self.config["TELEGRAM_BOT_TOKEN"]) @@ -969,6 +1074,7 @@ return any(results) if results else False def _send_rss_ntfy(self, content: str, proxy_url: Optional[str]) -> bool: + """发送 RSS 到 ntfy""" import requests server_url = self.config["NTFY_SERVER_URL"] @@ -1013,6 +1119,7 @@ return any(results) if results else False def _send_rss_bark(self, content: str, proxy_url: Optional[str]) -> bool: + """发送 RSS 到 Bark""" import requests import urllib.parse @@ -1048,6 +1155,7 @@ return any(results) if results else False def _send_rss_slack(self, content: str, proxy_url: Optional[str]) -> bool: + """发送 RSS 到 Slack""" import requests webhooks = parse_multi_account_config(self.config["SLACK_WEBHOOK_URL"]) @@ -1087,4 +1195,4 @@ print(f"❌ Slack{account_label} RSS 通知发送失败: {e}") results.append(False) - return any(results) if results else False+ return any(results) if results else False
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, w): def get_location(val, length): if val < 0: return 0 elif val > length: return length else: return val face_areas = [] for det_face in det_faces: left = get_location(det_face[0], w) right = get_location(det_face[2], w) top = get_location(det_face[1], h) bottom = get_location(det_face[3], h) face_area = (right - left) * (bottom - top) face_areas.append(face_area) largest_idx = face_areas.index(max(face_areas)) return det_faces[largest_idx], largest_idx def get_center_face(det_faces, h=0, w=0, center=None): if center is not None: center = np.array(center) else: center = np.array([w / 2, h / 2]) center_dist = [] for det_face in det_faces: face_center = np.array([(det_face[0] + det_face[2]) / 2, (det_face[1] + det_face[3]) / 2]) dist = np.linalg.norm(face_center - center) center_dist.append(dist) center_idx = center_dist.index(min(center_dist)) return det_faces[center_idx], center_idx class FaceRestoreHelper(object): def __init__(self, upscale_factor, face_size=512, crop_ratio=(1, 1), det_model='retinaface_resnet50', save_ext='png', template_3points=False, pad_blur=False, use_parse=False, device=None, model_rootpath=None): self.template_3points = template_3points # improve robustness self.upscale_factor = upscale_factor # the cropped face ratio based on the square face self.crop_ratio = crop_ratio # (h, w) assert (self.crop_ratio[0] >= 1 and self.crop_ratio[1] >= 1), 'crop ration only supports >=1' self.face_size = (int(face_size * self.crop_ratio[1]), int(face_size * self.crop_ratio[0])) if self.template_3points: self.face_template = np.array([[192, 240], [319, 240], [257, 371]]) else: # standard 5 landmarks for FFHQ faces with 512 x 512 self.face_template = np.array([[192.98138, 239.94708], [318.90277, 240.1936], [256.63416, 314.01935], [201.26117, 371.41043], [313.08905, 371.15118]]) self.face_template = self.face_template * (face_size / 512.0) if self.crop_ratio[0] > 1: self.face_template[:, 1] += face_size * (self.crop_ratio[0] - 1) / 2 if self.crop_ratio[1] > 1: self.face_template[:, 0] += face_size * (self.crop_ratio[1] - 1) / 2 self.save_ext = save_ext self.pad_blur = pad_blur if self.pad_blur is True: self.template_3points = False self.all_landmarks_5 = [] self.det_faces = [] self.affine_matrices = [] self.inverse_affine_matrices = [] self.cropped_faces = [] self.restored_faces = [] self.pad_input_imgs = [] if device is None: self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') else: self.device = device # init face detection model self.face_det = init_detection_model(det_model, half=False, device=self.device, model_rootpath=model_rootpath) # init face parsing model self.use_parse = use_parse self.face_parse = init_parsing_model(model_name='parsenet', device=self.device, model_rootpath=model_rootpath) def set_upscale_factor(self, upscale_factor): self.upscale_factor = upscale_factor def read_image(self, img): # self.input_img is Numpy array, (h, w, c), BGR, uint8, [0, 255] if isinstance(img, str): img = cv2.imread(img) if np.max(img) > 256: # 16-bit image img = img / 65535 * 255 if len(img.shape) == 2: # gray image img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) elif img.shape[2] == 4: # RGBA image with alpha channel img = img[:, :, 0:3] self.input_img = img def get_face_landmarks_5(self, only_keep_largest=False, only_center_face=False, resize=None, blur_ratio=0.01, eye_dist_threshold=None): if resize is None: scale = 1 input_img = self.input_img else: h, w = self.input_img.shape[0:2] scale = min(h, w) / resize h, w = int(h / scale), int(w / scale) input_img = cv2.resize(self.input_img, (w, h), interpolation=cv2.INTER_LANCZOS4) with torch.no_grad(): bboxes = self.face_det.detect_faces(input_img, 0.97) * scale for bbox in bboxes: # remove faces with too small eye distance: side faces or too small faces eye_dist = np.linalg.norm([bbox[5] - bbox[7], bbox[6] - bbox[8]]) if eye_dist_threshold is not None and (eye_dist < eye_dist_threshold): continue if self.template_3points: landmark = np.array([[bbox[i], bbox[i + 1]] for i in range(5, 11, 2)]) else: landmark = np.array([[bbox[i], bbox[i + 1]] for i in range(5, 15, 2)]) self.all_landmarks_5.append(landmark) self.det_faces.append(bbox[0:5]) if len(self.det_faces) == 0: return 0 if only_keep_largest: h, w, _ = self.input_img.shape self.det_faces, largest_idx = get_largest_face(self.det_faces, h, w) self.all_landmarks_5 = [self.all_landmarks_5[largest_idx]] elif only_center_face: h, w, _ = self.input_img.shape self.det_faces, center_idx = get_center_face(self.det_faces, h, w) self.all_landmarks_5 = [self.all_landmarks_5[center_idx]] # pad blurry images if self.pad_blur: self.pad_input_imgs = [] for landmarks in self.all_landmarks_5: # get landmarks eye_left = landmarks[0, :] eye_right = landmarks[1, :] eye_avg = (eye_left + eye_right) * 0.5 mouth_avg = (landmarks[3, :] + landmarks[4, :]) * 0.5 eye_to_eye = eye_right - eye_left eye_to_mouth = mouth_avg - eye_avg # Get the oriented crop rectangle # x: half width of the oriented crop rectangle x = eye_to_eye - np.flipud(eye_to_mouth) * [-1, 1] # - np.flipud(eye_to_mouth) * [-1, 1]: rotate 90 clockwise # norm with the hypotenuse: get the direction x /= np.hypot(*x) # get the hypotenuse of a right triangle rect_scale = 1.5 x *= max(np.hypot(*eye_to_eye) * 2.0 * rect_scale, np.hypot(*eye_to_mouth) * 1.8 * rect_scale) # y: half height of the oriented crop rectangle y = np.flipud(x) * [-1, 1] # c: center c = eye_avg + eye_to_mouth * 0.1 # quad: (left_top, left_bottom, right_bottom, right_top) quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y]) # qsize: side length of the square qsize = np.hypot(*x) * 2 border = max(int(np.rint(qsize * 0.1)), 3) # get pad # pad: (width_left, height_top, width_right, height_bottom) pad = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))), int(np.ceil(max(quad[:, 1])))) pad = [ max(-pad[0] + border, 1), max(-pad[1] + border, 1), max(pad[2] - self.input_img.shape[0] + border, 1), max(pad[3] - self.input_img.shape[1] + border, 1) ] if max(pad) > 1: # pad image pad_img = np.pad(self.input_img, ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect') # modify landmark coords landmarks[:, 0] += pad[0] landmarks[:, 1] += pad[1] # blur pad images h, w, _ = pad_img.shape y, x, _ = np.ogrid[:h, :w, :1] mask = np.maximum(1.0 - np.minimum(np.float32(x) / pad[0], np.float32(w - 1 - x) / pad[2]), 1.0 - np.minimum(np.float32(y) / pad[1], np.float32(h - 1 - y) / pad[3])) blur = int(qsize * blur_ratio) if blur % 2 == 0: blur += 1 blur_img = cv2.boxFilter(pad_img, 0, ksize=(blur, blur)) # blur_img = cv2.GaussianBlur(pad_img, (blur, blur), 0) pad_img = pad_img.astype('float32') pad_img += (blur_img - pad_img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0) pad_img += (np.median(pad_img, axis=(0, 1)) - pad_img) * np.clip(mask, 0.0, 1.0) pad_img = np.clip(pad_img, 0, 255) # float32, [0, 255] self.pad_input_imgs.append(pad_img) else: self.pad_input_imgs.append(np.copy(self.input_img)) return len(self.all_landmarks_5) def align_warp_face(self, save_cropped_path=None, border_mode='constant'): if self.pad_blur: assert len(self.pad_input_imgs) == len( self.all_landmarks_5), f'Mismatched samples: {len(self.pad_input_imgs)} and {len(self.all_landmarks_5)}' for idx, landmark in enumerate(self.all_landmarks_5): # use 5 landmarks to get affine matrix # use cv2.LMEDS method for the equivalence to skimage transform # ref: https://blog.csdn.net/yichxi/article/details/115827338 affine_matrix = cv2.estimateAffinePartial2D(landmark, self.face_template, method=cv2.LMEDS)[0] self.affine_matrices.append(affine_matrix) # warp and crop faces if border_mode == 'constant': border_mode = cv2.BORDER_CONSTANT elif border_mode == 'reflect101': border_mode = cv2.BORDER_REFLECT101 elif border_mode == 'reflect': border_mode = cv2.BORDER_REFLECT if self.pad_blur: input_img = self.pad_input_imgs[idx] else: input_img = self.input_img cropped_face = cv2.warpAffine( input_img, affine_matrix, self.face_size, borderMode=border_mode, borderValue=(135, 133, 132)) # gray self.cropped_faces.append(cropped_face) # save the cropped face if save_cropped_path is not None: path = os.path.splitext(save_cropped_path)[0] save_path = f'{path}_{idx:02d}.{self.save_ext}' imwrite(cropped_face, save_path) def get_inverse_affine(self, save_inverse_affine_path=None): for idx, affine_matrix in enumerate(self.affine_matrices): inverse_affine = cv2.invertAffineTransform(affine_matrix) inverse_affine *= self.upscale_factor self.inverse_affine_matrices.append(inverse_affine) # save inverse affine matrices if save_inverse_affine_path is not None: path, _ = os.path.splitext(save_inverse_affine_path) save_path = f'{path}_{idx:02d}.pth' torch.save(inverse_affine, save_path) def add_restored_face(self, face): self.restored_faces.append(face) def paste_faces_to_input_image(self, save_path=None, upsample_img=None): h, w, _ = self.input_img.shape h_up, w_up = int(h * self.upscale_factor), int(w * self.upscale_factor) if upsample_img is None: # simply resize the background upsample_img = cv2.resize(self.input_img, (w_up, h_up), interpolation=cv2.INTER_LANCZOS4) else: upsample_img = cv2.resize(upsample_img, (w_up, h_up), interpolation=cv2.INTER_LANCZOS4) assert len(self.restored_faces) == len( self.inverse_affine_matrices), ('length of restored_faces and affine_matrices are different.') for restored_face, inverse_affine in zip(self.restored_faces, self.inverse_affine_matrices): # Add an offset to inverse affine matrix, for more precise back alignment if self.upscale_factor > 1: extra_offset = 0.5 * self.upscale_factor else: extra_offset = 0 inverse_affine[:, 2] += extra_offset inv_restored = cv2.warpAffine(restored_face, inverse_affine, (w_up, h_up)) if self.use_parse: # inference face_input = cv2.resize(restored_face, (512, 512), interpolation=cv2.INTER_LINEAR) face_input = img2tensor(face_input.astype('float32') / 255., bgr2rgb=True, float32=True) normalize(face_input, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True) face_input = torch.unsqueeze(face_input, 0).to(self.device) with torch.no_grad(): out = self.face_parse(face_input)[0] out = out.argmax(dim=1).squeeze().cpu().numpy() mask = np.zeros(out.shape) MASK_COLORMAP = [0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 255, 0, 0, 0] for idx, color in enumerate(MASK_COLORMAP): mask[out == idx] = color # blur the mask mask = cv2.GaussianBlur(mask, (101, 101), 11) mask = cv2.GaussianBlur(mask, (101, 101), 11) # remove the black borders thres = 10 mask[:thres, :] = 0 mask[-thres:, :] = 0 mask[:, :thres] = 0 mask[:, -thres:] = 0 mask = mask / 255. mask = cv2.resize(mask, restored_face.shape[:2]) mask = cv2.warpAffine(mask, inverse_affine, (w_up, h_up), flags=3) inv_soft_mask = mask[:, :, None] pasted_face = inv_restored else: # use square parse maps mask = np.ones(self.face_size, dtype=np.float32) inv_mask = cv2.warpAffine(mask, inverse_affine, (w_up, h_up)) # remove the black borders inv_mask_erosion = cv2.erode( inv_mask, np.ones((int(2 * self.upscale_factor), int(2 * self.upscale_factor)), np.uint8)) pasted_face = inv_mask_erosion[:, :, None] * inv_restored total_face_area = np.sum(inv_mask_erosion) # // 3 # compute the fusion edge based on the area of face w_edge = int(total_face_area**0.5) // 20 erosion_radius = w_edge * 2 inv_mask_center = cv2.erode(inv_mask_erosion, np.ones((erosion_radius, erosion_radius), np.uint8)) blur_size = w_edge * 2 inv_soft_mask = cv2.GaussianBlur(inv_mask_center, (blur_size + 1, blur_size + 1), 0) if len(upsample_img.shape) == 2: # upsample_img is gray image upsample_img = upsample_img[:, :, None] inv_soft_mask = inv_soft_mask[:, :, None] if len(upsample_img.shape) == 3 and upsample_img.shape[2] == 4: # alpha channel alpha = upsample_img[:, :, 3:] upsample_img = inv_soft_mask * pasted_face + (1 - inv_soft_mask) * upsample_img[:, :, 0:3] upsample_img = np.concatenate((upsample_img, alpha), axis=2) else: upsample_img = inv_soft_mask * pasted_face + (1 - inv_soft_mask) * upsample_img if np.max(upsample_img) > 256: # 16-bit image upsample_img = upsample_img.astype(np.uint16) else: upsample_img = upsample_img.astype(np.uint8) if save_path is not None: path = os.path.splitext(save_path)[0] save_path = f'{path}.{self.save_ext}' imwrite(upsample_img, save_path) return upsample_img def clean_all(self): self.all_landmarks_5 = [] self.restored_faces = [] self.affine_matrices = [] self.cropped_faces = [] self.inverse_affine_matrices = [] self.det_faces = [] self.pad_input_imgs = []
--- +++ @@ -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 path or cv2 loaded image.""" # self.input_img is Numpy array, (h, w, c), BGR, uint8, [0, 255] if isinstance(img, str): img = cv2.imread(img) @@ -230,6 +232,8 @@ return len(self.all_landmarks_5) def align_warp_face(self, save_cropped_path=None, border_mode='constant'): + """Align and warp faces with face template. + """ if self.pad_blur: assert len(self.pad_input_imgs) == len( self.all_landmarks_5), f'Mismatched samples: {len(self.pad_input_imgs)} and {len(self.all_landmarks_5)}' @@ -260,6 +264,7 @@ imwrite(cropped_face, save_path) def get_inverse_affine(self, save_inverse_affine_path=None): + """Get inverse affine matrix.""" for idx, affine_matrix in enumerate(self.affine_matrices): inverse_affine = cv2.invertAffineTransform(affine_matrix) inverse_affine *= self.upscale_factor @@ -366,4 +371,4 @@ self.cropped_faces = [] self.inverse_affine_matrices = [] self.det_faces = [] - self.pad_input_imgs = []+ self.pad_input_imgs = []
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.facexlib.detection.retinaface_net import FPN, SSH, MobileNetV1, make_bbox_head, make_class_head, make_landmark_head from extras.facexlib.detection.retinaface_utils import (PriorBox, batched_decode, batched_decode_landm, decode, decode_landm, py_cpu_nms) def generate_config(network_name): cfg_mnet = { 'name': 'mobilenet0.25', 'min_sizes': [[16, 32], [64, 128], [256, 512]], 'steps': [8, 16, 32], 'variance': [0.1, 0.2], 'clip': False, 'loc_weight': 2.0, 'gpu_train': True, 'batch_size': 32, 'ngpu': 1, 'epoch': 250, 'decay1': 190, 'decay2': 220, 'image_size': 640, 'return_layers': { 'stage1': 1, 'stage2': 2, 'stage3': 3 }, 'in_channel': 32, 'out_channel': 64 } cfg_re50 = { 'name': 'Resnet50', 'min_sizes': [[16, 32], [64, 128], [256, 512]], 'steps': [8, 16, 32], 'variance': [0.1, 0.2], 'clip': False, 'loc_weight': 2.0, 'gpu_train': True, 'batch_size': 24, 'ngpu': 4, 'epoch': 100, 'decay1': 70, 'decay2': 90, 'image_size': 840, 'return_layers': { 'layer2': 1, 'layer3': 2, 'layer4': 3 }, 'in_channel': 256, 'out_channel': 256 } if network_name == 'mobile0.25': return cfg_mnet elif network_name == 'resnet50': return cfg_re50 else: raise NotImplementedError(f'network_name={network_name}') class RetinaFace(nn.Module): def __init__(self, network_name='resnet50', half=False, phase='test', device=None): self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') if device is None else device super(RetinaFace, self).__init__() self.half_inference = half cfg = generate_config(network_name) self.backbone = cfg['name'] self.model_name = f'retinaface_{network_name}' self.cfg = cfg self.phase = phase self.target_size, self.max_size = 1600, 2150 self.resize, self.scale, self.scale1 = 1., None, None self.mean_tensor = torch.tensor([[[[104.]], [[117.]], [[123.]]]], device=self.device) self.reference = get_reference_facial_points(default_square=True) # Build network. backbone = None if cfg['name'] == 'mobilenet0.25': backbone = MobileNetV1() self.body = IntermediateLayerGetter(backbone, cfg['return_layers']) elif cfg['name'] == 'Resnet50': import torchvision.models as models backbone = models.resnet50(weights=None) self.body = IntermediateLayerGetter(backbone, cfg['return_layers']) in_channels_stage2 = cfg['in_channel'] in_channels_list = [ in_channels_stage2 * 2, in_channels_stage2 * 4, in_channels_stage2 * 8, ] out_channels = cfg['out_channel'] self.fpn = FPN(in_channels_list, out_channels) self.ssh1 = SSH(out_channels, out_channels) self.ssh2 = SSH(out_channels, out_channels) self.ssh3 = SSH(out_channels, out_channels) self.ClassHead = make_class_head(fpn_num=3, inchannels=cfg['out_channel']) self.BboxHead = make_bbox_head(fpn_num=3, inchannels=cfg['out_channel']) self.LandmarkHead = make_landmark_head(fpn_num=3, inchannels=cfg['out_channel']) self.to(self.device) self.eval() if self.half_inference: self.half() def forward(self, inputs): out = self.body(inputs) if self.backbone == 'mobilenet0.25' or self.backbone == 'Resnet50': out = list(out.values()) # FPN fpn = self.fpn(out) # SSH feature1 = self.ssh1(fpn[0]) feature2 = self.ssh2(fpn[1]) feature3 = self.ssh3(fpn[2]) features = [feature1, feature2, feature3] bbox_regressions = torch.cat([self.BboxHead[i](feature) for i, feature in enumerate(features)], dim=1) classifications = torch.cat([self.ClassHead[i](feature) for i, feature in enumerate(features)], dim=1) tmp = [self.LandmarkHead[i](feature) for i, feature in enumerate(features)] ldm_regressions = (torch.cat(tmp, dim=1)) if self.phase == 'train': output = (bbox_regressions, classifications, ldm_regressions) else: output = (bbox_regressions, F.softmax(classifications, dim=-1), ldm_regressions) return output def __detect_faces(self, inputs): # get scale height, width = inputs.shape[2:] self.scale = torch.tensor([width, height, width, height], dtype=torch.float32, device=self.device) tmp = [width, height, width, height, width, height, width, height, width, height] self.scale1 = torch.tensor(tmp, dtype=torch.float32, device=self.device) # forawrd inputs = inputs.to(self.device) if self.half_inference: inputs = inputs.half() loc, conf, landmarks = self(inputs) # get priorbox priorbox = PriorBox(self.cfg, image_size=inputs.shape[2:]) priors = priorbox.forward().to(self.device) return loc, conf, landmarks, priors # single image detection def transform(self, image, use_origin_size): # convert to opencv format if isinstance(image, Image.Image): image = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR) image = image.astype(np.float32) # testing scale im_size_min = np.min(image.shape[0:2]) im_size_max = np.max(image.shape[0:2]) resize = float(self.target_size) / float(im_size_min) # prevent bigger axis from being more than max_size if np.round(resize * im_size_max) > self.max_size: resize = float(self.max_size) / float(im_size_max) resize = 1 if use_origin_size else resize # resize if resize != 1: image = cv2.resize(image, None, None, fx=resize, fy=resize, interpolation=cv2.INTER_LINEAR) # convert to torch.tensor format # image -= (104, 117, 123) image = image.transpose(2, 0, 1) image = torch.from_numpy(image).unsqueeze(0) return image, resize def detect_faces( self, image, conf_threshold=0.8, nms_threshold=0.4, use_origin_size=True, ): image, self.resize = self.transform(image, use_origin_size) image = image.to(self.device) if self.half_inference: image = image.half() image = image - self.mean_tensor loc, conf, landmarks, priors = self.__detect_faces(image) boxes = decode(loc.data.squeeze(0), priors.data, self.cfg['variance']) boxes = boxes * self.scale / self.resize boxes = boxes.cpu().numpy() scores = conf.squeeze(0).data.cpu().numpy()[:, 1] landmarks = decode_landm(landmarks.squeeze(0), priors, self.cfg['variance']) landmarks = landmarks * self.scale1 / self.resize landmarks = landmarks.cpu().numpy() # ignore low scores inds = np.where(scores > conf_threshold)[0] boxes, landmarks, scores = boxes[inds], landmarks[inds], scores[inds] # sort order = scores.argsort()[::-1] boxes, landmarks, scores = boxes[order], landmarks[order], scores[order] # do NMS bounding_boxes = np.hstack((boxes, scores[:, np.newaxis])).astype(np.float32, copy=False) keep = py_cpu_nms(bounding_boxes, nms_threshold) bounding_boxes, landmarks = bounding_boxes[keep, :], landmarks[keep] # self.t['forward_pass'].toc() # print(self.t['forward_pass'].average_time) # import sys # sys.stdout.flush() return np.concatenate((bounding_boxes, landmarks), axis=1) def __align_multi(self, image, boxes, landmarks, limit=None): if len(boxes) < 1: return [], [] if limit: boxes = boxes[:limit] landmarks = landmarks[:limit] faces = [] for landmark in landmarks: facial5points = [[landmark[2 * j], landmark[2 * j + 1]] for j in range(5)] warped_face = warp_and_crop_face(np.array(image), facial5points, self.reference, crop_size=(112, 112)) faces.append(warped_face) return np.concatenate((boxes, landmarks), axis=1), faces def align_multi(self, img, conf_threshold=0.8, limit=None): rlt = self.detect_faces(img, conf_threshold=conf_threshold) boxes, landmarks = rlt[:, 0:5], rlt[:, 5:] return self.__align_multi(img, boxes, landmarks, limit) # batched detection def batched_transform(self, frames, use_origin_size): from_PIL = True if isinstance(frames[0], Image.Image) else False # convert to opencv format if from_PIL: frames = [cv2.cvtColor(np.asarray(frame), cv2.COLOR_RGB2BGR) for frame in frames] frames = np.asarray(frames, dtype=np.float32) # testing scale im_size_min = np.min(frames[0].shape[0:2]) im_size_max = np.max(frames[0].shape[0:2]) resize = float(self.target_size) / float(im_size_min) # prevent bigger axis from being more than max_size if np.round(resize * im_size_max) > self.max_size: resize = float(self.max_size) / float(im_size_max) resize = 1 if use_origin_size else resize # resize if resize != 1: if not from_PIL: frames = F.interpolate(frames, scale_factor=resize) else: frames = [ cv2.resize(frame, None, None, fx=resize, fy=resize, interpolation=cv2.INTER_LINEAR) for frame in frames ] # convert to torch.tensor format if not from_PIL: frames = frames.transpose(1, 2).transpose(1, 3).contiguous() else: frames = frames.transpose((0, 3, 1, 2)) frames = torch.from_numpy(frames) return frames, resize def batched_detect_faces(self, frames, conf_threshold=0.8, nms_threshold=0.4, use_origin_size=True): # self.t['forward_pass'].tic() frames, self.resize = self.batched_transform(frames, use_origin_size) frames = frames.to(self.device) frames = frames - self.mean_tensor b_loc, b_conf, b_landmarks, priors = self.__detect_faces(frames) final_bounding_boxes, final_landmarks = [], [] # decode priors = priors.unsqueeze(0) b_loc = batched_decode(b_loc, priors, self.cfg['variance']) * self.scale / self.resize b_landmarks = batched_decode_landm(b_landmarks, priors, self.cfg['variance']) * self.scale1 / self.resize b_conf = b_conf[:, :, 1] # index for selection b_indice = b_conf > conf_threshold # concat b_loc_and_conf = torch.cat((b_loc, b_conf.unsqueeze(-1)), dim=2).float() for pred, landm, inds in zip(b_loc_and_conf, b_landmarks, b_indice): # ignore low scores pred, landm = pred[inds, :], landm[inds, :] if pred.shape[0] == 0: final_bounding_boxes.append(np.array([], dtype=np.float32)) final_landmarks.append(np.array([], dtype=np.float32)) continue # sort # order = score.argsort(descending=True) # box, landm, score = box[order], landm[order], score[order] # to CPU bounding_boxes, landm = pred.cpu().numpy(), landm.cpu().numpy() # NMS keep = py_cpu_nms(bounding_boxes, nms_threshold) bounding_boxes, landmarks = bounding_boxes[keep, :], landm[keep] # append final_bounding_boxes.append(bounding_boxes) final_landmarks.append(landmarks) # self.t['forward_pass'].toc(average=True) # self.batch_time += self.t['forward_pass'].diff # self.total_frame += len(frames) # print(self.batch_time / self.total_frame) return final_bounding_boxes, final_landmarks
--- +++ @@ -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 origin size. + """ from_PIL = True if isinstance(frames[0], Image.Image) else False # convert to opencv format @@ -296,6 +302,18 @@ return frames, resize def batched_detect_faces(self, frames, conf_threshold=0.8, nms_threshold=0.4, use_origin_size=True): + """ + Arguments: + frames: a list of PIL.Image, or np.array(shape=[n, h, w, c], + type=np.uint8, BGR format). + conf_threshold: confidence threshold. + nms_threshold: nms threshold. + use_origin_size: whether to use origin size. + Returns: + final_bounding_boxes: list of np.array ([n_boxes, 5], + type=np.float32). + final_landmarks: list of np.array ([n_boxes, 10], type=np.float32). + """ # self.t['forward_pass'].tic() frames, self.resize = self.batched_transform(frames, use_origin_size) frames = frames.to(self.device) @@ -345,4 +363,4 @@ # self.total_frame += len(frames) # print(self.batch_time / self.total_frame) - return final_bounding_boxes, final_landmarks+ return final_bounding_boxes, final_landmarks
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.ones((uv.shape[0], 1)))) xy = np.dot(uv, trans) xy = xy[:, 0:-1] return xy def tforminv(trans, uv): Tinv = inv(trans) xy = tformfwd(Tinv, uv) return xy def findNonreflectiveSimilarity(uv, xy, options=None): options = {'K': 2} K = options['K'] M = xy.shape[0] x = xy[:, 0].reshape((-1, 1)) # use reshape to keep a column vector y = xy[:, 1].reshape((-1, 1)) # use reshape to keep a column vector tmp1 = np.hstack((x, y, np.ones((M, 1)), np.zeros((M, 1)))) tmp2 = np.hstack((y, -x, np.zeros((M, 1)), np.ones((M, 1)))) X = np.vstack((tmp1, tmp2)) u = uv[:, 0].reshape((-1, 1)) # use reshape to keep a column vector v = uv[:, 1].reshape((-1, 1)) # use reshape to keep a column vector U = np.vstack((u, v)) # We know that X * r = U if rank(X) >= 2 * K: r, _, _, _ = lstsq(X, U, rcond=-1) r = np.squeeze(r) else: raise Exception('cp2tform:twoUniquePointsReq') sc = r[0] ss = r[1] tx = r[2] ty = r[3] Tinv = np.array([[sc, -ss, 0], [ss, sc, 0], [tx, ty, 1]]) T = inv(Tinv) T[:, 2] = np.array([0, 0, 1]) return T, Tinv def findSimilarity(uv, xy, options=None): options = {'K': 2} # uv = np.array(uv) # xy = np.array(xy) # Solve for trans1 trans1, trans1_inv = findNonreflectiveSimilarity(uv, xy, options) # Solve for trans2 # manually reflect the xy data across the Y-axis xyR = xy xyR[:, 0] = -1 * xyR[:, 0] trans2r, trans2r_inv = findNonreflectiveSimilarity(uv, xyR, options) # manually reflect the tform to undo the reflection done on xyR TreflectY = np.array([[-1, 0, 0], [0, 1, 0], [0, 0, 1]]) trans2 = np.dot(trans2r, TreflectY) # Figure out if trans1 or trans2 is better xy1 = tformfwd(trans1, uv) norm1 = norm(xy1 - xy) xy2 = tformfwd(trans2, uv) norm2 = norm(xy2 - xy) if norm1 <= norm2: return trans1, trans1_inv else: trans2_inv = inv(trans2) return trans2, trans2_inv def get_similarity_transform(src_pts, dst_pts, reflective=True): if reflective: trans, trans_inv = findSimilarity(src_pts, dst_pts) else: trans, trans_inv = findNonreflectiveSimilarity(src_pts, dst_pts) return trans, trans_inv def cvt_tform_mat_for_cv2(trans): cv2_trans = trans[:, 0:2].T return cv2_trans def get_similarity_transform_for_cv2(src_pts, dst_pts, reflective=True): trans, trans_inv = get_similarity_transform(src_pts, dst_pts, reflective) cv2_trans = cvt_tform_mat_for_cv2(trans) return cv2_trans if __name__ == '__main__': """ u = [0, 6, -2] v = [0, 3, 5] x = [-1, 0, 4] y = [-1, -10, 4] # In Matlab, run: # # uv = [u'; v']; # xy = [x'; y']; # tform_sim=cp2tform(uv,xy,'similarity'); # # trans = tform_sim.tdata.T # ans = # -0.0764 -1.6190 0 # 1.6190 -0.0764 0 # -3.2156 0.0290 1.0000 # trans_inv = tform_sim.tdata.Tinv # ans = # # -0.0291 0.6163 0 # -0.6163 -0.0291 0 # -0.0756 1.9826 1.0000 # xy_m=tformfwd(tform_sim, u,v) # # xy_m = # # -3.2156 0.0290 # 1.1833 -9.9143 # 5.0323 2.8853 # uv_m=tforminv(tform_sim, x,y) # # uv_m = # # 0.5698 1.3953 # 6.0872 2.2733 # -2.6570 4.3314 """ u = [0, 6, -2] v = [0, 3, 5] x = [-1, 0, 4] y = [-1, -10, 4] uv = np.array((u, v)).T xy = np.array((x, y)).T print('\n--->uv:') print(uv) print('\n--->xy:') print(xy) trans, trans_inv = get_similarity_transform(uv, xy) print('\n--->trans matrix:') print(trans) print('\n--->trans_inv matrix:') print(trans_inv) print('\n---> apply transform to uv') print('\nxy_m = uv_augmented * trans') uv_aug = np.hstack((uv, np.ones((uv.shape[0], 1)))) xy_m = np.dot(uv_aug, trans) print(xy_m) print('\nxy_m = tformfwd(trans, uv)') xy_m = tformfwd(trans, uv) print(xy_m) print('\n---> apply inverse transform to xy') print('\nuv_m = xy_augmented * trans_inv') xy_aug = np.hstack((xy, np.ones((xy.shape[0], 1)))) uv_m = np.dot(xy_aug, trans_inv) print(uv_m) print('\nuv_m = tformfwd(trans_inv, xy)') uv_m = tformfwd(trans_inv, xy) print(uv_m) uv_m = tforminv(trans, xy) print('\nuv_m = tforminv(trans, xy)') print(uv_m)
--- +++ @@ -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) + + Returns: + ---------- + @xy: Kx2 np.array + each row is a pair of transformed coordinates (x, y) + """ uv = np.hstack((uv, np.ones((uv.shape[0], 1)))) xy = np.dot(uv, trans) xy = xy[:, 0:-1] @@ -18,6 +35,23 @@ def tforminv(trans, uv): + """ + Function: + ---------- + apply the inverse of 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) + + Returns: + ---------- + @xy: Kx2 np.array + each row is a pair of inverse-transformed coordinates (x, y) + """ Tinv = inv(trans) xy = tformfwd(Tinv, uv) return xy @@ -94,6 +128,36 @@ def get_similarity_transform(src_pts, dst_pts, reflective=True): + """ + Function: + ---------- + Find Similarity Transform Matrix 'trans': + u = src_pts[:, 0] + v = src_pts[:, 1] + x = dst_pts[:, 0] + y = dst_pts[:, 1] + [x, y, 1] = [u, v, 1] * trans + + Parameters: + ---------- + @src_pts: Kx2 np.array + source points, each row is a pair of coordinates (x, y) + @dst_pts: Kx2 np.array + destination points, each row is a pair of transformed + coordinates (x, y) + @reflective: True or False + if True: + use reflective similarity transform + else: + use non-reflective similarity transform + + Returns: + ---------- + @trans: 3x3 np.array + transform matrix from uv to xy + trans_inv: 3x3 np.array + inverse of trans, transform matrix from xy to uv + """ if reflective: trans, trans_inv = findSimilarity(src_pts, dst_pts) @@ -104,12 +168,64 @@ def cvt_tform_mat_for_cv2(trans): + """ + Function: + ---------- + Convert Transform Matrix 'trans' into 'cv2_trans' which could be + directly used by cv2.warpAffine(): + u = src_pts[:, 0] + v = src_pts[:, 1] + x = dst_pts[:, 0] + y = dst_pts[:, 1] + [x, y].T = cv_trans * [u, v, 1].T + + Parameters: + ---------- + @trans: 3x3 np.array + transform matrix from uv to xy + + Returns: + ---------- + @cv2_trans: 2x3 np.array + transform matrix from src_pts to dst_pts, could be directly used + for cv2.warpAffine() + """ cv2_trans = trans[:, 0:2].T return cv2_trans def get_similarity_transform_for_cv2(src_pts, dst_pts, reflective=True): + """ + Function: + ---------- + Find Similarity Transform Matrix 'cv2_trans' which could be + directly used by cv2.warpAffine(): + u = src_pts[:, 0] + v = src_pts[:, 1] + x = dst_pts[:, 0] + y = dst_pts[:, 1] + [x, y].T = cv_trans * [u, v, 1].T + + Parameters: + ---------- + @src_pts: Kx2 np.array + source points, each row is a pair of coordinates (x, y) + @dst_pts: Kx2 np.array + destination points, each row is a pair of transformed + coordinates (x, y) + reflective: True or False + if True: + use reflective similarity transform + else: + use non-reflective similarity transform + + Returns: + ---------- + @cv2_trans: 2x3 np.array + transform matrix from src_pts to dst_pts, could be directly used + for cv2.warpAffine() + """ trans, trans_inv = get_similarity_transform(src_pts, dst_pts, reflective) cv2_trans = cvt_tform_mat_for_cv2(trans) @@ -198,4 +314,4 @@ uv_m = tforminv(trans, xy) print('\nuv_m = tforminv(trans, xy)') - print(uv_m)+ print(uv_m)
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.items: return {}, {}, {} all_results = {} final_id_to_name = {} title_info = {} for source_id, news_list in news_data.items.items(): # 按平台过滤 if current_platform_ids is not None and source_id not in current_platform_ids: continue # 获取来源名称 source_name = news_data.id_to_name.get(source_id, source_id) final_id_to_name[source_id] = source_name if source_id not in all_results: all_results[source_id] = {} title_info[source_id] = {} for item in news_list: title = item.title ranks = item.ranks or [item.rank] first_time = item.first_time or item.crawl_time last_time = item.last_time or item.crawl_time count = item.count rank_timeline = item.rank_timeline all_results[source_id][title] = { "ranks": ranks, "url": item.url or "", "mobileUrl": item.mobile_url or "", } title_info[source_id][title] = { "first_time": first_time, "last_time": last_time, "count": count, "ranks": ranks, "url": item.url or "", "mobileUrl": item.mobile_url or "", "rank_timeline": rank_timeline, } return all_results, final_id_to_name, title_info except Exception as e: print(f"[存储] 从存储后端读取数据失败: {e}") return {}, {}, {} def read_all_today_titles( storage_manager, current_platform_ids: Optional[List[str]] = None, quiet: bool = False, ) -> Tuple[Dict, Dict, Dict]: all_results, final_id_to_name, title_info = read_all_today_titles_from_storage( storage_manager, current_platform_ids ) if not quiet: if all_results: total_count = sum(len(titles) for titles in all_results.values()) print(f"[存储] 已从存储后端读取 {total_count} 条标题") else: print("[存储] 当天暂无数据") return all_results, final_id_to_name, title_info def detect_latest_new_titles_from_storage( storage_manager, current_platform_ids: Optional[List[str]] = None, ) -> Dict: try: # 获取最新抓取数据 latest_data = storage_manager.get_latest_crawl_data() if not latest_data or not latest_data.items: return {} # 获取所有历史数据 all_data = storage_manager.get_today_all_data() if not all_data or not all_data.items: # 没有历史数据(第一次抓取),不应该有"新增"标题 return {} # 获取最新批次时间 latest_time = latest_data.crawl_time # 步骤1:收集最新批次的标题(last_crawl_time = latest_time 的标题) latest_titles = {} for source_id, news_list in latest_data.items.items(): if current_platform_ids is not None and source_id not in current_platform_ids: continue latest_titles[source_id] = {} for item in news_list: latest_titles[source_id][item.title] = { "ranks": [item.rank], "url": item.url or "", "mobileUrl": item.mobile_url or "", } # 步骤2:收集历史标题 # 关键逻辑:一个标题只要其 first_crawl_time < latest_time,就是历史标题 # 这样即使同一标题有多条记录(URL 不同),只要任何一条是历史的,该标题就算历史 historical_titles = {} for source_id, news_list in all_data.items.items(): if current_platform_ids is not None and source_id not in current_platform_ids: continue historical_titles[source_id] = set() for item in news_list: first_time = item.first_time or item.crawl_time # 如果该记录的首次出现时间早于最新批次,则该标题是历史标题 if first_time < latest_time: historical_titles[source_id].add(item.title) # 检查是否是当天第一次抓取(没有任何历史标题) # 如果所有平台的历史标题集合都为空,说明只有一个抓取批次 # 在这种情况下,将所有最新批次的标题视为"新增"(用于增量模式的第一次推送) has_historical_data = any(len(titles) > 0 for titles in historical_titles.values()) if not has_historical_data: # 第一次爬取:返回所有最新标题作为"新增" return latest_titles # 步骤3:找出新增标题 = 最新批次标题 - 历史标题 new_titles = {} for source_id, source_latest_titles in latest_titles.items(): historical_set = historical_titles.get(source_id, set()) source_new_titles = {} for title, title_data in source_latest_titles.items(): if title not in historical_set: source_new_titles[title] = title_data if source_new_titles: new_titles[source_id] = source_new_titles return new_titles except Exception as e: print(f"[存储] 从存储后端检测新标题失败: {e}") return {} def detect_latest_new_titles( storage_manager, current_platform_ids: Optional[List[str]] = None, quiet: bool = False, ) -> Dict: new_titles = detect_latest_new_titles_from_storage(storage_manager, current_platform_ids) if new_titles and not quiet: total_new = sum(len(titles) for titles in new_titles.values()) print(f"[存储] 从存储后端检测到 {total_new} 条新增标题") return new_titles
--- +++ @@ -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]] = None, ) -> Tuple[Dict, Dict, Dict]: + """ + 从存储后端读取当天所有标题(SQLite 数据) + + Args: + storage_manager: 存储管理器实例 + current_platform_ids: 当前监控的平台 ID 列表(用于过滤) + + Returns: + Tuple[Dict, Dict, Dict]: (all_results, id_to_name, title_info) + """ try: news_data = storage_manager.get_today_all_data() @@ -66,6 +85,17 @@ current_platform_ids: Optional[List[str]] = None, quiet: bool = False, ) -> Tuple[Dict, Dict, Dict]: + """ + 读取当天所有标题(从存储后端) + + Args: + storage_manager: 存储管理器实例 + current_platform_ids: 当前监控的平台 ID 列表(用于过滤) + quiet: 是否静默模式(不打印日志) + + Returns: + Tuple[Dict, Dict, Dict]: (all_results, id_to_name, title_info) + """ all_results, final_id_to_name, title_info = read_all_today_titles_from_storage( storage_manager, current_platform_ids ) @@ -84,6 +114,16 @@ storage_manager, current_platform_ids: Optional[List[str]] = None, ) -> Dict: + """ + 从存储后端检测最新批次的新增标题 + + Args: + storage_manager: 存储管理器实例 + current_platform_ids: 当前监控的平台 ID 列表(用于过滤) + + Returns: + Dict: 新增标题 {source_id: {title: title_data}} + """ try: # 获取最新抓取数据 latest_data = storage_manager.get_latest_crawl_data() @@ -160,8 +200,19 @@ current_platform_ids: Optional[List[str]] = None, quiet: bool = False, ) -> Dict: + """ + 检测当日最新批次的新增标题(从存储后端) + + Args: + storage_manager: 存储管理器实例 + current_platform_ids: 当前监控的平台 ID 列表(用于过滤) + quiet: 是否静默模式(不打印日志) + + Returns: + Dict: 新增标题 {source_id: {title: title_data}} + """ new_titles = detect_latest_new_titles_from_storage(storage_manager, current_platform_ids) if new_titles and not quiet: total_new = sum(len(titles) for titles in new_titles.values()) print(f"[存储] 从存储后端检测到 {total_new} 条新增标题") - return new_titles+ return new_titles
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, Dict, Optional from urllib.parse import urlparse import requests from .batch import add_batch_headers, get_max_batch_header_size from .formatters import convert_markdown_to_mrkdwn, strip_markdown def _render_ai_analysis(ai_analysis: Any, channel: str) -> str: if not ai_analysis: return "" try: from trendradar.ai.formatter import get_ai_analysis_renderer renderer = get_ai_analysis_renderer(channel) return renderer(ai_analysis) except ImportError: return "" # === SMTP 邮件配置 === SMTP_CONFIGS = { # Gmail(使用 STARTTLS) "gmail.com": {"server": "smtp.gmail.com", "port": 587, "encryption": "TLS"}, # QQ邮箱(使用 SSL,更稳定) "qq.com": {"server": "smtp.qq.com", "port": 465, "encryption": "SSL"}, # Outlook(使用 STARTTLS) "outlook.com": {"server": "smtp-mail.outlook.com", "port": 587, "encryption": "TLS"}, "hotmail.com": {"server": "smtp-mail.outlook.com", "port": 587, "encryption": "TLS"}, "live.com": {"server": "smtp-mail.outlook.com", "port": 587, "encryption": "TLS"}, # 网易邮箱(使用 SSL,更稳定) "163.com": {"server": "smtp.163.com", "port": 465, "encryption": "SSL"}, "126.com": {"server": "smtp.126.com", "port": 465, "encryption": "SSL"}, # 新浪邮箱(使用 SSL) "sina.com": {"server": "smtp.sina.com", "port": 465, "encryption": "SSL"}, # 搜狐邮箱(使用 SSL) "sohu.com": {"server": "smtp.sohu.com", "port": 465, "encryption": "SSL"}, # 天翼邮箱(使用 SSL) "189.cn": {"server": "smtp.189.cn", "port": 465, "encryption": "SSL"}, # 阿里云邮箱(使用 TLS) "aliyun.com": {"server": "smtp.aliyun.com", "port": 465, "encryption": "TLS"}, # Yandex邮箱(使用 TLS) "yandex.com": {"server": "smtp.yandex.com", "port": 465, "encryption": "TLS"}, # iCloud邮箱(使用 SSL) "icloud.com": {"server": "smtp.mail.me.com", "port": 587, "encryption": "SSL"}, } def send_to_feishu( webhook_url: str, report_data: Dict, report_type: str, update_info: Optional[Dict] = None, proxy_url: Optional[str] = None, mode: str = "daily", account_label: str = "", *, batch_size: int = 29000, batch_interval: float = 1.0, split_content_func: Callable = None, get_time_func: Callable = None, rss_items: Optional[list] = None, rss_new_items: Optional[list] = None, ai_analysis: Any = None, display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: headers = {"Content-Type": "application/json"} proxies = None if proxy_url: proxies = {"http": proxy_url, "https": proxy_url} # 日志前缀 log_prefix = f"飞书{account_label}" if account_label else "飞书" # 渲染 AI 分析内容(如果有) ai_content = None ai_stats = None if ai_analysis: ai_content = _render_ai_analysis(ai_analysis, "feishu") # 提取 AI 分析统计数据(只要 AI 分析成功就显示) if getattr(ai_analysis, "success", False): ai_stats = { "total_news": getattr(ai_analysis, "total_news", 0), "analyzed_news": getattr(ai_analysis, "analyzed_news", 0), "max_news_limit": getattr(ai_analysis, "max_news_limit", 0), "hotlist_count": getattr(ai_analysis, "hotlist_count", 0), "rss_count": getattr(ai_analysis, "rss_count", 0), "ai_mode": getattr(ai_analysis, "ai_mode", ""), } # 预留批次头部空间,避免添加头部后超限 header_reserve = get_max_batch_header_size("feishu") batches = split_content_func( report_data, "feishu", update_info, max_bytes=batch_size - header_reserve, mode=mode, rss_items=rss_items, rss_new_items=rss_new_items, ai_content=ai_content, standalone_data=standalone_data, ai_stats=ai_stats, report_type=report_type, ) # 统一添加批次头部(已预留空间,不会超限) batches = add_batch_headers(batches, "feishu", batch_size) print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]") # 逐批发送 for i, batch_content in enumerate(batches, 1): content_size = len(batch_content.encode("utf-8")) print( f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]" ) # 飞书 webhook 只显示 content.text,所有信息都整合到 text 中 payload = { "msg_type": "interactive", "content": { "text": batch_content, }, } try: response = requests.post( webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30 ) if response.status_code == 200: result = response.json() # 检查飞书的响应状态 if result.get("StatusCode") == 0 or result.get("code") == 0: print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]") # 批次间间隔 if i < len(batches): time.sleep(batch_interval) else: error_msg = result.get("msg") or result.get("StatusMessage", "未知错误") print( f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{error_msg}" ) return False else: print( f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}" ) return False except Exception as e: print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}") return False print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]") return True def send_to_dingtalk( webhook_url: str, report_data: Dict, report_type: str, update_info: Optional[Dict] = None, proxy_url: Optional[str] = None, mode: str = "daily", account_label: str = "", *, batch_size: int = 20000, batch_interval: float = 1.0, split_content_func: Callable = None, rss_items: Optional[list] = None, rss_new_items: Optional[list] = None, ai_analysis: Any = None, display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: headers = {"Content-Type": "application/json"} proxies = None if proxy_url: proxies = {"http": proxy_url, "https": proxy_url} # 日志前缀 log_prefix = f"钉钉{account_label}" if account_label else "钉钉" # 渲染 AI 分析内容(如果有) ai_content = None ai_stats = None if ai_analysis: ai_content = _render_ai_analysis(ai_analysis, "dingtalk") # 提取 AI 分析统计数据(只要 AI 分析成功就显示) if getattr(ai_analysis, "success", False): ai_stats = { "total_news": getattr(ai_analysis, "total_news", 0), "analyzed_news": getattr(ai_analysis, "analyzed_news", 0), "max_news_limit": getattr(ai_analysis, "max_news_limit", 0), "hotlist_count": getattr(ai_analysis, "hotlist_count", 0), "rss_count": getattr(ai_analysis, "rss_count", 0), "ai_mode": getattr(ai_analysis, "ai_mode", ""), } # 预留批次头部空间,避免添加头部后超限 header_reserve = get_max_batch_header_size("dingtalk") batches = split_content_func( report_data, "dingtalk", update_info, max_bytes=batch_size - header_reserve, mode=mode, rss_items=rss_items, rss_new_items=rss_new_items, ai_content=ai_content, standalone_data=standalone_data, ai_stats=ai_stats, report_type=report_type, ) # 统一添加批次头部(已预留空间,不会超限) batches = add_batch_headers(batches, "dingtalk", batch_size) print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]") # 逐批发送 for i, batch_content in enumerate(batches, 1): content_size = len(batch_content.encode("utf-8")) print( f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]" ) payload = { "msgtype": "markdown", "markdown": { "title": f"TrendRadar 热点分析报告 - {report_type}", "text": batch_content, }, } try: response = requests.post( webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30 ) if response.status_code == 200: result = response.json() if result.get("errcode") == 0: print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]") # 批次间间隔 if i < len(batches): time.sleep(batch_interval) else: print( f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{result.get('errmsg')}" ) return False else: print( f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}" ) return False except Exception as e: print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}") return False print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]") return True def send_to_wework( webhook_url: str, report_data: Dict, report_type: str, update_info: Optional[Dict] = None, proxy_url: Optional[str] = None, mode: str = "daily", account_label: str = "", *, batch_size: int = 4000, batch_interval: float = 1.0, msg_type: str = "markdown", split_content_func: Callable = None, rss_items: Optional[list] = None, rss_new_items: Optional[list] = None, ai_analysis: Any = None, display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: headers = {"Content-Type": "application/json"} proxies = None if proxy_url: proxies = {"http": proxy_url, "https": proxy_url} # 日志前缀 log_prefix = f"企业微信{account_label}" if account_label else "企业微信" # 获取消息类型配置(markdown 或 text) is_text_mode = msg_type.lower() == "text" if is_text_mode: print(f"{log_prefix}使用 text 格式(个人微信模式)[{report_type}]") else: print(f"{log_prefix}使用 markdown 格式(群机器人模式)[{report_type}]") # text 模式使用 wework_text,markdown 模式使用 wework header_format_type = "wework_text" if is_text_mode else "wework" # 渲染 AI 分析内容(如果有) ai_content = None ai_stats = None if ai_analysis: ai_content = _render_ai_analysis(ai_analysis, "wework") # 提取 AI 分析统计数据(只要 AI 分析成功就显示) if getattr(ai_analysis, "success", False): ai_stats = { "total_news": getattr(ai_analysis, "total_news", 0), "analyzed_news": getattr(ai_analysis, "analyzed_news", 0), "max_news_limit": getattr(ai_analysis, "max_news_limit", 0), "hotlist_count": getattr(ai_analysis, "hotlist_count", 0), "rss_count": getattr(ai_analysis, "rss_count", 0), "ai_mode": getattr(ai_analysis, "ai_mode", ""), } # 获取分批内容,预留批次头部空间 header_reserve = get_max_batch_header_size(header_format_type) batches = split_content_func( report_data, "wework", update_info, max_bytes=batch_size - header_reserve, mode=mode, rss_items=rss_items, rss_new_items=rss_new_items, ai_content=ai_content, standalone_data=standalone_data, ai_stats=ai_stats, report_type=report_type, ) # 统一添加批次头部(已预留空间,不会超限) batches = add_batch_headers(batches, header_format_type, batch_size) print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]") # 逐批发送 for i, batch_content in enumerate(batches, 1): # 根据消息类型构建 payload if is_text_mode: # text 格式:去除 markdown 语法 plain_content = strip_markdown(batch_content) payload = {"msgtype": "text", "text": {"content": plain_content}} content_size = len(plain_content.encode("utf-8")) else: # markdown 格式:保持原样 payload = {"msgtype": "markdown", "markdown": {"content": batch_content}} content_size = len(batch_content.encode("utf-8")) print( f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]" ) try: response = requests.post( webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30 ) if response.status_code == 200: result = response.json() if result.get("errcode") == 0: print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]") # 批次间间隔 if i < len(batches): time.sleep(batch_interval) else: print( f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{result.get('errmsg')}" ) return False else: print( f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}" ) return False except Exception as e: print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}") return False print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]") return True def send_to_telegram( bot_token: str, chat_id: str, report_data: Dict, report_type: str, update_info: Optional[Dict] = None, proxy_url: Optional[str] = None, mode: str = "daily", account_label: str = "", *, batch_size: int = 4000, batch_interval: float = 1.0, split_content_func: Callable = None, rss_items: Optional[list] = None, rss_new_items: Optional[list] = None, ai_analysis: Any = None, display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: headers = {"Content-Type": "application/json"} url = f"https://api.telegram.org/bot{bot_token}/sendMessage" proxies = None if proxy_url: proxies = {"http": proxy_url, "https": proxy_url} # 日志前缀 log_prefix = f"Telegram{account_label}" if account_label else "Telegram" # 渲染 AI 分析内容(如果有) ai_content = None ai_stats = None if ai_analysis: ai_content = _render_ai_analysis(ai_analysis, "telegram") # 提取 AI 分析统计数据(只要 AI 分析成功就显示) if getattr(ai_analysis, "success", False): ai_stats = { "total_news": getattr(ai_analysis, "total_news", 0), "analyzed_news": getattr(ai_analysis, "analyzed_news", 0), "max_news_limit": getattr(ai_analysis, "max_news_limit", 0), "hotlist_count": getattr(ai_analysis, "hotlist_count", 0), "rss_count": getattr(ai_analysis, "rss_count", 0), "ai_mode": getattr(ai_analysis, "ai_mode", ""), } # 获取分批内容,预留批次头部空间 header_reserve = get_max_batch_header_size("telegram") batches = split_content_func( report_data, "telegram", update_info, max_bytes=batch_size - header_reserve, mode=mode, rss_items=rss_items, rss_new_items=rss_new_items, ai_content=ai_content, standalone_data=standalone_data, ai_stats=ai_stats, report_type=report_type, ) # 统一添加批次头部(已预留空间,不会超限) batches = add_batch_headers(batches, "telegram", batch_size) print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]") # 逐批发送 for i, batch_content in enumerate(batches, 1): content_size = len(batch_content.encode("utf-8")) print( f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]" ) payload = { "chat_id": chat_id, "text": batch_content, "parse_mode": "HTML", "disable_web_page_preview": True, } try: response = requests.post( url, headers=headers, json=payload, proxies=proxies, timeout=30 ) if response.status_code == 200: result = response.json() if result.get("ok"): print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]") # 批次间间隔 if i < len(batches): time.sleep(batch_interval) else: print( f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{result.get('description')}" ) return False else: print( f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}" ) return False except Exception as e: print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}") return False print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]") return True def send_to_email( from_email: str, password: str, to_email: str, report_type: str, html_file_path: str, custom_smtp_server: Optional[str] = None, custom_smtp_port: Optional[int] = None, *, get_time_func: Callable = None, ) -> bool: try: if not html_file_path or not Path(html_file_path).exists(): print(f"错误:HTML文件不存在或未提供: {html_file_path}") return False print(f"使用HTML文件: {html_file_path}") with open(html_file_path, "r", encoding="utf-8") as f: html_content = f.read() domain = from_email.split("@")[-1].lower() if custom_smtp_server and custom_smtp_port: # 使用自定义 SMTP 配置 smtp_server = custom_smtp_server smtp_port = int(custom_smtp_port) # 根据端口判断加密方式:465=SSL, 587=TLS if smtp_port == 465: use_tls = False # SSL 模式(SMTP_SSL) elif smtp_port == 587: use_tls = True # TLS 模式(STARTTLS) else: # 其他端口优先尝试 TLS(更安全,更广泛支持) use_tls = True elif domain in SMTP_CONFIGS: # 使用预设配置 config = SMTP_CONFIGS[domain] smtp_server = config["server"] smtp_port = config["port"] use_tls = config["encryption"] == "TLS" else: print(f"未识别的邮箱服务商: {domain},使用通用 SMTP 配置") smtp_server = f"smtp.{domain}" smtp_port = 587 use_tls = True msg = MIMEMultipart("alternative") # 严格按照 RFC 标准设置 From header sender_name = "TrendRadar" msg["From"] = formataddr((sender_name, from_email)) # 设置收件人 recipients = [addr.strip() for addr in to_email.split(",")] if len(recipients) == 1: msg["To"] = recipients[0] else: msg["To"] = ", ".join(recipients) # 设置邮件主题 now = get_time_func() if get_time_func else datetime.now() subject = f"TrendRadar 热点分析报告 - {report_type} - {now.strftime('%m月%d日 %H:%M')}" msg["Subject"] = Header(subject, "utf-8") # 设置其他标准 header msg["MIME-Version"] = "1.0" msg["Date"] = formatdate(localtime=True) msg["Message-ID"] = make_msgid() # 添加纯文本部分(作为备选) text_content = f""" TrendRadar 热点分析报告 ======================== 报告类型:{report_type} 生成时间:{now.strftime('%Y-%m-%d %H:%M:%S')} 请使用支持HTML的邮件客户端查看完整报告内容。 """ text_part = MIMEText(text_content, "plain", "utf-8") msg.attach(text_part) html_part = MIMEText(html_content, "html", "utf-8") msg.attach(html_part) print(f"正在发送邮件到 {to_email}...") print(f"SMTP 服务器: {smtp_server}:{smtp_port}") print(f"发件人: {from_email}") try: if use_tls: # TLS 模式 server = smtplib.SMTP(smtp_server, smtp_port, timeout=30) server.set_debuglevel(0) # 设为1可以查看详细调试信息 server.ehlo() server.starttls() server.ehlo() else: # SSL 模式 server = smtplib.SMTP_SSL(smtp_server, smtp_port, timeout=30) server.set_debuglevel(0) server.ehlo() # 登录 server.login(from_email, password) # 发送邮件 server.send_message(msg) server.quit() print(f"邮件发送成功 [{report_type}] -> {to_email}") return True except smtplib.SMTPServerDisconnected: print("邮件发送失败:服务器意外断开连接,请检查网络或稍后重试") return False except smtplib.SMTPAuthenticationError as e: print("邮件发送失败:认证错误,请检查邮箱和密码/授权码") print(f"详细错误: {str(e)}") return False except smtplib.SMTPRecipientsRefused as e: print(f"邮件发送失败:收件人地址被拒绝 {e}") return False except smtplib.SMTPSenderRefused as e: print(f"邮件发送失败:发件人地址被拒绝 {e}") return False except smtplib.SMTPDataError as e: print(f"邮件发送失败:邮件数据错误 {e}") return False except smtplib.SMTPConnectError as e: print(f"邮件发送失败:无法连接到 SMTP 服务器 {smtp_server}:{smtp_port}") print(f"详细错误: {str(e)}") return False except Exception as e: print(f"邮件发送失败 [{report_type}]:{e}") import traceback traceback.print_exc() return False def send_to_ntfy( server_url: str, topic: str, token: Optional[str], report_data: Dict, report_type: str, update_info: Optional[Dict] = None, proxy_url: Optional[str] = None, mode: str = "daily", account_label: str = "", *, batch_size: int = 3800, split_content_func: Callable = None, rss_items: Optional[list] = None, rss_new_items: Optional[list] = None, ai_analysis: Any = None, display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: # 日志前缀 log_prefix = f"ntfy{account_label}" if account_label else "ntfy" # 避免 HTTP header 编码问题 report_type_en_map = { "全天汇总": "Daily Summary", "当前榜单": "Current Ranking", "增量分析": "Incremental Update", "通知连通性测试": "Notification Test", } report_type_en = report_type_en_map.get(report_type, "News Report") headers = { "Content-Type": "text/plain; charset=utf-8", "Markdown": "yes", "Title": report_type_en, "Priority": "default", "Tags": "news", } if token: headers["Authorization"] = f"Bearer {token}" # 构建完整URL,确保格式正确 base_url = server_url.rstrip("/") if not base_url.startswith(("http://", "https://")): base_url = f"https://{base_url}" url = f"{base_url}/{topic}" proxies = None if proxy_url: proxies = {"http": proxy_url, "https": proxy_url} # 渲染 AI 分析内容(如果有),合并到主内容中 ai_content = None ai_stats = None if ai_analysis: ai_content = _render_ai_analysis(ai_analysis, "ntfy") # 提取 AI 分析统计数据(只要 AI 分析成功就显示) if getattr(ai_analysis, "success", False): ai_stats = { "total_news": getattr(ai_analysis, "total_news", 0), "analyzed_news": getattr(ai_analysis, "analyzed_news", 0), "max_news_limit": getattr(ai_analysis, "max_news_limit", 0), "hotlist_count": getattr(ai_analysis, "hotlist_count", 0), "rss_count": getattr(ai_analysis, "rss_count", 0), "ai_mode": getattr(ai_analysis, "ai_mode", ""), } # 获取分批内容,预留批次头部空间 header_reserve = get_max_batch_header_size("ntfy") batches = split_content_func( report_data, "ntfy", update_info, max_bytes=batch_size - header_reserve, mode=mode, rss_items=rss_items, rss_new_items=rss_new_items, ai_content=ai_content, standalone_data=standalone_data, ai_stats=ai_stats, report_type=report_type, ) # 统一添加批次头部(已预留空间,不会超限) batches = add_batch_headers(batches, "ntfy", batch_size) total_batches = len(batches) print(f"{log_prefix}消息分为 {total_batches} 批次发送 [{report_type}]") # 反转批次顺序,使得在ntfy客户端显示时顺序正确 # ntfy显示最新消息在上面,所以我们从最后一批开始推送 reversed_batches = list(reversed(batches)) print(f"{log_prefix}将按反向顺序推送(最后批次先推送),确保客户端显示顺序正确") # 逐批发送(反向顺序) success_count = 0 for idx, batch_content in enumerate(reversed_batches, 1): # 计算正确的批次编号(用户视角的编号) actual_batch_num = total_batches - idx + 1 content_size = len(batch_content.encode("utf-8")) print( f"发送{log_prefix}第 {actual_batch_num}/{total_batches} 批次(推送顺序: {idx}/{total_batches}),大小:{content_size} 字节 [{report_type}]" ) # 检查消息大小,确保不超过4KB if content_size > 4096: print(f"警告:{log_prefix}第 {actual_batch_num} 批次消息过大({content_size} 字节),可能被拒绝") # 更新 headers 的批次标识 current_headers = headers.copy() if total_batches > 1: current_headers["Title"] = f"{report_type_en} ({actual_batch_num}/{total_batches})" try: response = requests.post( url, headers=current_headers, data=batch_content.encode("utf-8"), proxies=proxies, timeout=30, ) if response.status_code == 200: print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送成功 [{report_type}]") success_count += 1 if idx < total_batches: # 公共服务器建议 2-3 秒,自托管可以更短 interval = 2 if "ntfy.sh" in server_url else 1 time.sleep(interval) elif response.status_code == 429: print( f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次速率限制 [{report_type}],等待后重试" ) time.sleep(10) # 等待10秒后重试 # 重试一次 retry_response = requests.post( url, headers=current_headers, data=batch_content.encode("utf-8"), proxies=proxies, timeout=30, ) if retry_response.status_code == 200: print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次重试成功 [{report_type}]") success_count += 1 else: print( f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次重试失败,状态码:{retry_response.status_code}" ) elif response.status_code == 413: print( f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次消息过大被拒绝 [{report_type}],消息大小:{content_size} 字节" ) else: print( f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送失败 [{report_type}],状态码:{response.status_code}" ) try: print(f"错误详情:{response.text}") except: pass except requests.exceptions.ConnectTimeout: print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次连接超时 [{report_type}]") except requests.exceptions.ReadTimeout: print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次读取超时 [{report_type}]") except requests.exceptions.ConnectionError as e: print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次连接错误 [{report_type}]:{e}") except Exception as e: print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送异常 [{report_type}]:{e}") # 判断整体发送是否成功 if success_count == total_batches: print(f"{log_prefix}所有 {total_batches} 批次发送完成 [{report_type}]") elif success_count > 0: print(f"{log_prefix}部分发送成功:{success_count}/{total_batches} 批次 [{report_type}]") else: print(f"{log_prefix}发送完全失败 [{report_type}]") return False return True def send_to_bark( bark_url: str, report_data: Dict, report_type: str, update_info: Optional[Dict] = None, proxy_url: Optional[str] = None, mode: str = "daily", account_label: str = "", *, batch_size: int = 3600, batch_interval: float = 1.0, split_content_func: Callable = None, rss_items: Optional[list] = None, rss_new_items: Optional[list] = None, ai_analysis: Any = None, display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: # 日志前缀 log_prefix = f"Bark{account_label}" if account_label else "Bark" proxies = None if proxy_url: proxies = {"http": proxy_url, "https": proxy_url} # 解析 Bark URL,提取 device_key 和 API 端点 # Bark URL 格式: https://api.day.app/device_key 或 https://bark.day.app/device_key parsed_url = urlparse(bark_url) device_key = parsed_url.path.strip('/').split('/')[0] if parsed_url.path else None if not device_key: print(f"{log_prefix} URL 格式错误,无法提取 device_key: {bark_url}") return False # 构建正确的 API 端点 api_endpoint = f"{parsed_url.scheme}://{parsed_url.netloc}/push" # 渲染 AI 分析内容(如果有),合并到主内容中 ai_content = None ai_stats = None if ai_analysis: ai_content = _render_ai_analysis(ai_analysis, "bark") # 提取 AI 分析统计数据(只要 AI 分析成功就显示) if getattr(ai_analysis, "success", False): ai_stats = { "total_news": getattr(ai_analysis, "total_news", 0), "analyzed_news": getattr(ai_analysis, "analyzed_news", 0), "max_news_limit": getattr(ai_analysis, "max_news_limit", 0), "hotlist_count": getattr(ai_analysis, "hotlist_count", 0), "rss_count": getattr(ai_analysis, "rss_count", 0), "ai_mode": getattr(ai_analysis, "ai_mode", ""), } # 获取分批内容,预留批次头部空间 header_reserve = get_max_batch_header_size("bark") batches = split_content_func( report_data, "bark", update_info, max_bytes=batch_size - header_reserve, mode=mode, rss_items=rss_items, rss_new_items=rss_new_items, ai_content=ai_content, standalone_data=standalone_data, ai_stats=ai_stats, report_type=report_type, ) # 统一添加批次头部(已预留空间,不会超限) batches = add_batch_headers(batches, "bark", batch_size) total_batches = len(batches) print(f"{log_prefix}消息分为 {total_batches} 批次发送 [{report_type}]") # 反转批次顺序,使得在Bark客户端显示时顺序正确 # Bark显示最新消息在上面,所以我们从最后一批开始推送 reversed_batches = list(reversed(batches)) print(f"{log_prefix}将按反向顺序推送(最后批次先推送),确保客户端显示顺序正确") # 逐批发送(反向顺序) success_count = 0 for idx, batch_content in enumerate(reversed_batches, 1): # 计算正确的批次编号(用户视角的编号) actual_batch_num = total_batches - idx + 1 content_size = len(batch_content.encode("utf-8")) print( f"发送{log_prefix}第 {actual_batch_num}/{total_batches} 批次(推送顺序: {idx}/{total_batches}),大小:{content_size} 字节 [{report_type}]" ) # 检查消息大小(Bark使用APNs,限制4KB) if content_size > 4096: print( f"警告:{log_prefix}第 {actual_batch_num}/{total_batches} 批次消息过大({content_size} 字节),可能被拒绝" ) # 构建JSON payload payload = { "title": report_type, "markdown": batch_content, "device_key": device_key, "sound": "default", "group": "TrendRadar", "action": "none", # 点击推送跳到 APP 不弹出弹框,方便阅读 } try: response = requests.post( api_endpoint, json=payload, proxies=proxies, timeout=30, ) if response.status_code == 200: result = response.json() if result.get("code") == 200: print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送成功 [{report_type}]") success_count += 1 # 批次间间隔 if idx < total_batches: time.sleep(batch_interval) else: print( f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送失败 [{report_type}],错误:{result.get('message', '未知错误')}" ) else: print( f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送失败 [{report_type}],状态码:{response.status_code}" ) try: print(f"错误详情:{response.text}") except: pass except requests.exceptions.ConnectTimeout: print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次连接超时 [{report_type}]") except requests.exceptions.ReadTimeout: print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次读取超时 [{report_type}]") except requests.exceptions.ConnectionError as e: print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次连接错误 [{report_type}]:{e}") except Exception as e: print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送异常 [{report_type}]:{e}") # 判断整体发送是否成功 if success_count == total_batches: print(f"{log_prefix}所有 {total_batches} 批次发送完成 [{report_type}]") elif success_count > 0: print(f"{log_prefix}部分发送成功:{success_count}/{total_batches} 批次 [{report_type}]") else: print(f"{log_prefix}发送完全失败 [{report_type}]") return False return True def send_to_slack( webhook_url: str, report_data: Dict, report_type: str, update_info: Optional[Dict] = None, proxy_url: Optional[str] = None, mode: str = "daily", account_label: str = "", *, batch_size: int = 4000, batch_interval: float = 1.0, split_content_func: Callable = None, rss_items: Optional[list] = None, rss_new_items: Optional[list] = None, ai_analysis: Any = None, display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: headers = {"Content-Type": "application/json"} proxies = None if proxy_url: proxies = {"http": proxy_url, "https": proxy_url} # 日志前缀 log_prefix = f"Slack{account_label}" if account_label else "Slack" # 渲染 AI 分析内容(如果有),合并到主内容中 ai_content = None ai_stats = None if ai_analysis: ai_content = _render_ai_analysis(ai_analysis, "slack") # 提取 AI 分析统计数据(只要 AI 分析成功就显示) if getattr(ai_analysis, "success", False): ai_stats = { "total_news": getattr(ai_analysis, "total_news", 0), "analyzed_news": getattr(ai_analysis, "analyzed_news", 0), "max_news_limit": getattr(ai_analysis, "max_news_limit", 0), "hotlist_count": getattr(ai_analysis, "hotlist_count", 0), "rss_count": getattr(ai_analysis, "rss_count", 0), "ai_mode": getattr(ai_analysis, "ai_mode", ""), } # 获取分批内容,预留批次头部空间 header_reserve = get_max_batch_header_size("slack") batches = split_content_func( report_data, "slack", update_info, max_bytes=batch_size - header_reserve, mode=mode, rss_items=rss_items, rss_new_items=rss_new_items, ai_content=ai_content, standalone_data=standalone_data, ai_stats=ai_stats, report_type=report_type, ) # 统一添加批次头部(已预留空间,不会超限) batches = add_batch_headers(batches, "slack", batch_size) print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]") # 逐批发送 for i, batch_content in enumerate(batches, 1): # 转换 Markdown 到 mrkdwn 格式 mrkdwn_content = convert_markdown_to_mrkdwn(batch_content) content_size = len(mrkdwn_content.encode("utf-8")) print( f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]" ) # 构建 Slack payload(使用简单的 text 字段,支持 mrkdwn) payload = {"text": mrkdwn_content} try: response = requests.post( webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30 ) # Slack Incoming Webhooks 成功时返回 "ok" 文本 if response.status_code == 200 and response.text == "ok": print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]") # 批次间间隔 if i < len(batches): time.sleep(batch_interval) else: error_msg = response.text if response.text else f"状态码:{response.status_code}" print( f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{error_msg}" ) return False except Exception as e: print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}") return False print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]") return True def send_to_generic_webhook( webhook_url: str, payload_template: Optional[str], report_data: Dict, report_type: str, update_info: Optional[Dict] = None, proxy_url: Optional[str] = None, mode: str = "daily", account_label: str = "", *, batch_size: int = 4000, batch_interval: float = 1.0, split_content_func: Optional[Callable] = None, rss_items: Optional[list] = None, rss_new_items: Optional[list] = None, ai_analysis: Any = None, display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: if split_content_func is None: raise ValueError("split_content_func is required") headers = {"Content-Type": "application/json"} proxies = None if proxy_url: proxies = {"http": proxy_url, "https": proxy_url} # 日志前缀 log_prefix = f"通用Webhook{account_label}" if account_label else "通用Webhook" # 渲染 AI 分析内容(如果有) ai_content = None ai_stats = None if ai_analysis: # 通用 Webhook 使用 markdown 格式渲染 AI 分析 ai_content = _render_ai_analysis(ai_analysis, "wework") # 提取 AI 分析统计数据 if getattr(ai_analysis, "success", False): ai_stats = { "total_news": getattr(ai_analysis, "total_news", 0), "analyzed_news": getattr(ai_analysis, "analyzed_news", 0), "max_news_limit": getattr(ai_analysis, "max_news_limit", 0), "hotlist_count": getattr(ai_analysis, "hotlist_count", 0), "rss_count": getattr(ai_analysis, "rss_count", 0), } # 获取分批内容 # 使用 'wework' 作为 format_type 以获取 markdown 格式的通用输出 # 预留一定空间给模板外壳 template_overhead = 200 batches = split_content_func( report_data, "wework", update_info, max_bytes=batch_size - template_overhead, mode=mode, rss_items=rss_items, rss_new_items=rss_new_items, ai_content=ai_content, standalone_data=standalone_data, ai_stats=ai_stats, report_type=report_type, ) # 统一添加批次头部 batches = add_batch_headers(batches, "wework", batch_size) print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]") # 逐批发送 for i, batch_content in enumerate(batches, 1): content_size = len(batch_content.encode("utf-8")) print( f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]" ) try: # 构建 payload if payload_template: # 简单的字符串替换 # 注意:content 可能包含 JSON 特殊字符,需要先转义 json_content = json.dumps(batch_content)[1:-1] # 去掉首尾引号 json_title = json.dumps(report_type)[1:-1] payload_str = payload_template.replace("{content}", json_content).replace("{title}", json_title) # 尝试解析为 JSON 对象以验证有效性 try: payload = json.loads(payload_str) except json.JSONDecodeError as e: print(f"{log_prefix} JSON 模板解析失败: {e}") # 回退到默认格式 payload = {"title": report_type, "content": batch_content} else: # 默认格式 payload = {"title": report_type, "content": batch_content} response = requests.post( webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30 ) if response.status_code >= 200 and response.status_code < 300: print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]") if i < len(batches): time.sleep(batch_interval) else: print( f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}, 响应: {response.text}" ) return False except Exception as e: print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}") return False print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]") return True
--- +++ @@ -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: Any, channel: str) -> str: + """渲染 AI 分析内容为指定渠道格式""" if not ai_analysis: return "" @@ -77,6 +93,27 @@ display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: + """ + 发送到飞书(支持分批发送,支持热榜+RSS合并+独立展示区) + + Args: + webhook_url: 飞书 Webhook URL + report_data: 报告数据 + report_type: 报告类型 + update_info: 更新信息(可选) + proxy_url: 代理 URL(可选) + mode: 报告模式 (daily/current) + account_label: 账号标签(多账号时显示) + batch_size: 批次大小(字节) + batch_interval: 批次发送间隔(秒) + split_content_func: 内容分批函数 + get_time_func: 获取当前时间的函数 + rss_items: RSS 统计条目列表(可选,用于合并推送) + rss_new_items: RSS 新增条目列表(可选,用于新增区块) + + Returns: + bool: 发送是否成功 + """ headers = {"Content-Type": "application/json"} proxies = None if proxy_url: @@ -187,6 +224,26 @@ display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: + """ + 发送到钉钉(支持分批发送,支持热榜+RSS合并+独立展示区) + + Args: + webhook_url: 钉钉 Webhook URL + report_data: 报告数据 + report_type: 报告类型 + update_info: 更新信息(可选) + proxy_url: 代理 URL(可选) + mode: 报告模式 (daily/current) + account_label: 账号标签(多账号时显示) + batch_size: 批次大小(字节) + batch_interval: 批次发送间隔(秒) + split_content_func: 内容分批函数 + rss_items: RSS 统计条目列表(可选,用于合并推送) + rss_new_items: RSS 新增条目列表(可选,用于新增区块) + + Returns: + bool: 发送是否成功 + """ headers = {"Content-Type": "application/json"} proxies = None if proxy_url: @@ -296,6 +353,27 @@ display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: + """ + 发送到企业微信(支持分批发送,支持 markdown 和 text 两种格式,支持热榜+RSS合并+独立展示区) + + Args: + webhook_url: 企业微信 Webhook URL + report_data: 报告数据 + report_type: 报告类型 + update_info: 更新信息(可选) + proxy_url: 代理 URL(可选) + mode: 报告模式 (daily/current) + account_label: 账号标签(多账号时显示) + batch_size: 批次大小(字节) + batch_interval: 批次发送间隔(秒) + msg_type: 消息类型 (markdown/text) + split_content_func: 内容分批函数 + rss_items: RSS 统计条目列表(可选,用于合并推送) + rss_new_items: RSS 新增条目列表(可选,用于新增区块) + + Returns: + bool: 发送是否成功 + """ headers = {"Content-Type": "application/json"} proxies = None if proxy_url: @@ -414,6 +492,27 @@ display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: + """ + 发送到 Telegram(支持分批发送,支持热榜+RSS合并+独立展示区) + + Args: + bot_token: Telegram Bot Token + chat_id: Telegram Chat ID + report_data: 报告数据 + report_type: 报告类型 + update_info: 更新信息(可选) + proxy_url: 代理 URL(可选) + mode: 报告模式 (daily/current) + account_label: 账号标签(多账号时显示) + batch_size: 批次大小(字节) + batch_interval: 批次发送间隔(秒) + split_content_func: 内容分批函数 + rss_items: RSS 统计条目列表(可选,用于合并推送) + rss_new_items: RSS 新增条目列表(可选,用于新增区块) + + Returns: + bool: 发送是否成功 + """ headers = {"Content-Type": "application/json"} url = f"https://api.telegram.org/bot{bot_token}/sendMessage" @@ -512,6 +611,25 @@ *, get_time_func: Callable = None, ) -> bool: + """ + 发送邮件通知 + + Args: + from_email: 发件人邮箱 + password: 邮箱密码/授权码 + to_email: 收件人邮箱(多个用逗号分隔) + report_type: 报告类型 + html_file_path: HTML 报告文件路径 + custom_smtp_server: 自定义 SMTP 服务器(可选) + custom_smtp_port: 自定义 SMTP 端口(可选) + get_time_func: 获取当前时间的函数 + + Returns: + bool: 发送是否成功 + + Note: + AI 分析内容已在 HTML 生成时嵌入,无需再追加 + """ try: if not html_file_path or not Path(html_file_path).exists(): print(f"错误:HTML文件不存在或未提供: {html_file_path}") @@ -660,6 +778,27 @@ display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: + """ + 发送到 ntfy(支持分批发送,严格遵守4KB限制,支持热榜+RSS合并+独立展示区) + + Args: + server_url: ntfy 服务器 URL + topic: ntfy 主题 + token: ntfy 访问令牌(可选) + report_data: 报告数据 + report_type: 报告类型 + update_info: 更新信息(可选) + proxy_url: 代理 URL(可选) + mode: 报告模式 (daily/current) + account_label: 账号标签(多账号时显示) + batch_size: 批次大小(字节) + split_content_func: 内容分批函数 + rss_items: RSS 统计条目列表(可选,用于合并推送) + rss_new_items: RSS 新增条目列表(可选,用于新增区块) + + Returns: + bool: 发送是否成功 + """ # 日志前缀 log_prefix = f"ntfy{account_label}" if account_label else "ntfy" @@ -841,6 +980,26 @@ display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: + """ + 发送到 Bark(支持分批发送,使用 markdown 格式,支持热榜+RSS合并+独立展示区) + + Args: + bark_url: Bark URL(包含 device_key) + report_data: 报告数据 + report_type: 报告类型 + update_info: 更新信息(可选) + proxy_url: 代理 URL(可选) + mode: 报告模式 (daily/current) + account_label: 账号标签(多账号时显示) + batch_size: 批次大小(字节) + batch_interval: 批次发送间隔(秒) + split_content_func: 内容分批函数 + rss_items: RSS 统计条目列表(可选,用于合并推送) + rss_new_items: RSS 新增条目列表(可选,用于新增区块) + + Returns: + bool: 发送是否成功 + """ # 日志前缀 log_prefix = f"Bark{account_label}" if account_label else "Bark" @@ -995,6 +1154,26 @@ display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: + """ + 发送到 Slack(支持分批发送,使用 mrkdwn 格式,支持热榜+RSS合并+独立展示区) + + Args: + webhook_url: Slack Webhook URL + report_data: 报告数据 + report_type: 报告类型 + update_info: 更新信息(可选) + proxy_url: 代理 URL(可选) + mode: 报告模式 (daily/current) + account_label: 账号标签(多账号时显示) + batch_size: 批次大小(字节) + batch_interval: 批次发送间隔(秒) + split_content_func: 内容分批函数 + rss_items: RSS 统计条目列表(可选,用于合并推送) + rss_new_items: RSS 新增条目列表(可选,用于新增区块) + + Returns: + bool: 发送是否成功 + """ headers = {"Content-Type": "application/json"} proxies = None if proxy_url: @@ -1094,6 +1273,27 @@ display_regions: Optional[Dict] = None, standalone_data: Optional[Dict] = None, ) -> bool: + """ + 发送到通用 Webhook(支持分批发送,支持自定义 JSON 模板,支持热榜+RSS合并+独立展示区) + + Args: + webhook_url: Webhook URL + payload_template: JSON 模板字符串,支持 {title} 和 {content} 占位符 + report_data: 报告数据 + report_type: 报告类型 + update_info: 更新信息(可选) + proxy_url: 代理 URL(可选) + mode: 报告模式 (daily/current) + account_label: 账号标签(多账号时显示) + batch_size: 批次大小(字节) + batch_interval: 批次发送间隔(秒) + split_content_func: 内容分批函数 + rss_items: RSS 统计条目列表(可选,用于合并推送) + rss_new_items: RSS 新增条目列表(可选,用于新增区块) + + Returns: + bool: 发送是否成功 + """ if split_content_func is None: raise ValueError("split_content_func is required") @@ -1187,4 +1387,4 @@ print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]") - return True+ return True
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, matches_word_groups_func: Optional[Callable] = None, load_frequency_words_func: Optional[Callable] = None, show_new_section: bool = True, ) -> Dict: processed_new_titles = [] # 在增量模式下或配置关闭时隐藏新增新闻区域 hide_new_section = mode == "incremental" or not show_new_section # 只有在非隐藏模式下才处理新增新闻部分 if not hide_new_section: filtered_new_titles = {} if new_titles and id_to_name: # 如果提供了匹配函数,使用它过滤 if matches_word_groups_func and load_frequency_words_func: word_groups, filter_words, global_filters = load_frequency_words_func() for source_id, titles_data in new_titles.items(): filtered_titles = {} for title, title_data in titles_data.items(): if matches_word_groups_func(title, word_groups, filter_words, global_filters): filtered_titles[title] = title_data if filtered_titles: filtered_new_titles[source_id] = filtered_titles else: # 没有匹配函数时,使用全部 filtered_new_titles = new_titles # 打印过滤后的新增热点数(与推送显示一致) original_new_count = sum(len(titles) for titles in new_titles.values()) if new_titles else 0 filtered_new_count = sum(len(titles) for titles in filtered_new_titles.values()) if filtered_new_titles else 0 if original_new_count > 0: print(f"频率词过滤后:{filtered_new_count} 条新增热点匹配(原始 {original_new_count} 条)") if filtered_new_titles and id_to_name: for source_id, titles_data in filtered_new_titles.items(): source_name = id_to_name.get(source_id, source_id) source_titles = [] for title, title_data in titles_data.items(): url = title_data.get("url", "") mobile_url = title_data.get("mobileUrl", "") ranks = title_data.get("ranks", []) processed_title = { "title": title, "source_name": source_name, "time_display": "", "count": 1, "ranks": ranks, "rank_threshold": rank_threshold, "url": url, "mobile_url": mobile_url, "is_new": True, } source_titles.append(processed_title) if source_titles: processed_new_titles.append( { "source_id": source_id, "source_name": source_name, "titles": source_titles, } ) processed_stats = [] for stat in stats: if stat["count"] <= 0: continue processed_titles = [] for title_data in stat["titles"]: processed_title = { "title": title_data["title"], "source_name": title_data["source_name"], "time_display": title_data["time_display"], "count": title_data["count"], "ranks": title_data["ranks"], "rank_threshold": title_data["rank_threshold"], "url": title_data.get("url", ""), "mobile_url": title_data.get("mobileUrl", ""), "is_new": title_data.get("is_new", False), } processed_titles.append(processed_title) processed_stats.append( { "word": stat["word"], "count": stat["count"], "percentage": stat.get("percentage", 0), "titles": processed_titles, } ) return { "stats": processed_stats, "new_titles": processed_new_titles, "failed_ids": failed_ids or [], "total_new_count": sum( len(source["titles"]) for source in processed_new_titles ), } def generate_html_report( stats: List[Dict], total_titles: int, failed_ids: Optional[List] = None, new_titles: Optional[Dict] = None, id_to_name: Optional[Dict] = None, mode: str = "daily", update_info: Optional[Dict] = None, rank_threshold: int = 3, output_dir: str = "output", date_folder: str = "", time_filename: str = "", render_html_func: Optional[Callable] = None, matches_word_groups_func: Optional[Callable] = None, load_frequency_words_func: Optional[Callable] = None, ) -> str: # 时间戳快照文件名 snapshot_filename = f"{time_filename}.html" # 构建输出路径(扁平化结构:output/html/日期/) snapshot_path = Path(output_dir) / "html" / date_folder snapshot_path.mkdir(parents=True, exist_ok=True) snapshot_file = str(snapshot_path / snapshot_filename) # 准备报告数据 report_data = prepare_report_data( stats, failed_ids, new_titles, id_to_name, mode, rank_threshold, matches_word_groups_func, load_frequency_words_func, ) # 渲染 HTML 内容 if render_html_func: html_content = render_html_func( report_data, total_titles, mode, update_info ) else: # 默认简单 HTML html_content = f"<html><body><h1>Report</h1><pre>{report_data}</pre></body></html>" # 1. 保存时间戳快照(历史记录) with open(snapshot_file, "w", encoding="utf-8") as f: f.write(html_content) # 2. 复制到 html/latest/{mode}.html(最新报告) latest_dir = Path(output_dir) / "html" / "latest" latest_dir.mkdir(parents=True, exist_ok=True) latest_file = latest_dir / f"{mode}.html" with open(latest_file, "w", encoding="utf-8") as f: f.write(html_content) # 3. 复制到 index.html(入口) # output/index.html(供 Docker Volume 挂载访问) output_index = Path(output_dir) / "index.html" with open(output_index, "w", encoding="utf-8") as f: f.write(html_content) # 根目录 index.html(供 GitHub Pages 访问) root_index = Path("index.html") with open(root_index, "w", encoding="utf-8") as f: f.write(html_content) return snapshot_file
--- +++ @@ -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_section: bool = True, ) -> Dict: + """ + 准备报告数据 + + Args: + stats: 统计结果列表 + failed_ids: 失败的 ID 列表 + new_titles: 新增标题 + id_to_name: ID 到名称的映射 + mode: 报告模式 (daily/incremental/current) + rank_threshold: 排名阈值 + matches_word_groups_func: 词组匹配函数 + load_frequency_words_func: 加载频率词函数 + show_new_section: 是否显示新增热点区域 + + Returns: + Dict: 准备好的报告数据 + """ processed_new_titles = [] # 在增量模式下或配置关闭时隐藏新增新闻区域 @@ -131,6 +155,33 @@ matches_word_groups_func: Optional[Callable] = None, load_frequency_words_func: Optional[Callable] = None, ) -> str: + """ + 生成 HTML 报告 + + 每次生成 HTML 后会: + 1. 保存时间戳快照到 output/html/日期/时间.html(历史记录) + 2. 复制到 output/html/latest/{mode}.html(最新报告) + 3. 复制到 output/index.html 和根目录 index.html(入口) + + Args: + stats: 统计结果列表 + total_titles: 总标题数 + failed_ids: 失败的 ID 列表 + new_titles: 新增标题 + id_to_name: ID 到名称的映射 + mode: 报告模式 (daily/incremental/current) + update_info: 更新信息 + rank_threshold: 排名阈值 + output_dir: 输出目录 + date_folder: 日期文件夹名称 + time_filename: 时间文件名 + render_html_func: HTML 渲染函数 + matches_word_groups_func: 词组匹配函数 + load_frequency_words_func: 加载频率词函数 + + Returns: + str: 生成的 HTML 文件路径(时间戳快照路径) + """ # 时间戳快照文件名 snapshot_filename = f"{time_filename}.html" @@ -182,4 +233,4 @@ with open(root_index, "w", encoding="utf-8") as f: f.write(html_content) - return snapshot_file+ return snapshot_file
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() return cleaned_title def html_escape(text: str) -> str: if not isinstance(text, str): text = str(text) return ( text.replace("&", "&amp;") .replace("<", "&lt;") .replace(">", "&gt;") .replace('"', "&quot;") .replace("'", "&#x27;") ) def format_rank_display(ranks: List[int], rank_threshold: int, format_type: str) -> str: if not ranks: return "" unique_ranks = sorted(set(ranks)) min_rank = unique_ranks[0] max_rank = unique_ranks[-1] # 根据平台类型选择高亮格式 if format_type == "html": highlight_start = "<font color='red'><strong>" highlight_end = "</strong></font>" elif format_type == "feishu": highlight_start = "<font color='red'>**" highlight_end = "**</font>" elif format_type == "dingtalk": highlight_start = "**" highlight_end = "**" elif format_type == "wework": highlight_start = "**" highlight_end = "**" elif format_type == "telegram": highlight_start = "<b>" highlight_end = "</b>" elif format_type == "slack": highlight_start = "*" highlight_end = "*" else: # 默认 markdown 格式 highlight_start = "**" highlight_end = "**" # 生成排名显示 rank_str = "" if min_rank <= rank_threshold: if min_rank == max_rank: rank_str = f"{highlight_start}[{min_rank}]{highlight_end}" else: rank_str = f"{highlight_start}[{min_rank} - {max_rank}]{highlight_end}" else: if min_rank == max_rank: rank_str = f"[{min_rank}]" else: rank_str = f"[{min_rank} - {max_rank}]" # 计算热度趋势 trend_arrow = "" if len(ranks) >= 2: prev_rank = ranks[-2] curr_rank = ranks[-1] if curr_rank < prev_rank: trend_arrow = "🔺" # 排名上升(数值变小) elif curr_rank > prev_rank: trend_arrow = "🔻" # 排名下降(数值变大) else: trend_arrow = "➖" # 排名持平 # len(ranks) == 1 时不显示趋势箭头(新上榜由 is_new 字段在 formatter.py 中处理) return f"{rank_str} {trend_arrow}" if trend_arrow else rank_str
--- +++ @@ -1,10 +1,28 @@ # coding=utf-8 +""" +报告辅助函数模块 + +提供报告生成相关的通用辅助函数 +""" import re from typing import List def clean_title(title: str) -> str: + """清理标题中的特殊字符 + + 清理规则: + - 将换行符(\n, \r)替换为空格 + - 将多个连续空白字符合并为单个空格 + - 去除首尾空白 + + Args: + title: 原始标题字符串 + + Returns: + 清理后的标题字符串 + """ if not isinstance(title, str): title = str(title) cleaned_title = title.replace("\n", " ").replace("\r", " ") @@ -14,6 +32,21 @@ def html_escape(text: str) -> str: + """HTML特殊字符转义 + + 转义规则(按顺序): + - & → &amp; + - < → &lt; + - > → &gt; + - " → &quot; + - ' → &#x27; + + Args: + text: 原始文本 + + Returns: + 转义后的文本 + """ if not isinstance(text, str): text = str(text) @@ -27,6 +60,27 @@ def format_rank_display(ranks: List[int], rank_threshold: int, format_type: str) -> str: + """格式化排名显示 + + 根据不同平台类型生成对应格式的排名字符串。 + 当最小排名小于等于阈值时,使用高亮格式。 + + Args: + ranks: 排名列表(可能包含重复值) + rank_threshold: 高亮阈值,小于等于此值的排名会高亮显示 + format_type: 平台类型,支持: + - "html": HTML格式 + - "feishu": 飞书格式 + - "dingtalk": 钉钉格式 + - "wework": 企业微信格式 + - "telegram": Telegram格式 + - "slack": Slack格式 + - 其他: 默认markdown格式 + + Returns: + 格式化后的排名字符串,如 "[1]" 或 "[1 - 5]" + 如果排名列表为空,返回空字符串 + """ if not ranks: return "" @@ -84,4 +138,4 @@ trend_arrow = "➖" # 排名持平 # len(ranks) == 1 时不显示趋势箭头(新上榜由 is_new 字段在 formatter.py 中处理) - return f"{rank_str} {trend_arrow}" if trend_arrow else rank_str+ return f"{rank_str} {trend_arrow}" if trend_arrow else rank_str
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_display # 默认批次大小配置 DEFAULT_BATCH_SIZES = { "dingtalk": 20000, "feishu": 29000, "ntfy": 3800, "default": 4000, } # 默认区域顺序 DEFAULT_REGION_ORDER = ["hotlist", "rss", "new_items", "standalone", "ai_analysis"] def split_content_into_batches( report_data: Dict, format_type: str, update_info: Optional[Dict] = None, max_bytes: Optional[int] = None, mode: str = "daily", batch_sizes: Optional[Dict[str, int]] = None, feishu_separator: str = "---", region_order: Optional[List[str]] = None, get_time_func: Optional[Callable[[], datetime]] = None, rss_items: Optional[list] = None, rss_new_items: Optional[list] = None, timezone: str = DEFAULT_TIMEZONE, display_mode: str = "keyword", ai_content: Optional[str] = None, standalone_data: Optional[Dict] = None, rank_threshold: int = 10, ai_stats: Optional[Dict] = None, report_type: str = "热点分析报告", show_new_section: bool = True, ) -> List[str]: if region_order is None: region_order = DEFAULT_REGION_ORDER # 合并批次大小配置 sizes = {**DEFAULT_BATCH_SIZES, **(batch_sizes or {})} if max_bytes is None: if format_type == "dingtalk": max_bytes = sizes.get("dingtalk", 20000) elif format_type == "feishu": max_bytes = sizes.get("feishu", 29000) elif format_type == "ntfy": max_bytes = sizes.get("ntfy", 3800) else: max_bytes = sizes.get("default", 4000) batches = [] total_hotlist_count = sum( len(stat["titles"]) for stat in report_data["stats"] if stat["count"] > 0 ) total_titles = total_hotlist_count # 累加 RSS 条目数 if rss_items: total_titles += sum(stat.get("count", 0) for stat in rss_items) now = get_time_func() if get_time_func else datetime.now() # 构建头部信息 base_header = "" # 准备 AI 分析统计行(如果存在) ai_stats_line = "" if ai_stats and ai_stats.get("analyzed_news", 0) > 0: analyzed_news = ai_stats.get("analyzed_news", 0) total_news = ai_stats.get("total_news", 0) ai_mode = ai_stats.get("ai_mode", "") # 构建分析数显示:如果被截断则显示 "实际分析数/总可分析数" if total_news > analyzed_news: news_display = f"{analyzed_news}/{total_news}" else: news_display = str(analyzed_news) # 如果 AI 模式与推送模式不同,显示模式标识 mode_suffix = "" if ai_mode and ai_mode != mode: mode_map = { "daily": "全天汇总", "current": "当前榜单", "incremental": "增量分析" } mode_label = mode_map.get(ai_mode, ai_mode) mode_suffix = f" ({mode_label})" if format_type in ("wework", "bark", "ntfy", "feishu", "dingtalk"): ai_stats_line = f"**AI 分析数:** {news_display}{mode_suffix}\n" elif format_type == "slack": ai_stats_line = f"*AI 分析数:* {news_display}{mode_suffix}\n" elif format_type == "telegram": ai_stats_line = f"AI 分析数: {news_display}{mode_suffix}\n" # 构建统一的头部(总是显示总新闻数、时间和类型) if format_type in ("wework", "bark"): base_header = f"**总新闻数:** {total_titles}\n" base_header += ai_stats_line base_header += f"**时间:** {now.strftime('%Y-%m-%d %H:%M:%S')}\n" base_header += f"**类型:** {report_type}\n\n" elif format_type == "telegram": base_header = f"总新闻数: {total_titles}\n" base_header += ai_stats_line base_header += f"时间: {now.strftime('%Y-%m-%d %H:%M:%S')}\n" base_header += f"类型: {report_type}\n\n" elif format_type == "ntfy": base_header = f"**总新闻数:** {total_titles}\n" base_header += ai_stats_line base_header += f"**时间:** {now.strftime('%Y-%m-%d %H:%M:%S')}\n" base_header += f"**类型:** {report_type}\n\n" elif format_type == "feishu": base_header = f"**总新闻数:** {total_titles}\n" base_header += ai_stats_line base_header += f"**时间:** {now.strftime('%Y-%m-%d %H:%M:%S')}\n" base_header += f"**类型:** {report_type}\n\n" base_header += "---\n\n" elif format_type == "dingtalk": base_header = f"**总新闻数:** {total_titles}\n" base_header += ai_stats_line base_header += f"**时间:** {now.strftime('%Y-%m-%d %H:%M:%S')}\n" base_header += f"**类型:** {report_type}\n\n" base_header += "---\n\n" elif format_type == "slack": base_header = f"*总新闻数:* {total_titles}\n" base_header += ai_stats_line base_header += f"*时间:* {now.strftime('%Y-%m-%d %H:%M:%S')}\n" base_header += f"*类型:* {report_type}\n\n" base_footer = "" if format_type in ("wework", "bark"): base_footer = f"\n\n\n> 更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}" if update_info: base_footer += f"\n> TrendRadar 发现新版本 **{update_info['remote_version']}**,当前 **{update_info['current_version']}**" elif format_type == "telegram": base_footer = f"\n\n更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}" if update_info: base_footer += f"\nTrendRadar 发现新版本 {update_info['remote_version']},当前 {update_info['current_version']}" elif format_type == "ntfy": base_footer = f"\n\n> 更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}" if update_info: base_footer += f"\n> TrendRadar 发现新版本 **{update_info['remote_version']}**,当前 **{update_info['current_version']}**" elif format_type == "feishu": base_footer = f"\n\n<font color='grey'>更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}</font>" if update_info: base_footer += f"\n<font color='grey'>TrendRadar 发现新版本 {update_info['remote_version']},当前 {update_info['current_version']}</font>" elif format_type == "dingtalk": base_footer = f"\n\n> 更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}" if update_info: base_footer += f"\n> TrendRadar 发现新版本 **{update_info['remote_version']}**,当前 **{update_info['current_version']}**" elif format_type == "slack": base_footer = f"\n\n_更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}_" if update_info: base_footer += f"\n_TrendRadar 发现新版本 *{update_info['remote_version']}*,当前 *{update_info['current_version']}_" # 根据 display_mode 选择统计标题 stats_title = "热点词汇统计" if display_mode == "keyword" else "热点新闻统计" stats_header = "" if report_data["stats"]: if format_type in ("wework", "bark"): stats_header = f"📊 **{stats_title}** (共 {total_hotlist_count} 条)\n\n" elif format_type == "telegram": stats_header = f"📊 {stats_title} (共 {total_hotlist_count} 条)\n\n" elif format_type == "ntfy": stats_header = f"📊 **{stats_title}** (共 {total_hotlist_count} 条)\n\n" elif format_type == "feishu": stats_header = f"📊 **{stats_title}** (共 {total_hotlist_count} 条)\n\n" elif format_type == "dingtalk": stats_header = f"📊 **{stats_title}** (共 {total_hotlist_count} 条)\n\n" elif format_type == "slack": stats_header = f"📊 *{stats_title}* (共 {total_hotlist_count} 条)\n\n" current_batch = base_header current_batch_has_content = False # 当没有热榜数据时的处理 # 注意:如果有 ai_content,不应该返回"暂无匹配"消息,而应该继续处理 AI 内容 if ( not report_data["stats"] and not report_data["new_titles"] and not report_data["failed_ids"] and not ai_content # 有 AI 内容时不返回"暂无匹配" and not rss_items # 有 RSS 内容时也不返回 and not standalone_data # 有独立展示区数据时也不返回 ): if mode == "incremental": mode_text = "增量模式下暂无新增匹配的热点词汇" elif mode == "current": mode_text = "当前榜单模式下暂无匹配的热点词汇" else: mode_text = "暂无匹配的热点词汇" simple_content = f"📭 {mode_text}\n\n" final_content = base_header + simple_content + base_footer batches.append(final_content) return batches # 定义处理热点词汇统计的函数 def process_stats_section(current_batch, current_batch_has_content, batches, add_separator=True): if not report_data["stats"]: return current_batch, current_batch_has_content, batches total_count = len(report_data["stats"]) # 根据 add_separator 决定是否添加前置分割线 actual_stats_header = "" if add_separator and current_batch_has_content: # 需要添加分割线 if format_type == "feishu": actual_stats_header = f"\n{feishu_separator}\n\n{stats_header}" elif format_type == "dingtalk": actual_stats_header = f"\n---\n\n{stats_header}" elif format_type in ("wework", "bark"): actual_stats_header = f"\n\n\n\n{stats_header}" else: actual_stats_header = f"\n\n{stats_header}" else: # 不需要分割线(第一个区域) actual_stats_header = stats_header # 添加统计标题 test_content = current_batch + actual_stats_header if ( len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) < max_bytes ): current_batch = test_content current_batch_has_content = True else: if current_batch_has_content: batches.append(current_batch + base_footer) # 新批次开头不需要分割线,使用原始 stats_header current_batch = base_header + stats_header current_batch_has_content = True # 逐个处理词组(确保词组标题+第一条新闻的原子性) for i, stat in enumerate(report_data["stats"]): word = stat["word"] count = stat["count"] sequence_display = f"[{i + 1}/{total_count}]" # 构建词组标题 word_header = "" if format_type in ("wework", "bark"): if count >= 10: word_header = ( f"🔥 {sequence_display} **{word}** : **{count}** 条\n\n" ) elif count >= 5: word_header = ( f"📈 {sequence_display} **{word}** : **{count}** 条\n\n" ) else: word_header = f"📌 {sequence_display} **{word}** : {count} 条\n\n" elif format_type == "telegram": if count >= 10: word_header = f"🔥 {sequence_display} {word} : {count} 条\n\n" elif count >= 5: word_header = f"📈 {sequence_display} {word} : {count} 条\n\n" else: word_header = f"📌 {sequence_display} {word} : {count} 条\n\n" elif format_type == "ntfy": if count >= 10: word_header = ( f"🔥 {sequence_display} **{word}** : **{count}** 条\n\n" ) elif count >= 5: word_header = ( f"📈 {sequence_display} **{word}** : **{count}** 条\n\n" ) else: word_header = f"📌 {sequence_display} **{word}** : {count} 条\n\n" elif format_type == "feishu": if count >= 10: word_header = f"🔥 <font color='grey'>{sequence_display}</font> **{word}** : <font color='red'>{count}</font> 条\n\n" elif count >= 5: word_header = f"📈 <font color='grey'>{sequence_display}</font> **{word}** : <font color='orange'>{count}</font> 条\n\n" else: word_header = f"📌 <font color='grey'>{sequence_display}</font> **{word}** : {count} 条\n\n" elif format_type == "dingtalk": if count >= 10: word_header = ( f"🔥 {sequence_display} **{word}** : **{count}** 条\n\n" ) elif count >= 5: word_header = ( f"📈 {sequence_display} **{word}** : **{count}** 条\n\n" ) else: word_header = f"📌 {sequence_display} **{word}** : {count} 条\n\n" elif format_type == "slack": if count >= 10: word_header = ( f"🔥 {sequence_display} *{word}* : *{count}* 条\n\n" ) elif count >= 5: word_header = ( f"📈 {sequence_display} *{word}* : *{count}* 条\n\n" ) else: word_header = f"📌 {sequence_display} *{word}* : {count} 条\n\n" # 构建第一条新闻 # display_mode: keyword=显示来源, platform=显示关键词 show_source = display_mode == "keyword" show_keyword = display_mode == "platform" first_news_line = "" if stat["titles"]: first_title_data = stat["titles"][0] if format_type in ("wework", "bark"): formatted_title = format_title_for_platform( "wework", first_title_data, show_source=show_source, show_keyword=show_keyword ) elif format_type == "telegram": formatted_title = format_title_for_platform( "telegram", first_title_data, show_source=show_source, show_keyword=show_keyword ) elif format_type == "ntfy": formatted_title = format_title_for_platform( "ntfy", first_title_data, show_source=show_source, show_keyword=show_keyword ) elif format_type == "feishu": formatted_title = format_title_for_platform( "feishu", first_title_data, show_source=show_source, show_keyword=show_keyword ) elif format_type == "dingtalk": formatted_title = format_title_for_platform( "dingtalk", first_title_data, show_source=show_source, show_keyword=show_keyword ) elif format_type == "slack": formatted_title = format_title_for_platform( "slack", first_title_data, show_source=show_source, show_keyword=show_keyword ) else: formatted_title = f"{first_title_data['title']}" first_news_line = f" 1. {formatted_title}\n" if len(stat["titles"]) > 1: first_news_line += "\n" # 原子性检查:词组标题+第一条新闻必须一起处理 word_with_first_news = word_header + first_news_line test_content = current_batch + word_with_first_news if ( len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) >= max_bytes ): # 当前批次容纳不下,开启新批次 if current_batch_has_content: batches.append(current_batch + base_footer) current_batch = base_header + stats_header + word_with_first_news current_batch_has_content = True start_index = 1 else: current_batch = test_content current_batch_has_content = True start_index = 1 # 处理剩余新闻条目 for j in range(start_index, len(stat["titles"])): title_data = stat["titles"][j] if format_type in ("wework", "bark"): formatted_title = format_title_for_platform( "wework", title_data, show_source=show_source, show_keyword=show_keyword ) elif format_type == "telegram": formatted_title = format_title_for_platform( "telegram", title_data, show_source=show_source, show_keyword=show_keyword ) elif format_type == "ntfy": formatted_title = format_title_for_platform( "ntfy", title_data, show_source=show_source, show_keyword=show_keyword ) elif format_type == "feishu": formatted_title = format_title_for_platform( "feishu", title_data, show_source=show_source, show_keyword=show_keyword ) elif format_type == "dingtalk": formatted_title = format_title_for_platform( "dingtalk", title_data, show_source=show_source, show_keyword=show_keyword ) elif format_type == "slack": formatted_title = format_title_for_platform( "slack", title_data, show_source=show_source, show_keyword=show_keyword ) else: formatted_title = f"{title_data['title']}" news_line = f" {j + 1}. {formatted_title}\n" if j < len(stat["titles"]) - 1: news_line += "\n" test_content = current_batch + news_line if ( len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) >= max_bytes ): if current_batch_has_content: batches.append(current_batch + base_footer) current_batch = base_header + stats_header + word_header + news_line current_batch_has_content = True else: current_batch = test_content current_batch_has_content = True # 词组间分隔符 if i < len(report_data["stats"]) - 1: separator = "" if format_type in ("wework", "bark"): separator = f"\n\n\n\n" elif format_type == "telegram": separator = f"\n\n" elif format_type == "ntfy": separator = f"\n\n" elif format_type == "feishu": separator = f"\n{feishu_separator}\n\n" elif format_type == "dingtalk": separator = f"\n---\n\n" elif format_type == "slack": separator = f"\n\n" test_content = current_batch + separator if ( len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) < max_bytes ): current_batch = test_content return current_batch, current_batch_has_content, batches # 定义处理新增新闻的函数 def process_new_titles_section(current_batch, current_batch_has_content, batches, add_separator=True): if not show_new_section or not report_data["new_titles"]: return current_batch, current_batch_has_content, batches # 根据 add_separator 决定是否添加前置分割线 new_header = "" if add_separator and current_batch_has_content: # 需要添加分割线 if format_type in ("wework", "bark"): new_header = f"\n\n\n\n🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n" elif format_type == "telegram": new_header = ( f"\n\n🆕 本次新增热点新闻 (共 {report_data['total_new_count']} 条)\n\n" ) elif format_type == "ntfy": new_header = f"\n\n🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n" elif format_type == "feishu": new_header = f"\n{feishu_separator}\n\n🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n" elif format_type == "dingtalk": new_header = f"\n---\n\n🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n" elif format_type == "slack": new_header = f"\n\n🆕 *本次新增热点新闻* (共 {report_data['total_new_count']} 条)\n\n" else: # 不需要分割线(第一个区域) if format_type in ("wework", "bark"): new_header = f"🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n" elif format_type == "telegram": new_header = f"🆕 本次新增热点新闻 (共 {report_data['total_new_count']} 条)\n\n" elif format_type == "ntfy": new_header = f"🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n" elif format_type == "feishu": new_header = f"🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n" elif format_type == "dingtalk": new_header = f"🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n" elif format_type == "slack": new_header = f"🆕 *本次新增热点新闻* (共 {report_data['total_new_count']} 条)\n\n" test_content = current_batch + new_header if ( len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) >= max_bytes ): if current_batch_has_content: batches.append(current_batch + base_footer) current_batch = base_header + new_header current_batch_has_content = True else: current_batch = test_content current_batch_has_content = True # 逐个处理新增新闻来源 for source_data in report_data["new_titles"]: source_header = "" if format_type in ("wework", "bark"): source_header = f"**{source_data['source_name']}** ({len(source_data['titles'])} 条):\n\n" elif format_type == "telegram": source_header = f"{source_data['source_name']} ({len(source_data['titles'])} 条):\n\n" elif format_type == "ntfy": source_header = f"**{source_data['source_name']}** ({len(source_data['titles'])} 条):\n\n" elif format_type == "feishu": source_header = f"**{source_data['source_name']}** ({len(source_data['titles'])} 条):\n\n" elif format_type == "dingtalk": source_header = f"**{source_data['source_name']}** ({len(source_data['titles'])} 条):\n\n" elif format_type == "slack": source_header = f"*{source_data['source_name']}* ({len(source_data['titles'])} 条):\n\n" # 构建第一条新增新闻 first_news_line = "" if source_data["titles"]: first_title_data = source_data["titles"][0] title_data_copy = first_title_data.copy() title_data_copy["is_new"] = False if format_type in ("wework", "bark"): formatted_title = format_title_for_platform( "wework", title_data_copy, show_source=False ) elif format_type == "telegram": formatted_title = format_title_for_platform( "telegram", title_data_copy, show_source=False ) elif format_type == "feishu": formatted_title = format_title_for_platform( "feishu", title_data_copy, show_source=False ) elif format_type == "dingtalk": formatted_title = format_title_for_platform( "dingtalk", title_data_copy, show_source=False ) elif format_type == "slack": formatted_title = format_title_for_platform( "slack", title_data_copy, show_source=False ) else: formatted_title = f"{title_data_copy['title']}" first_news_line = f" 1. {formatted_title}\n" # 原子性检查:来源标题+第一条新闻 source_with_first_news = source_header + first_news_line test_content = current_batch + source_with_first_news if ( len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) >= max_bytes ): if current_batch_has_content: batches.append(current_batch + base_footer) current_batch = base_header + new_header + source_with_first_news current_batch_has_content = True start_index = 1 else: current_batch = test_content current_batch_has_content = True start_index = 1 # 处理剩余新增新闻 for j in range(start_index, len(source_data["titles"])): title_data = source_data["titles"][j] title_data_copy = title_data.copy() title_data_copy["is_new"] = False if format_type == "wework": formatted_title = format_title_for_platform( "wework", title_data_copy, show_source=False ) elif format_type == "telegram": formatted_title = format_title_for_platform( "telegram", title_data_copy, show_source=False ) elif format_type == "feishu": formatted_title = format_title_for_platform( "feishu", title_data_copy, show_source=False ) elif format_type == "dingtalk": formatted_title = format_title_for_platform( "dingtalk", title_data_copy, show_source=False ) elif format_type == "slack": formatted_title = format_title_for_platform( "slack", title_data_copy, show_source=False ) else: formatted_title = f"{title_data_copy['title']}" news_line = f" {j + 1}. {formatted_title}\n" test_content = current_batch + news_line if ( len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) >= max_bytes ): if current_batch_has_content: batches.append(current_batch + base_footer) current_batch = base_header + new_header + source_header + news_line current_batch_has_content = True else: current_batch = test_content current_batch_has_content = True current_batch += "\n" return current_batch, current_batch_has_content, batches # 定义处理 AI 分析的函数 def process_ai_section(current_batch, current_batch_has_content, batches, add_separator=True): nonlocal ai_content if not ai_content: return current_batch, current_batch_has_content, batches # 根据 add_separator 决定是否添加前置分割线 ai_separator = "" if add_separator and current_batch_has_content: # 需要添加分割线 if format_type == "feishu": ai_separator = f"\n{feishu_separator}\n\n" elif format_type == "dingtalk": ai_separator = "\n---\n\n" elif format_type in ("wework", "bark"): ai_separator = "\n\n\n\n" elif format_type in ("telegram", "ntfy", "slack"): ai_separator = "\n\n" # 如果不需要分割线,ai_separator 保持为空字符串 # 尝试将 AI 内容添加到当前批次 test_content = current_batch + ai_separator + ai_content if ( len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) < max_bytes ): current_batch = test_content current_batch_has_content = True else: # 当前批次容纳不下,开启新批次 if current_batch_has_content: batches.append(current_batch + base_footer) # AI 内容可能很长,需要考虑是否需要进一步分割 ai_with_header = base_header + ai_content current_batch = ai_with_header current_batch_has_content = True return current_batch, current_batch_has_content, batches # 定义处理独立展示区的函数 def process_standalone_section_wrapper(current_batch, current_batch_has_content, batches, add_separator=True): if not standalone_data: return current_batch, current_batch_has_content, batches return _process_standalone_section( standalone_data, format_type, feishu_separator, base_header, base_footer, max_bytes, current_batch, current_batch_has_content, batches, timezone, rank_threshold, add_separator ) # 定义处理 RSS 统计的函数 def process_rss_stats_wrapper(current_batch, current_batch_has_content, batches, add_separator=True): if not rss_items: return current_batch, current_batch_has_content, batches return _process_rss_stats_section( rss_items, format_type, feishu_separator, base_header, base_footer, max_bytes, current_batch, current_batch_has_content, batches, timezone, add_separator ) # 定义处理 RSS 新增的函数 def process_rss_new_wrapper(current_batch, current_batch_has_content, batches, add_separator=True): if not rss_new_items: return current_batch, current_batch_has_content, batches return _process_rss_new_titles_section( rss_new_items, format_type, feishu_separator, base_header, base_footer, max_bytes, current_batch, current_batch_has_content, batches, timezone, add_separator ) # 按 region_order 顺序处理各区域 # 记录是否已有区域内容(用于决定是否添加分割线) has_region_content = False for region in region_order: # 记录处理前的状态,用于判断该区域是否产生了内容 batch_before = current_batch has_content_before = current_batch_has_content batches_len_before = len(batches) # 决定是否需要添加分割线(第一个有内容的区域不需要) add_separator = has_region_content if region == "hotlist": # 处理热榜统计 current_batch, current_batch_has_content, batches = process_stats_section( current_batch, current_batch_has_content, batches, add_separator ) elif region == "rss": # 处理 RSS 统计 current_batch, current_batch_has_content, batches = process_rss_stats_wrapper( current_batch, current_batch_has_content, batches, add_separator ) elif region == "new_items": # 处理热榜新增 current_batch, current_batch_has_content, batches = process_new_titles_section( current_batch, current_batch_has_content, batches, add_separator ) # 处理 RSS 新增(跟随 new_items,继承 add_separator 逻辑) # 如果热榜新增产生了内容,RSS 新增需要分割线 new_batch_changed = ( current_batch != batch_before or current_batch_has_content != has_content_before or len(batches) != batches_len_before ) rss_new_separator = new_batch_changed or has_region_content current_batch, current_batch_has_content, batches = process_rss_new_wrapper( current_batch, current_batch_has_content, batches, rss_new_separator ) elif region == "standalone": # 处理独立展示区 current_batch, current_batch_has_content, batches = process_standalone_section_wrapper( current_batch, current_batch_has_content, batches, add_separator ) elif region == "ai_analysis": # 处理 AI 分析 current_batch, current_batch_has_content, batches = process_ai_section( current_batch, current_batch_has_content, batches, add_separator ) # 检查该区域是否产生了内容 region_produced_content = ( current_batch != batch_before or current_batch_has_content != has_content_before or len(batches) != batches_len_before ) if region_produced_content: has_region_content = True if report_data["failed_ids"]: failed_header = "" if format_type == "wework": failed_header = f"\n\n\n\n⚠️ **数据获取失败的平台:**\n\n" elif format_type == "telegram": failed_header = f"\n\n⚠️ 数据获取失败的平台:\n\n" elif format_type == "ntfy": failed_header = f"\n\n⚠️ **数据获取失败的平台:**\n\n" elif format_type == "feishu": failed_header = f"\n{feishu_separator}\n\n⚠️ **数据获取失败的平台:**\n\n" elif format_type == "dingtalk": failed_header = f"\n---\n\n⚠️ **数据获取失败的平台:**\n\n" test_content = current_batch + failed_header if ( len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) >= max_bytes ): if current_batch_has_content: batches.append(current_batch + base_footer) current_batch = base_header + failed_header current_batch_has_content = True else: current_batch = test_content current_batch_has_content = True for i, id_value in enumerate(report_data["failed_ids"], 1): if format_type == "feishu": failed_line = f" • <font color='red'>{id_value}</font>\n" elif format_type == "dingtalk": failed_line = f" • **{id_value}**\n" else: failed_line = f" • {id_value}\n" test_content = current_batch + failed_line if ( len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) >= max_bytes ): if current_batch_has_content: batches.append(current_batch + base_footer) current_batch = base_header + failed_header + failed_line current_batch_has_content = True else: current_batch = test_content current_batch_has_content = True # 完成最后批次 if current_batch_has_content: batches.append(current_batch + base_footer) return batches def _process_rss_stats_section( rss_stats: list, format_type: str, feishu_separator: str, base_header: str, base_footer: str, max_bytes: int, current_batch: str, current_batch_has_content: bool, batches: List[str], timezone: str = DEFAULT_TIMEZONE, add_separator: bool = True, ) -> tuple: if not rss_stats: return current_batch, current_batch_has_content, batches # 计算总条目数 total_items = sum(stat["count"] for stat in rss_stats) total_keywords = len(rss_stats) # RSS 统计区块标题(根据 add_separator 决定是否添加前置分割线) rss_header = "" if add_separator and current_batch_has_content: # 需要添加分割线 if format_type == "feishu": rss_header = f"\n{feishu_separator}\n\n📰 **RSS 订阅统计** (共 {total_items} 条)\n\n" elif format_type == "dingtalk": rss_header = f"\n---\n\n📰 **RSS 订阅统计** (共 {total_items} 条)\n\n" elif format_type in ("wework", "bark"): rss_header = f"\n\n\n\n📰 **RSS 订阅统计** (共 {total_items} 条)\n\n" elif format_type == "telegram": rss_header = f"\n\n📰 RSS 订阅统计 (共 {total_items} 条)\n\n" elif format_type == "slack": rss_header = f"\n\n📰 *RSS 订阅统计* (共 {total_items} 条)\n\n" else: rss_header = f"\n\n📰 **RSS 订阅统计** (共 {total_items} 条)\n\n" else: # 不需要分割线(第一个区域) if format_type == "feishu": rss_header = f"📰 **RSS 订阅统计** (共 {total_items} 条)\n\n" elif format_type == "dingtalk": rss_header = f"📰 **RSS 订阅统计** (共 {total_items} 条)\n\n" elif format_type == "telegram": rss_header = f"📰 RSS 订阅统计 (共 {total_items} 条)\n\n" elif format_type == "slack": rss_header = f"📰 *RSS 订阅统计* (共 {total_items} 条)\n\n" else: rss_header = f"📰 **RSS 订阅统计** (共 {total_items} 条)\n\n" # 添加 RSS 标题 test_content = current_batch + rss_header if len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) < max_bytes: current_batch = test_content current_batch_has_content = True else: if current_batch_has_content: batches.append(current_batch + base_footer) current_batch = base_header + rss_header current_batch_has_content = True # 逐个处理关键词组(与热榜一致) for i, stat in enumerate(rss_stats): word = stat["word"] count = stat["count"] sequence_display = f"[{i + 1}/{total_keywords}]" # 构建关键词标题(与热榜格式一致) word_header = "" if format_type in ("wework", "bark"): if count >= 10: word_header = f"🔥 {sequence_display} **{word}** : **{count}** 条\n\n" elif count >= 5: word_header = f"📈 {sequence_display} **{word}** : **{count}** 条\n\n" else: word_header = f"📌 {sequence_display} **{word}** : {count} 条\n\n" elif format_type == "telegram": if count >= 10: word_header = f"🔥 {sequence_display} {word} : {count} 条\n\n" elif count >= 5: word_header = f"📈 {sequence_display} {word} : {count} 条\n\n" else: word_header = f"📌 {sequence_display} {word} : {count} 条\n\n" elif format_type == "ntfy": if count >= 10: word_header = f"🔥 {sequence_display} **{word}** : **{count}** 条\n\n" elif count >= 5: word_header = f"📈 {sequence_display} **{word}** : **{count}** 条\n\n" else: word_header = f"📌 {sequence_display} **{word}** : {count} 条\n\n" elif format_type == "feishu": if count >= 10: word_header = f"🔥 <font color='grey'>{sequence_display}</font> **{word}** : <font color='red'>{count}</font> 条\n\n" elif count >= 5: word_header = f"📈 <font color='grey'>{sequence_display}</font> **{word}** : <font color='orange'>{count}</font> 条\n\n" else: word_header = f"📌 <font color='grey'>{sequence_display}</font> **{word}** : {count} 条\n\n" elif format_type == "dingtalk": if count >= 10: word_header = f"🔥 {sequence_display} **{word}** : **{count}** 条\n\n" elif count >= 5: word_header = f"📈 {sequence_display} **{word}** : **{count}** 条\n\n" else: word_header = f"📌 {sequence_display} **{word}** : {count} 条\n\n" elif format_type == "slack": if count >= 10: word_header = f"🔥 {sequence_display} *{word}* : *{count}* 条\n\n" elif count >= 5: word_header = f"📈 {sequence_display} *{word}* : *{count}* 条\n\n" else: word_header = f"📌 {sequence_display} *{word}* : {count} 条\n\n" # 构建第一条新闻(使用 format_title_for_platform) first_news_line = "" if stat["titles"]: first_title_data = stat["titles"][0] if format_type in ("wework", "bark"): formatted_title = format_title_for_platform("wework", first_title_data, show_source=True) elif format_type == "telegram": formatted_title = format_title_for_platform("telegram", first_title_data, show_source=True) elif format_type == "ntfy": formatted_title = format_title_for_platform("ntfy", first_title_data, show_source=True) elif format_type == "feishu": formatted_title = format_title_for_platform("feishu", first_title_data, show_source=True) elif format_type == "dingtalk": formatted_title = format_title_for_platform("dingtalk", first_title_data, show_source=True) elif format_type == "slack": formatted_title = format_title_for_platform("slack", first_title_data, show_source=True) else: formatted_title = f"{first_title_data['title']}" first_news_line = f" 1. {formatted_title}\n" if len(stat["titles"]) > 1: first_news_line += "\n" # 原子性检查:关键词标题 + 第一条新闻必须一起处理 word_with_first_news = word_header + first_news_line test_content = current_batch + word_with_first_news if len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) >= max_bytes: if current_batch_has_content: batches.append(current_batch + base_footer) current_batch = base_header + rss_header + word_with_first_news current_batch_has_content = True start_index = 1 else: current_batch = test_content current_batch_has_content = True start_index = 1 # 处理剩余新闻条目 for j in range(start_index, len(stat["titles"])): title_data = stat["titles"][j] if format_type in ("wework", "bark"): formatted_title = format_title_for_platform("wework", title_data, show_source=True) elif format_type == "telegram": formatted_title = format_title_for_platform("telegram", title_data, show_source=True) elif format_type == "ntfy": formatted_title = format_title_for_platform("ntfy", title_data, show_source=True) elif format_type == "feishu": formatted_title = format_title_for_platform("feishu", title_data, show_source=True) elif format_type == "dingtalk": formatted_title = format_title_for_platform("dingtalk", title_data, show_source=True) elif format_type == "slack": formatted_title = format_title_for_platform("slack", title_data, show_source=True) else: formatted_title = f"{title_data['title']}" news_line = f" {j + 1}. {formatted_title}\n" if j < len(stat["titles"]) - 1: news_line += "\n" test_content = current_batch + news_line if len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) >= max_bytes: if current_batch_has_content: batches.append(current_batch + base_footer) current_batch = base_header + rss_header + word_header + news_line current_batch_has_content = True else: current_batch = test_content current_batch_has_content = True # 关键词间分隔符 if i < len(rss_stats) - 1: separator = "" if format_type in ("wework", "bark"): separator = "\n\n\n\n" elif format_type == "telegram": separator = "\n\n" elif format_type == "ntfy": separator = "\n\n" elif format_type == "feishu": separator = f"\n{feishu_separator}\n\n" elif format_type == "dingtalk": separator = "\n---\n\n" elif format_type == "slack": separator = "\n\n" test_content = current_batch + separator if len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) < max_bytes: current_batch = test_content return current_batch, current_batch_has_content, batches def _process_rss_new_titles_section( rss_new_stats: list, format_type: str, feishu_separator: str, base_header: str, base_footer: str, max_bytes: int, current_batch: str, current_batch_has_content: bool, batches: List[str], timezone: str = DEFAULT_TIMEZONE, add_separator: bool = True, ) -> tuple: if not rss_new_stats: return current_batch, current_batch_has_content, batches # 从关键词分组中提取所有条目,重新按来源分组 source_map = {} for stat in rss_new_stats: for title_data in stat.get("titles", []): source_name = title_data.get("source_name", "未知来源") if source_name not in source_map: source_map[source_name] = [] source_map[source_name].append(title_data) if not source_map: return current_batch, current_batch_has_content, batches # 计算总条目数 total_items = sum(len(titles) for titles in source_map.values()) # RSS 新增区块标题(根据 add_separator 决定是否添加前置分割线) new_header = "" if add_separator and current_batch_has_content: # 需要添加分割线 if format_type in ("wework", "bark"): new_header = f"\n\n\n\n🆕 **RSS 本次新增** (共 {total_items} 条)\n\n" elif format_type == "telegram": new_header = f"\n\n🆕 RSS 本次新增 (共 {total_items} 条)\n\n" elif format_type == "ntfy": new_header = f"\n\n🆕 **RSS 本次新增** (共 {total_items} 条)\n\n" elif format_type == "feishu": new_header = f"\n{feishu_separator}\n\n🆕 **RSS 本次新增** (共 {total_items} 条)\n\n" elif format_type == "dingtalk": new_header = f"\n---\n\n🆕 **RSS 本次新增** (共 {total_items} 条)\n\n" elif format_type == "slack": new_header = f"\n\n🆕 *RSS 本次新增* (共 {total_items} 条)\n\n" else: # 不需要分割线(第一个区域) if format_type in ("wework", "bark"): new_header = f"🆕 **RSS 本次新增** (共 {total_items} 条)\n\n" elif format_type == "telegram": new_header = f"🆕 RSS 本次新增 (共 {total_items} 条)\n\n" elif format_type == "ntfy": new_header = f"🆕 **RSS 本次新增** (共 {total_items} 条)\n\n" elif format_type == "feishu": new_header = f"🆕 **RSS 本次新增** (共 {total_items} 条)\n\n" elif format_type == "dingtalk": new_header = f"🆕 **RSS 本次新增** (共 {total_items} 条)\n\n" elif format_type == "slack": new_header = f"🆕 *RSS 本次新增* (共 {total_items} 条)\n\n" # 添加 RSS 新增标题 test_content = current_batch + new_header if len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) >= max_bytes: if current_batch_has_content: batches.append(current_batch + base_footer) current_batch = base_header + new_header current_batch_has_content = True else: current_batch = test_content current_batch_has_content = True # 按来源分组显示(与热榜新增格式一致) source_list = list(source_map.items()) for i, (source_name, titles) in enumerate(source_list): count = len(titles) # 构建来源标题(与热榜新增格式一致) source_header = "" if format_type in ("wework", "bark"): source_header = f"**{source_name}** ({count} 条):\n\n" elif format_type == "telegram": source_header = f"{source_name} ({count} 条):\n\n" elif format_type == "ntfy": source_header = f"**{source_name}** ({count} 条):\n\n" elif format_type == "feishu": source_header = f"**{source_name}** ({count} 条):\n\n" elif format_type == "dingtalk": source_header = f"**{source_name}** ({count} 条):\n\n" elif format_type == "slack": source_header = f"*{source_name}* ({count} 条):\n\n" # 构建第一条新闻(不显示来源,禁用 new emoji) first_news_line = "" if titles: first_title_data = titles[0].copy() first_title_data["is_new"] = False if format_type in ("wework", "bark"): formatted_title = format_title_for_platform("wework", first_title_data, show_source=False) elif format_type == "telegram": formatted_title = format_title_for_platform("telegram", first_title_data, show_source=False) elif format_type == "ntfy": formatted_title = format_title_for_platform("ntfy", first_title_data, show_source=False) elif format_type == "feishu": formatted_title = format_title_for_platform("feishu", first_title_data, show_source=False) elif format_type == "dingtalk": formatted_title = format_title_for_platform("dingtalk", first_title_data, show_source=False) elif format_type == "slack": formatted_title = format_title_for_platform("slack", first_title_data, show_source=False) else: formatted_title = f"{first_title_data['title']}" first_news_line = f" 1. {formatted_title}\n" # 原子性检查:来源标题 + 第一条新闻必须一起处理 source_with_first_news = source_header + first_news_line test_content = current_batch + source_with_first_news if len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) >= max_bytes: if current_batch_has_content: batches.append(current_batch + base_footer) current_batch = base_header + new_header + source_with_first_news current_batch_has_content = True start_index = 1 else: current_batch = test_content current_batch_has_content = True start_index = 1 # 处理剩余新闻条目(禁用 new emoji) for j in range(start_index, len(titles)): title_data = titles[j].copy() title_data["is_new"] = False if format_type in ("wework", "bark"): formatted_title = format_title_for_platform("wework", title_data, show_source=False) elif format_type == "telegram": formatted_title = format_title_for_platform("telegram", title_data, show_source=False) elif format_type == "ntfy": formatted_title = format_title_for_platform("ntfy", title_data, show_source=False) elif format_type == "feishu": formatted_title = format_title_for_platform("feishu", title_data, show_source=False) elif format_type == "dingtalk": formatted_title = format_title_for_platform("dingtalk", title_data, show_source=False) elif format_type == "slack": formatted_title = format_title_for_platform("slack", title_data, show_source=False) else: formatted_title = f"{title_data['title']}" news_line = f" {j + 1}. {formatted_title}\n" test_content = current_batch + news_line if len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) >= max_bytes: if current_batch_has_content: batches.append(current_batch + base_footer) current_batch = base_header + new_header + source_header + news_line current_batch_has_content = True else: current_batch = test_content current_batch_has_content = True # 来源间添加空行(与热榜新增格式一致) current_batch += "\n" return current_batch, current_batch_has_content, batches def _format_rss_item_line( item: Dict, index: int, format_type: str, timezone: str = DEFAULT_TIMEZONE, ) -> str: title = item.get("title", "") url = item.get("url", "") published_at = item.get("published_at", "") # 使用友好时间格式 if published_at: friendly_time = format_iso_time_friendly(published_at, timezone, include_date=True) else: friendly_time = "" # 构建条目行 if format_type == "feishu": if url: item_line = f" {index}. [{title}]({url})" else: item_line = f" {index}. {title}" if friendly_time: item_line += f" <font color='grey'>- {friendly_time}</font>" elif format_type == "telegram": if url: item_line = f" {index}. {title} ({url})" else: item_line = f" {index}. {title}" if friendly_time: item_line += f" - {friendly_time}" else: if url: item_line = f" {index}. [{title}]({url})" else: item_line = f" {index}. {title}" if friendly_time: item_line += f" `{friendly_time}`" item_line += "\n" return item_line def _process_standalone_section( standalone_data: Dict, format_type: str, feishu_separator: str, base_header: str, base_footer: str, max_bytes: int, current_batch: str, current_batch_has_content: bool, batches: List[str], timezone: str = DEFAULT_TIMEZONE, rank_threshold: int = 10, add_separator: bool = True, ) -> tuple: if not standalone_data: return current_batch, current_batch_has_content, batches platforms = standalone_data.get("platforms", []) rss_feeds = standalone_data.get("rss_feeds", []) if not platforms and not rss_feeds: return current_batch, current_batch_has_content, batches # 计算总条目数 total_platform_items = sum(len(p.get("items", [])) for p in platforms) total_rss_items = sum(len(f.get("items", [])) for f in rss_feeds) total_items = total_platform_items + total_rss_items # 独立展示区标题(根据 add_separator 决定是否添加前置分割线) section_header = "" if add_separator and current_batch_has_content: # 需要添加分割线 if format_type == "feishu": section_header = f"\n{feishu_separator}\n\n📋 **独立展示区** (共 {total_items} 条)\n\n" elif format_type == "dingtalk": section_header = f"\n---\n\n📋 **独立展示区** (共 {total_items} 条)\n\n" elif format_type in ("wework", "bark"): section_header = f"\n\n\n\n📋 **独立展示区** (共 {total_items} 条)\n\n" elif format_type == "telegram": section_header = f"\n\n📋 独立展示区 (共 {total_items} 条)\n\n" elif format_type == "slack": section_header = f"\n\n📋 *独立展示区* (共 {total_items} 条)\n\n" else: section_header = f"\n\n📋 **独立展示区** (共 {total_items} 条)\n\n" else: # 不需要分割线(第一个区域) if format_type == "feishu": section_header = f"📋 **独立展示区** (共 {total_items} 条)\n\n" elif format_type == "dingtalk": section_header = f"📋 **独立展示区** (共 {total_items} 条)\n\n" elif format_type == "telegram": section_header = f"📋 独立展示区 (共 {total_items} 条)\n\n" elif format_type == "slack": section_header = f"📋 *独立展示区* (共 {total_items} 条)\n\n" else: section_header = f"📋 **独立展示区** (共 {total_items} 条)\n\n" # 添加区块标题 test_content = current_batch + section_header if len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) < max_bytes: current_batch = test_content current_batch_has_content = True else: if current_batch_has_content: batches.append(current_batch + base_footer) current_batch = base_header + section_header current_batch_has_content = True # 处理热榜平台 for platform in platforms: platform_name = platform.get("name", platform.get("id", "")) items = platform.get("items", []) if not items: continue # 平台标题 platform_header = "" if format_type in ("wework", "bark"): platform_header = f"**{platform_name}** ({len(items)} 条):\n\n" elif format_type == "telegram": platform_header = f"{platform_name} ({len(items)} 条):\n\n" elif format_type == "ntfy": platform_header = f"**{platform_name}** ({len(items)} 条):\n\n" elif format_type == "feishu": platform_header = f"**{platform_name}** ({len(items)} 条):\n\n" elif format_type == "dingtalk": platform_header = f"**{platform_name}** ({len(items)} 条):\n\n" elif format_type == "slack": platform_header = f"*{platform_name}* ({len(items)} 条):\n\n" # 构建第一条新闻 first_item_line = "" if items: first_item_line = _format_standalone_platform_item(items[0], 1, format_type, rank_threshold) # 原子性检查 platform_with_first = platform_header + first_item_line test_content = current_batch + platform_with_first if len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) >= max_bytes: if current_batch_has_content: batches.append(current_batch + base_footer) current_batch = base_header + section_header + platform_with_first current_batch_has_content = True start_index = 1 else: current_batch = test_content current_batch_has_content = True start_index = 1 # 处理剩余条目 for j in range(start_index, len(items)): item_line = _format_standalone_platform_item(items[j], j + 1, format_type, rank_threshold) test_content = current_batch + item_line if len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) >= max_bytes: if current_batch_has_content: batches.append(current_batch + base_footer) current_batch = base_header + section_header + platform_header + item_line current_batch_has_content = True else: current_batch = test_content current_batch_has_content = True current_batch += "\n" # 处理 RSS 源 for feed in rss_feeds: feed_name = feed.get("name", feed.get("id", "")) items = feed.get("items", []) if not items: continue # RSS 源标题 feed_header = "" if format_type in ("wework", "bark"): feed_header = f"**{feed_name}** ({len(items)} 条):\n\n" elif format_type == "telegram": feed_header = f"{feed_name} ({len(items)} 条):\n\n" elif format_type == "ntfy": feed_header = f"**{feed_name}** ({len(items)} 条):\n\n" elif format_type == "feishu": feed_header = f"**{feed_name}** ({len(items)} 条):\n\n" elif format_type == "dingtalk": feed_header = f"**{feed_name}** ({len(items)} 条):\n\n" elif format_type == "slack": feed_header = f"*{feed_name}* ({len(items)} 条):\n\n" # 构建第一条 RSS first_item_line = "" if items: first_item_line = _format_standalone_rss_item(items[0], 1, format_type, timezone) # 原子性检查 feed_with_first = feed_header + first_item_line test_content = current_batch + feed_with_first if len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) >= max_bytes: if current_batch_has_content: batches.append(current_batch + base_footer) current_batch = base_header + section_header + feed_with_first current_batch_has_content = True start_index = 1 else: current_batch = test_content current_batch_has_content = True start_index = 1 # 处理剩余条目 for j in range(start_index, len(items)): item_line = _format_standalone_rss_item(items[j], j + 1, format_type, timezone) test_content = current_batch + item_line if len(test_content.encode("utf-8")) + len(base_footer.encode("utf-8")) >= max_bytes: if current_batch_has_content: batches.append(current_batch + base_footer) current_batch = base_header + section_header + feed_header + item_line current_batch_has_content = True else: current_batch = test_content current_batch_has_content = True current_batch += "\n" return current_batch, current_batch_has_content, batches def _format_standalone_platform_item(item: Dict, index: int, format_type: str, rank_threshold: int = 10) -> str: title = item.get("title", "") url = item.get("url", "") or item.get("mobileUrl", "") ranks = item.get("ranks", []) rank = item.get("rank", 0) first_time = item.get("first_time", "") last_time = item.get("last_time", "") count = item.get("count", 1) # 使用 format_rank_display 格式化排名(复用热点词汇统计区逻辑) # 如果没有 ranks 列表,用单个 rank 构造 if not ranks and rank > 0: ranks = [rank] rank_display = format_rank_display(ranks, rank_threshold, format_type) if ranks else "" # 构建时间显示(用 ~ 连接范围,与热点词汇统计区一致) # 将 HH-MM 格式转换为 HH:MM 格式 time_display = "" if first_time and last_time and first_time != last_time: first_time_display = convert_time_for_display(first_time) last_time_display = convert_time_for_display(last_time) time_display = f"{first_time_display}~{last_time_display}" elif first_time: time_display = convert_time_for_display(first_time) # 构建次数显示(格式为 (N次),与热点词汇统计区一致) count_display = f"({count}次)" if count > 1 else "" # 根据格式类型构建条目行(复用热点词汇统计区样式) if format_type == "feishu": if url: item_line = f" {index}. [{title}]({url})" else: item_line = f" {index}. {title}" if rank_display: item_line += f" {rank_display}" if time_display: item_line += f" <font color='grey'>- {time_display}</font>" if count_display: item_line += f" <font color='green'>{count_display}</font>" elif format_type == "dingtalk": if url: item_line = f" {index}. [{title}]({url})" else: item_line = f" {index}. {title}" if rank_display: item_line += f" {rank_display}" if time_display: item_line += f" - {time_display}" if count_display: item_line += f" {count_display}" elif format_type == "telegram": if url: item_line = f" {index}. {title} ({url})" else: item_line = f" {index}. {title}" if rank_display: item_line += f" {rank_display}" if time_display: item_line += f" - {time_display}" if count_display: item_line += f" {count_display}" elif format_type == "slack": if url: item_line = f" {index}. <{url}|{title}>" else: item_line = f" {index}. {title}" if rank_display: item_line += f" {rank_display}" if time_display: item_line += f" _{time_display}_" if count_display: item_line += f" {count_display}" else: # wework, bark, ntfy if url: item_line = f" {index}. [{title}]({url})" else: item_line = f" {index}. {title}" if rank_display: item_line += f" {rank_display}" if time_display: item_line += f" - {time_display}" if count_display: item_line += f" {count_display}" item_line += "\n" return item_line def _format_standalone_rss_item( item: Dict, index: int, format_type: str, timezone: str = "Asia/Shanghai" ) -> str: title = item.get("title", "") url = item.get("url", "") published_at = item.get("published_at", "") author = item.get("author", "") # 使用友好时间格式 friendly_time = "" if published_at: friendly_time = format_iso_time_friendly(published_at, timezone, include_date=True) # 构建元信息 meta_parts = [] if friendly_time: meta_parts.append(friendly_time) if author: meta_parts.append(author) meta_str = ", ".join(meta_parts) # 根据格式类型构建条目行 if format_type == "feishu": if url: item_line = f" {index}. [{title}]({url})" else: item_line = f" {index}. {title}" if meta_str: item_line += f" <font color='grey'>- {meta_str}</font>" elif format_type == "telegram": if url: item_line = f" {index}. {title} ({url})" else: item_line = f" {index}. {title}" if meta_str: item_line += f" - {meta_str}" elif format_type == "slack": if url: item_line = f" {index}. <{url}|{title}>" else: item_line = f" {index}. {title}" if meta_str: item_line += f" _{meta_str}_" else: # wework, bark, ntfy, dingtalk if url: item_line = f" {index}. [{title}]({url})" else: item_line = f" {index}. {title}" if meta_str: item_line += f" `{meta_str}`" item_line += "\n" return item_line
--- +++ @@ -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]: + """分批处理消息内容,确保词组标题+至少第一条新闻的完整性(支持热榜+RSS合并+AI分析+独立展示区) + + 热榜统计与RSS统计并列显示,热榜新增与RSS新增并列显示。 + region_order 控制各区域的显示顺序。 + AI分析内容根据 region_order 中的位置显示。 + 独立展示区根据 region_order 中的位置显示。 + + Args: + report_data: 报告数据字典,包含 stats, new_titles, failed_ids, total_new_count + format_type: 格式类型 (feishu, dingtalk, wework, telegram, ntfy, bark, slack) + update_info: 版本更新信息(可选) + max_bytes: 最大字节数(可选,如果不指定则使用默认配置) + mode: 报告模式 (daily, incremental, current) + batch_sizes: 批次大小配置字典(可选) + feishu_separator: 飞书消息分隔符 + region_order: 区域显示顺序列表 + get_time_func: 获取当前时间的函数(可选) + rss_items: RSS 统计条目列表(按源分组,用于合并推送) + rss_new_items: RSS 新增条目列表(可选,用于新增区块) + timezone: 时区名称(用于 RSS 时间格式化) + display_mode: 显示模式 (keyword=按关键词分组, platform=按平台分组) + ai_content: AI 分析内容(已渲染的字符串,可选) + standalone_data: 独立展示区数据(可选),包含 platforms 和 rss_feeds 列表 + ai_stats: AI 分析统计数据(可选),包含 total_news, analyzed_news, max_news_limit 等 + + Returns: + 分批后的消息内容列表 + """ if region_order is None: region_order = DEFAULT_REGION_ORDER # 合并批次大小配置 @@ -206,6 +239,7 @@ # 定义处理热点词汇统计的函数 def process_stats_section(current_batch, current_batch_has_content, batches, add_separator=True): + """处理热点词汇统计""" if not report_data["stats"]: return current_batch, current_batch_has_content, batches @@ -440,6 +474,7 @@ # 定义处理新增新闻的函数 def process_new_titles_section(current_batch, current_batch_has_content, batches, add_separator=True): + """处理新增新闻""" if not show_new_section or not report_data["new_titles"]: return current_batch, current_batch_has_content, batches @@ -605,6 +640,7 @@ # 定义处理 AI 分析的函数 def process_ai_section(current_batch, current_batch_has_content, batches, add_separator=True): + """处理 AI 分析内容""" nonlocal ai_content if not ai_content: return current_batch, current_batch_has_content, batches @@ -644,6 +680,7 @@ # 定义处理独立展示区的函数 def process_standalone_section_wrapper(current_batch, current_batch_has_content, batches, add_separator=True): + """处理独立展示区""" if not standalone_data: return current_batch, current_batch_has_content, batches return _process_standalone_section( @@ -654,6 +691,7 @@ # 定义处理 RSS 统计的函数 def process_rss_stats_wrapper(current_batch, current_batch_has_content, batches, add_separator=True): + """处理 RSS 统计""" if not rss_items: return current_batch, current_batch_has_content, batches return _process_rss_stats_section( @@ -664,6 +702,7 @@ # 定义处理 RSS 新增的函数 def process_rss_new_wrapper(current_batch, current_batch_has_content, batches, add_separator=True): + """处理 RSS 新增""" if not rss_new_items: return current_batch, current_batch_has_content, batches return _process_rss_new_titles_section( @@ -798,6 +837,25 @@ timezone: str = DEFAULT_TIMEZONE, add_separator: bool = True, ) -> tuple: + """处理 RSS 统计区块(按关键词分组,与热榜统计格式一致) + + Args: + rss_stats: RSS 关键词统计列表,格式与热榜 stats 一致: + [{"word": "AI", "count": 5, "titles": [...]}] + format_type: 格式类型 + feishu_separator: 飞书分隔符 + base_header: 基础头部 + base_footer: 基础尾部 + max_bytes: 最大字节数 + current_batch: 当前批次内容 + current_batch_has_content: 当前批次是否有内容 + batches: 已完成的批次列表 + timezone: 时区名称 + add_separator: 是否在区块前添加分割线(第一个区域时为 False) + + Returns: + (current_batch, current_batch_has_content, batches) 元组 + """ if not rss_stats: return current_batch, current_batch_has_content, batches @@ -1002,6 +1060,25 @@ timezone: str = DEFAULT_TIMEZONE, add_separator: bool = True, ) -> tuple: + """处理 RSS 新增区块(按来源分组,与热榜新增格式一致) + + Args: + rss_new_stats: RSS 新增关键词统计列表,格式与热榜 stats 一致: + [{"word": "AI", "count": 5, "titles": [...]}] + format_type: 格式类型 + feishu_separator: 飞书分隔符 + base_header: 基础头部 + base_footer: 基础尾部 + max_bytes: 最大字节数 + current_batch: 当前批次内容 + current_batch_has_content: 当前批次是否有内容 + batches: 已完成的批次列表 + timezone: 时区名称 + add_separator: 是否在区块前添加分割线(第一个区域时为 False) + + Returns: + (current_batch, current_batch_has_content, batches) 元组 + """ if not rss_new_stats: return current_batch, current_batch_has_content, batches @@ -1162,6 +1239,17 @@ format_type: str, timezone: str = DEFAULT_TIMEZONE, ) -> str: + """格式化单条 RSS 条目 + + Args: + item: RSS 条目字典 + index: 序号 + format_type: 格式类型 + timezone: 时区名称 + + Returns: + 格式化后的条目行字符串 + """ title = item.get("title", "") url = item.get("url", "") published_at = item.get("published_at", "") @@ -1213,6 +1301,32 @@ rank_threshold: int = 10, add_separator: bool = True, ) -> tuple: + """处理独立展示区区块 + + 独立展示区显示指定平台的完整热榜或 RSS 源内容,不受关键词过滤影响。 + 热榜按原始排名排序,RSS 按发布时间排序。 + + Args: + standalone_data: 独立展示数据,格式: + { + "platforms": [{"id": "zhihu", "name": "知乎热榜", "items": [...]}], + "rss_feeds": [{"id": "hacker-news", "name": "Hacker News", "items": [...]}] + } + format_type: 格式类型 + feishu_separator: 飞书分隔符 + base_header: 基础头部 + base_footer: 基础尾部 + max_bytes: 最大字节数 + current_batch: 当前批次内容 + current_batch_has_content: 当前批次是否有内容 + batches: 已完成的批次列表 + timezone: 时区名称 + rank_threshold: 排名高亮阈值 + add_separator: 是否在区块前添加分割线(第一个区域时为 False) + + Returns: + (current_batch, current_batch_has_content, batches) 元组 + """ if not standalone_data: return current_batch, current_batch_has_content, batches @@ -1387,6 +1501,17 @@ def _format_standalone_platform_item(item: Dict, index: int, format_type: str, rank_threshold: int = 10) -> str: + """格式化独立展示区的热榜条目(复用热点词汇统计区样式) + + Args: + item: 热榜条目,包含 title, url, rank, ranks, first_time, last_time, count + index: 序号 + format_type: 格式类型 + rank_threshold: 排名高亮阈值 + + Returns: + 格式化后的条目行字符串 + """ title = item.get("title", "") url = item.get("url", "") or item.get("mobileUrl", "") ranks = item.get("ranks", []) @@ -1483,6 +1608,17 @@ def _format_standalone_rss_item( item: Dict, index: int, format_type: str, timezone: str = "Asia/Shanghai" ) -> str: + """格式化独立展示区的 RSS 条目 + + Args: + item: RSS 条目,包含 title, url, published_at, author + index: 序号 + format_type: 格式类型 + timezone: 时区名称 + + Returns: + 格式化后的条目行字符串 + """ title = item.get("title", "") url = item.get("url", "") published_at = item.get("published_at", "") @@ -1533,4 +1669,4 @@ item_line += f" `{meta_str}`" item_line += "\n" - return item_line+ return item_line
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 import ModelPatcher from segment_anything.modeling import Sam from typing import Optional, Tuple from segment_anything.utils.transforms import ResizeLongestSide class SamPredictor: def __init__( self, model: Sam, load_device=model_management.text_encoder_device(), offload_device=model_management.text_encoder_offload_device() ) -> None: super().__init__() self.load_device = load_device self.offload_device = offload_device # can't use model.half() here as slow_conv2d_cpu is not implemented for half model.to(self.offload_device) self.patcher = ModelPatcher(model, load_device=self.load_device, offload_device=self.offload_device) self.transform = ResizeLongestSide(model.image_encoder.img_size) self.reset_image() def set_image( self, image: np.ndarray, image_format: str = "RGB", ) -> None: assert image_format in [ "RGB", "BGR", ], f"image_format must be in ['RGB', 'BGR'], is {image_format}." if image_format != self.patcher.model.image_format: image = image[..., ::-1] # Transform the image to the form expected by the model input_image = self.transform.apply_image(image) input_image_torch = torch.as_tensor(input_image, device=self.load_device) input_image_torch = input_image_torch.permute(2, 0, 1).contiguous()[None, :, :, :] self.set_torch_image(input_image_torch, image.shape[:2]) @torch.no_grad() def set_torch_image( self, transformed_image: torch.Tensor, original_image_size: Tuple[int, ...], ) -> None: assert ( len(transformed_image.shape) == 4 and transformed_image.shape[1] == 3 and max(*transformed_image.shape[2:]) == self.patcher.model.image_encoder.img_size ), f"set_torch_image input must be BCHW with long side {self.patcher.model.image_encoder.img_size}." self.reset_image() self.original_size = original_image_size self.input_size = tuple(transformed_image.shape[-2:]) model_management.load_model_gpu(self.patcher) input_image = self.patcher.model.preprocess(transformed_image.to(self.load_device)) self.features = self.patcher.model.image_encoder(input_image) self.is_image_set = True def predict( self, point_coords: Optional[np.ndarray] = None, point_labels: Optional[np.ndarray] = None, box: Optional[np.ndarray] = None, mask_input: Optional[np.ndarray] = None, multimask_output: bool = True, return_logits: bool = False, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: if not self.is_image_set: raise RuntimeError("An image must be set with .set_image(...) before mask prediction.") # Transform input prompts coords_torch, labels_torch, box_torch, mask_input_torch = None, None, None, None if point_coords is not None: assert ( point_labels is not None ), "point_labels must be supplied if point_coords is supplied." point_coords = self.transform.apply_coords(point_coords, self.original_size) coords_torch = torch.as_tensor(point_coords, dtype=torch.float, device=self.load_device) labels_torch = torch.as_tensor(point_labels, dtype=torch.int, device=self.load_device) coords_torch, labels_torch = coords_torch[None, :, :], labels_torch[None, :] if box is not None: box = self.transform.apply_boxes(box, self.original_size) box_torch = torch.as_tensor(box, dtype=torch.float, device=self.load_device) box_torch = box_torch[None, :] if mask_input is not None: mask_input_torch = torch.as_tensor(mask_input, dtype=torch.float, device=self.load_device) mask_input_torch = mask_input_torch[None, :, :, :] masks, iou_predictions, low_res_masks = self.predict_torch( coords_torch, labels_torch, box_torch, mask_input_torch, multimask_output, return_logits=return_logits, ) masks = masks[0].detach().cpu().numpy() iou_predictions = iou_predictions[0].detach().cpu().numpy() low_res_masks = low_res_masks[0].detach().cpu().numpy() return masks, iou_predictions, low_res_masks @torch.no_grad() def predict_torch( self, point_coords: Optional[torch.Tensor], point_labels: Optional[torch.Tensor], boxes: Optional[torch.Tensor] = None, mask_input: Optional[torch.Tensor] = None, multimask_output: bool = True, return_logits: bool = False, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: if not self.is_image_set: raise RuntimeError("An image must be set with .set_image(...) before mask prediction.") if point_coords is not None: points = (point_coords.to(self.load_device), point_labels.to(self.load_device)) else: points = None # load if boxes is not None: boxes = boxes.to(self.load_device) if mask_input is not None: mask_input = mask_input.to(self.load_device) model_management.load_model_gpu(self.patcher) # Embed prompts sparse_embeddings, dense_embeddings = self.patcher.model.prompt_encoder( points=points, boxes=boxes, masks=mask_input, ) # Predict masks low_res_masks, iou_predictions = self.patcher.model.mask_decoder( image_embeddings=self.features, image_pe=self.patcher.model.prompt_encoder.get_dense_pe(), sparse_prompt_embeddings=sparse_embeddings, dense_prompt_embeddings=dense_embeddings, multimask_output=multimask_output, ) # Upscale the masks to the original image resolution masks = self.patcher.model.postprocess_masks(low_res_masks, self.input_size, self.original_size) if not return_logits: masks = masks > self.patcher.model.mask_threshold return masks, iou_predictions, low_res_masks def get_image_embedding(self) -> torch.Tensor: if not self.is_image_set: raise RuntimeError( "An image must be set with .set_image(...) to generate an embedding." ) assert self.features is not None, "Features must exist if an image has been set." return self.features @property def device(self) -> torch.device: return self.patcher.model.device def reset_image(self) -> None: self.is_image_set = False self.features = None self.orig_h = None self.orig_w = None self.input_h = None self.input_w = None
--- +++ @@ -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 prompts. + + Arguments: + model (Sam): The model to use for mask prediction. + """ super().__init__() self.load_device = load_device @@ -40,6 +47,15 @@ image: np.ndarray, image_format: str = "RGB", ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. + + Arguments: + image (np.ndarray): The image for calculating masks. Expects an + image in HWC uint8 format, with pixel values in [0, 255]. + image_format (str): The color format of the image, in ['RGB', 'BGR']. + """ assert image_format in [ "RGB", "BGR", @@ -60,6 +76,17 @@ transformed_image: torch.Tensor, original_image_size: Tuple[int, ...], ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. Expects the input + image to be already transformed to the format expected by the model. + + Arguments: + transformed_image (torch.Tensor): The input image, with shape + 1x3xHxW, which has been transformed with ResizeLongestSide. + original_image_size (tuple(int, int)): The size of the image + before transformation, in (H, W) format. + """ assert ( len(transformed_image.shape) == 4 and transformed_image.shape[1] == 3 @@ -83,6 +110,38 @@ multimask_output: bool = True, return_logits: bool = False, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Predict masks for the given input prompts, using the currently set image. + + Arguments: + point_coords (np.ndarray or None): A Nx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (np.ndarray or None): A length N array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + box (np.ndarray or None): A length 4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form 1xHxW, where + for SAM, H=W=256. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (np.ndarray): The output masks in CxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (np.ndarray): An array of length C containing the model's + predictions for the quality of each mask. + (np.ndarray): An array of shape CxHxW, where C is the number + of masks and H=W=256. These low resolution logits can be passed to + a subsequent iteration as mask input. + """ if not self.is_image_set: raise RuntimeError("An image must be set with .set_image(...) before mask prediction.") @@ -128,6 +187,41 @@ multimask_output: bool = True, return_logits: bool = False, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Predict masks for the given input prompts, using the currently set image. + Input prompts are batched torch tensors and are expected to already be + transformed to the input frame using ResizeLongestSide. + + Arguments: + point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (torch.Tensor or None): A BxN array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + box (np.ndarray or None): A Bx4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form Bx1xHxW, where + for SAM, H=W=256. Masks returned by a previous iteration of the + predict method do not need further transformation. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (torch.Tensor): The output masks in BxCxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (torch.Tensor): An array of shape BxC containing the model's + predictions for the quality of each mask. + (torch.Tensor): An array of shape BxCxHxW, where C is the number + of masks and H=W=256. These low res logits can be passed to + a subsequent iteration as mask input. + """ if not self.is_image_set: raise RuntimeError("An image must be set with .set_image(...) before mask prediction.") @@ -168,6 +262,11 @@ return masks, iou_predictions, low_res_masks def get_image_embedding(self) -> torch.Tensor: + """ + Returns the image embeddings for the currently set image, with + shape 1xCxHxW, where C is the embedding dimension and (H,W) are + the embedding spatial dimension of SAM (typically C=256, H=W=64). + """ if not self.is_image_set: raise RuntimeError( "An image must be set with .set_image(...) to generate an embedding." @@ -180,9 +279,10 @@ return self.patcher.model.device def reset_image(self) -> None: + """Resets the currently set image.""" self.is_image_set = False self.features = None self.orig_h = None self.orig_w = None self.input_h = None - self.input_w = None+ self.input_w = None
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: # ======================================== # 抽象方法 - 子类必须实现 # ======================================== @abstractmethod def _get_connection(self, date: Optional[str] = None, db_type: str = "news") -> sqlite3.Connection: pass @abstractmethod def _get_configured_time(self) -> datetime: pass @abstractmethod def _format_date_folder(self, date: Optional[str] = None) -> str: pass @abstractmethod def _format_time_filename(self) -> str: pass # ======================================== # Schema 管理 # ======================================== def _get_schema_path(self, db_type: str = "news") -> Path: if db_type == "rss": return Path(__file__).parent / "rss_schema.sql" return Path(__file__).parent / "schema.sql" def _get_ai_filter_schema_path(self) -> Path: return Path(__file__).parent / "ai_filter_schema.sql" def _init_tables(self, conn: sqlite3.Connection, db_type: str = "news") -> None: schema_path = self._get_schema_path(db_type) if schema_path.exists(): with open(schema_path, "r", encoding="utf-8") as f: schema_sql = f.read() conn.executescript(schema_sql) else: raise FileNotFoundError(f"Schema file not found: {schema_path}") # news 库额外加载 AI 筛选表结构 if db_type == "news": ai_filter_schema = self._get_ai_filter_schema_path() if ai_filter_schema.exists(): with open(ai_filter_schema, "r", encoding="utf-8") as f: conn.executescript(f.read()) conn.commit() # ======================================== # 新闻数据存储 # ======================================== def _save_news_data_impl(self, data: NewsData, log_prefix: str = "[存储]") -> tuple[bool, int, int, int, int]: try: conn = self._get_connection(data.date) cursor = conn.cursor() # 获取配置时区的当前时间 now_str = self._get_configured_time().strftime("%Y-%m-%d %H:%M:%S") # 首先同步平台信息到 platforms 表 for source_id, source_name in data.id_to_name.items(): cursor.execute(""" INSERT INTO platforms (id, name, updated_at) VALUES (?, ?, ?) ON CONFLICT(id) DO UPDATE SET name = excluded.name, updated_at = excluded.updated_at """, (source_id, source_name, now_str)) # 统计计数器 new_count = 0 updated_count = 0 title_changed_count = 0 success_sources = [] for source_id, news_list in data.items.items(): success_sources.append(source_id) for item in news_list: try: # 标准化 URL(去除动态参数,如微博的 band_rank) normalized_url = normalize_url(item.url, source_id) if item.url else "" # 检查是否已存在(通过标准化 URL + platform_id) if normalized_url: cursor.execute(""" SELECT id, title FROM news_items WHERE url = ? AND platform_id = ? """, (normalized_url, source_id)) existing = cursor.fetchone() if existing: # 已存在,更新记录 existing_id, existing_title = existing # 检查标题是否变化 if existing_title != item.title: # 记录标题变更 cursor.execute(""" INSERT INTO title_changes (news_item_id, old_title, new_title, changed_at) VALUES (?, ?, ?, ?) """, (existing_id, existing_title, item.title, now_str)) title_changed_count += 1 # 记录排名历史 cursor.execute(""" INSERT INTO rank_history (news_item_id, rank, crawl_time, created_at) VALUES (?, ?, ?, ?) """, (existing_id, item.rank, data.crawl_time, now_str)) # 更新现有记录 cursor.execute(""" UPDATE news_items SET title = ?, rank = ?, mobile_url = ?, last_crawl_time = ?, crawl_count = crawl_count + 1, updated_at = ? WHERE id = ? """, (item.title, item.rank, item.mobile_url, data.crawl_time, now_str, existing_id)) updated_count += 1 else: # 不存在,插入新记录(存储标准化后的 URL) cursor.execute(""" INSERT INTO news_items (title, platform_id, rank, url, mobile_url, first_crawl_time, last_crawl_time, crawl_count, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, ?) """, (item.title, source_id, item.rank, normalized_url, item.mobile_url, data.crawl_time, data.crawl_time, now_str, now_str)) new_id = cursor.lastrowid # 记录初始排名 cursor.execute(""" INSERT INTO rank_history (news_item_id, rank, crawl_time, created_at) VALUES (?, ?, ?, ?) """, (new_id, item.rank, data.crawl_time, now_str)) new_count += 1 else: # URL 为空的情况,直接插入(不做去重) cursor.execute(""" INSERT INTO news_items (title, platform_id, rank, url, mobile_url, first_crawl_time, last_crawl_time, crawl_count, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, ?) """, (item.title, source_id, item.rank, "", item.mobile_url, data.crawl_time, data.crawl_time, now_str, now_str)) new_id = cursor.lastrowid # 记录初始排名 cursor.execute(""" INSERT INTO rank_history (news_item_id, rank, crawl_time, created_at) VALUES (?, ?, ?, ?) """, (new_id, item.rank, data.crawl_time, now_str)) new_count += 1 except sqlite3.Error as e: print(f"{log_prefix} 保存新闻条目失败 [{item.title[:30]}...]: {e}") total_items = new_count + updated_count # ======================================== # 脱榜检测:检测上次在榜但这次不在榜的新闻 # ======================================== off_list_count = 0 # 获取上一次抓取时间 cursor.execute(""" SELECT crawl_time FROM crawl_records WHERE crawl_time < ? ORDER BY crawl_time DESC LIMIT 1 """, (data.crawl_time,)) prev_record = cursor.fetchone() if prev_record: prev_crawl_time = prev_record[0] # 对于每个成功抓取的平台,检测脱榜 for source_id in success_sources: # 获取当前抓取中该平台的所有标准化 URL current_urls = set() for item in data.items.get(source_id, []): normalized_url = normalize_url(item.url, source_id) if item.url else "" if normalized_url: current_urls.add(normalized_url) # 查询上次在榜(last_crawl_time = prev_crawl_time)但这次不在榜的新闻 # 这些新闻是"第一次脱榜",需要记录 cursor.execute(""" SELECT id, url FROM news_items WHERE platform_id = ? AND last_crawl_time = ? AND url != '' """, (source_id, prev_crawl_time)) for row in cursor.fetchall(): news_id, url = row[0], row[1] if url not in current_urls: # 插入脱榜记录(rank=0 表示脱榜) cursor.execute(""" INSERT INTO rank_history (news_item_id, rank, crawl_time, created_at) VALUES (?, 0, ?, ?) """, (news_id, data.crawl_time, now_str)) off_list_count += 1 # 记录抓取信息 cursor.execute(""" INSERT OR REPLACE INTO crawl_records (crawl_time, total_items, created_at) VALUES (?, ?, ?) """, (data.crawl_time, total_items, now_str)) # 获取刚插入的 crawl_record 的 ID cursor.execute(""" SELECT id FROM crawl_records WHERE crawl_time = ? """, (data.crawl_time,)) record_row = cursor.fetchone() if record_row: crawl_record_id = record_row[0] # 记录成功的来源 for source_id in success_sources: cursor.execute(""" INSERT OR REPLACE INTO crawl_source_status (crawl_record_id, platform_id, status) VALUES (?, ?, 'success') """, (crawl_record_id, source_id)) # 记录失败的来源 for failed_id in data.failed_ids: # 确保失败的平台也在 platforms 表中 cursor.execute(""" INSERT OR IGNORE INTO platforms (id, name, updated_at) VALUES (?, ?, ?) """, (failed_id, failed_id, now_str)) cursor.execute(""" INSERT OR REPLACE INTO crawl_source_status (crawl_record_id, platform_id, status) VALUES (?, ?, 'failed') """, (crawl_record_id, failed_id)) conn.commit() return True, new_count, updated_count, title_changed_count, off_list_count except Exception as e: print(f"{log_prefix} 保存失败: {e}") return False, 0, 0, 0, 0 def _get_today_all_data_impl(self, date: Optional[str] = None) -> Optional[NewsData]: try: conn = self._get_connection(date) cursor = conn.cursor() # 获取所有新闻数据(包含 id 用于查询排名历史) cursor.execute(""" SELECT n.id, n.title, n.platform_id, p.name as platform_name, n.rank, n.url, n.mobile_url, n.first_crawl_time, n.last_crawl_time, n.crawl_count FROM news_items n LEFT JOIN platforms p ON n.platform_id = p.id ORDER BY n.platform_id, n.last_crawl_time """) rows = cursor.fetchall() if not rows: return None # 收集所有 news_item_id news_ids = [row[0] for row in rows] # 批量查询排名历史(同时获取时间和排名) # 过滤逻辑:只保留 last_crawl_time 之前的脱榜记录(rank=0) # 这样可以避免显示新闻永久脱榜后的无意义记录 rank_history_map: Dict[int, List[int]] = {} rank_timeline_map: Dict[int, List[Dict[str, Any]]] = {} if news_ids: placeholders = ",".join("?" * len(news_ids)) cursor.execute(f""" SELECT rh.news_item_id, rh.rank, rh.crawl_time FROM rank_history rh JOIN news_items ni ON rh.news_item_id = ni.id WHERE rh.news_item_id IN ({placeholders}) AND NOT (rh.rank = 0 AND rh.crawl_time > ni.last_crawl_time) ORDER BY rh.news_item_id, rh.crawl_time """, news_ids) for rh_row in cursor.fetchall(): news_id, rank, crawl_time = rh_row[0], rh_row[1], rh_row[2] # 构建 ranks 列表(去重,排除脱榜记录 rank=0) if news_id not in rank_history_map: rank_history_map[news_id] = [] if rank != 0 and rank not in rank_history_map[news_id]: rank_history_map[news_id].append(rank) # 构建 rank_timeline 列表(完整时间线,包含脱榜) if news_id not in rank_timeline_map: rank_timeline_map[news_id] = [] # 提取时间部分(HH:MM) time_part = crawl_time.split()[1][:5] if ' ' in crawl_time else crawl_time[:5] rank_timeline_map[news_id].append({ "time": time_part, "rank": rank if rank != 0 else None # 0 转为 None 表示脱榜 }) # 按 platform_id 分组 items: Dict[str, List[NewsItem]] = {} id_to_name: Dict[str, str] = {} crawl_date = self._format_date_folder(date) for row in rows: news_id = row[0] platform_id = row[2] title = row[1] platform_name = row[3] or platform_id id_to_name[platform_id] = platform_name if platform_id not in items: items[platform_id] = [] # 获取排名历史,如果没有则使用当前排名 ranks = rank_history_map.get(news_id, [row[4]]) rank_timeline = rank_timeline_map.get(news_id, []) items[platform_id].append(NewsItem( title=title, source_id=platform_id, source_name=platform_name, rank=row[4], url=row[5] or "", mobile_url=row[6] or "", crawl_time=row[8], # last_crawl_time ranks=ranks, first_time=row[7], # first_crawl_time last_time=row[8], # last_crawl_time count=row[9], # crawl_count rank_timeline=rank_timeline, )) final_items = items # 获取失败的来源 cursor.execute(""" SELECT DISTINCT css.platform_id FROM crawl_source_status css JOIN crawl_records cr ON css.crawl_record_id = cr.id WHERE css.status = 'failed' """) failed_ids = [row[0] for row in cursor.fetchall()] # 获取最新的抓取时间 cursor.execute(""" SELECT crawl_time FROM crawl_records ORDER BY crawl_time DESC LIMIT 1 """) time_row = cursor.fetchone() crawl_time = time_row[0] if time_row else self._format_time_filename() return NewsData( date=crawl_date, crawl_time=crawl_time, items=final_items, id_to_name=id_to_name, failed_ids=failed_ids, ) except Exception as e: print(f"[存储] 读取数据失败: {e}") return None def _get_latest_crawl_data_impl(self, date: Optional[str] = None) -> Optional[NewsData]: try: conn = self._get_connection(date) cursor = conn.cursor() # 获取最新的抓取时间 cursor.execute(""" SELECT crawl_time FROM crawl_records ORDER BY crawl_time DESC LIMIT 1 """) time_row = cursor.fetchone() if not time_row: return None latest_time = time_row[0] # 获取该时间的新闻数据(包含 id 用于查询排名历史) cursor.execute(""" SELECT n.id, n.title, n.platform_id, p.name as platform_name, n.rank, n.url, n.mobile_url, n.first_crawl_time, n.last_crawl_time, n.crawl_count FROM news_items n LEFT JOIN platforms p ON n.platform_id = p.id WHERE n.last_crawl_time = ? """, (latest_time,)) rows = cursor.fetchall() if not rows: return None # 收集所有 news_item_id news_ids = [row[0] for row in rows] # 批量查询排名历史(同时获取时间和排名) # 过滤逻辑:只保留 last_crawl_time 之前的脱榜记录(rank=0) # 这样可以避免显示新闻永久脱榜后的无意义记录 rank_history_map: Dict[int, List[int]] = {} rank_timeline_map: Dict[int, List[Dict[str, Any]]] = {} if news_ids: placeholders = ",".join("?" * len(news_ids)) cursor.execute(f""" SELECT rh.news_item_id, rh.rank, rh.crawl_time FROM rank_history rh JOIN news_items ni ON rh.news_item_id = ni.id WHERE rh.news_item_id IN ({placeholders}) AND NOT (rh.rank = 0 AND rh.crawl_time > ni.last_crawl_time) ORDER BY rh.news_item_id, rh.crawl_time """, news_ids) for rh_row in cursor.fetchall(): news_id, rank, crawl_time = rh_row[0], rh_row[1], rh_row[2] # 构建 ranks 列表(去重,排除脱榜记录 rank=0) if news_id not in rank_history_map: rank_history_map[news_id] = [] if rank != 0 and rank not in rank_history_map[news_id]: rank_history_map[news_id].append(rank) # 构建 rank_timeline 列表(完整时间线,包含脱榜) if news_id not in rank_timeline_map: rank_timeline_map[news_id] = [] # 提取时间部分(HH:MM) time_part = crawl_time.split()[1][:5] if ' ' in crawl_time else crawl_time[:5] rank_timeline_map[news_id].append({ "time": time_part, "rank": rank if rank != 0 else None # 0 转为 None 表示脱榜 }) items: Dict[str, List[NewsItem]] = {} id_to_name: Dict[str, str] = {} crawl_date = self._format_date_folder(date) for row in rows: news_id = row[0] platform_id = row[2] platform_name = row[3] or platform_id id_to_name[platform_id] = platform_name if platform_id not in items: items[platform_id] = [] # 获取排名历史,如果没有则使用当前排名 ranks = rank_history_map.get(news_id, [row[4]]) rank_timeline = rank_timeline_map.get(news_id, []) items[platform_id].append(NewsItem( title=row[1], source_id=platform_id, source_name=platform_name, rank=row[4], url=row[5] or "", mobile_url=row[6] or "", crawl_time=row[8], # last_crawl_time ranks=ranks, first_time=row[7], # first_crawl_time last_time=row[8], # last_crawl_time count=row[9], # crawl_count rank_timeline=rank_timeline, )) # 获取失败的来源(针对最新一次抓取) cursor.execute(""" SELECT css.platform_id FROM crawl_source_status css JOIN crawl_records cr ON css.crawl_record_id = cr.id WHERE cr.crawl_time = ? AND css.status = 'failed' """, (latest_time,)) failed_ids = [row[0] for row in cursor.fetchall()] return NewsData( date=crawl_date, crawl_time=latest_time, items=items, id_to_name=id_to_name, failed_ids=failed_ids, ) except Exception as e: print(f"[存储] 获取最新数据失败: {e}") return None def _detect_new_titles_impl(self, current_data: NewsData) -> Dict[str, Dict]: try: # 获取历史数据 historical_data = self._get_today_all_data_impl(current_data.date) if not historical_data: # 没有历史数据,所有都是新的 new_titles = {} for source_id, news_list in current_data.items.items(): new_titles[source_id] = {item.title: item for item in news_list} return new_titles # 获取当前批次时间 current_time = current_data.crawl_time # 收集历史标题(first_time < current_time 的标题) # 这样可以正确处理同一标题因 URL 变化而产生多条记录的情况 historical_titles: Dict[str, set] = {} for source_id, news_list in historical_data.items.items(): historical_titles[source_id] = set() for item in news_list: first_time = item.first_time or item.crawl_time if first_time < current_time: historical_titles[source_id].add(item.title) # 检查是否有历史数据 has_historical_data = any(len(titles) > 0 for titles in historical_titles.values()) if not has_historical_data: # 第一次抓取,没有"新增"概念 return {} # 检测新增 new_titles = {} for source_id, news_list in current_data.items.items(): hist_set = historical_titles.get(source_id, set()) for item in news_list: if item.title not in hist_set: if source_id not in new_titles: new_titles[source_id] = {} new_titles[source_id][item.title] = item return new_titles except Exception as e: print(f"[存储] 检测新标题失败: {e}") return {} def _is_first_crawl_today_impl(self, date: Optional[str] = None) -> bool: try: conn = self._get_connection(date) cursor = conn.cursor() cursor.execute(""" SELECT COUNT(*) as count FROM crawl_records """) row = cursor.fetchone() count = row[0] if row else 0 # 如果只有一条或没有记录,视为第一次抓取 return count <= 1 except Exception as e: print(f"[存储] 检查首次抓取失败: {e}") return True def _get_crawl_times_impl(self, date: Optional[str] = None) -> List[str]: try: conn = self._get_connection(date) cursor = conn.cursor() cursor.execute(""" SELECT crawl_time FROM crawl_records ORDER BY crawl_time """) rows = cursor.fetchall() return [row[0] for row in rows] except Exception as e: print(f"[存储] 获取抓取时间列表失败: {e}") return [] # ======================================== # 时间段执行记录(调度系统) # ======================================== def _has_period_executed_impl(self, date_str: str, period_key: str, action: str) -> bool: try: conn = self._get_connection(date_str) cursor = conn.cursor() # 先检查表是否存在 cursor.execute(""" SELECT name FROM sqlite_master WHERE type='table' AND name='period_executions' """) if not cursor.fetchone(): return False cursor.execute(""" SELECT 1 FROM period_executions WHERE execution_date = ? AND period_key = ? AND action = ? """, (date_str, period_key, action)) return cursor.fetchone() is not None except Exception as e: print(f"[存储] 检查时间段执行记录失败: {e}") return False def _record_period_execution_impl(self, date_str: str, period_key: str, action: str) -> bool: try: conn = self._get_connection(date_str) cursor = conn.cursor() # 确保表存在 cursor.execute(""" CREATE TABLE IF NOT EXISTS period_executions ( id INTEGER PRIMARY KEY AUTOINCREMENT, execution_date TEXT NOT NULL, period_key TEXT NOT NULL, action TEXT NOT NULL, executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE(execution_date, period_key, action) ) """) now_str = self._get_configured_time().strftime("%Y-%m-%d %H:%M:%S") cursor.execute(""" INSERT OR IGNORE INTO period_executions (execution_date, period_key, action, executed_at) VALUES (?, ?, ?, ?) """, (date_str, period_key, action, now_str)) conn.commit() return True except Exception as e: print(f"[存储] 记录时间段执行失败: {e}") return False # ======================================== # RSS 数据存储 # ======================================== def _save_rss_data_impl(self, data: RSSData, log_prefix: str = "[存储]") -> tuple[bool, int, int]: try: conn = self._get_connection(data.date, db_type="rss") cursor = conn.cursor() now_str = self._get_configured_time().strftime("%Y-%m-%d %H:%M:%S") # 同步 RSS 源信息到 rss_feeds 表 for feed_id, feed_name in data.id_to_name.items(): cursor.execute(""" INSERT INTO rss_feeds (id, name, updated_at) VALUES (?, ?, ?) ON CONFLICT(id) DO UPDATE SET name = excluded.name, updated_at = excluded.updated_at """, (feed_id, feed_name, now_str)) # 统计计数器 new_count = 0 updated_count = 0 for feed_id, rss_list in data.items.items(): for item in rss_list: try: # 检查是否已存在(通过 URL + feed_id) if item.url: cursor.execute(""" SELECT id, title FROM rss_items WHERE url = ? AND feed_id = ? """, (item.url, feed_id)) existing = cursor.fetchone() if existing: # 已存在,更新记录 existing_id = existing[0] cursor.execute(""" UPDATE rss_items SET title = ?, published_at = ?, summary = ?, author = ?, last_crawl_time = ?, crawl_count = crawl_count + 1, updated_at = ? WHERE id = ? """, (item.title, item.published_at, item.summary, item.author, data.crawl_time, now_str, existing_id)) updated_count += 1 else: # 不存在,插入新记录(使用 ON CONFLICT 兜底处理并发/竞争场景) cursor.execute(""" INSERT INTO rss_items (title, feed_id, url, published_at, summary, author, first_crawl_time, last_crawl_time, crawl_count, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?) ON CONFLICT(url, feed_id) DO UPDATE SET title = excluded.title, published_at = excluded.published_at, summary = excluded.summary, author = excluded.author, last_crawl_time = excluded.last_crawl_time, crawl_count = crawl_count + 1, updated_at = excluded.updated_at """, (item.title, feed_id, item.url, item.published_at, item.summary, item.author, data.crawl_time, data.crawl_time, now_str, now_str)) new_count += 1 else: # URL 为空,用 try-except 处理重复 try: cursor.execute(""" INSERT INTO rss_items (title, feed_id, url, published_at, summary, author, first_crawl_time, last_crawl_time, crawl_count, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?) """, (item.title, feed_id, "", item.published_at, item.summary, item.author, data.crawl_time, data.crawl_time, now_str, now_str)) new_count += 1 except sqlite3.IntegrityError: # 重复的空 URL 条目,忽略 pass except sqlite3.Error as e: print(f"{log_prefix} 保存 RSS 条目失败 [{item.title[:30]}...]: {e}") total_items = new_count + updated_count # 记录抓取信息 cursor.execute(""" INSERT OR REPLACE INTO rss_crawl_records (crawl_time, total_items, created_at) VALUES (?, ?, ?) """, (data.crawl_time, total_items, now_str)) # 记录抓取状态 cursor.execute(""" SELECT id FROM rss_crawl_records WHERE crawl_time = ? """, (data.crawl_time,)) record_row = cursor.fetchone() if record_row: crawl_record_id = record_row[0] # 记录成功的源 for feed_id in data.items.keys(): cursor.execute(""" INSERT OR REPLACE INTO rss_crawl_status (crawl_record_id, feed_id, status) VALUES (?, ?, 'success') """, (crawl_record_id, feed_id)) # 记录失败的源 for failed_id in data.failed_ids: cursor.execute(""" INSERT OR IGNORE INTO rss_feeds (id, name, updated_at) VALUES (?, ?, ?) """, (failed_id, failed_id, now_str)) cursor.execute(""" INSERT OR REPLACE INTO rss_crawl_status (crawl_record_id, feed_id, status) VALUES (?, ?, 'failed') """, (crawl_record_id, failed_id)) conn.commit() return True, new_count, updated_count except Exception as e: print(f"{log_prefix} 保存 RSS 数据失败: {e}") return False, 0, 0 def _get_rss_data_impl(self, date: Optional[str] = None) -> Optional[RSSData]: try: conn = self._get_connection(date, db_type="rss") cursor = conn.cursor() # 获取所有 RSS 数据 cursor.execute(""" SELECT i.id, i.title, i.feed_id, f.name as feed_name, i.url, i.published_at, i.summary, i.author, i.first_crawl_time, i.last_crawl_time, i.crawl_count FROM rss_items i LEFT JOIN rss_feeds f ON i.feed_id = f.id ORDER BY i.published_at DESC """) rows = cursor.fetchall() if not rows: return None items: Dict[str, List[RSSItem]] = {} id_to_name: Dict[str, str] = {} crawl_date = self._format_date_folder(date) for row in rows: feed_id = row[2] feed_name = row[3] or feed_id id_to_name[feed_id] = feed_name if feed_id not in items: items[feed_id] = [] items[feed_id].append(RSSItem( title=row[1], feed_id=feed_id, feed_name=feed_name, url=row[4] or "", published_at=row[5] or "", summary=row[6] or "", author=row[7] or "", crawl_time=row[9], first_time=row[8], last_time=row[9], count=row[10], )) # 获取最新的抓取时间 cursor.execute(""" SELECT crawl_time FROM rss_crawl_records ORDER BY crawl_time DESC LIMIT 1 """) time_row = cursor.fetchone() crawl_time = time_row[0] if time_row else self._format_time_filename() # 获取失败的源 cursor.execute(""" SELECT DISTINCT cs.feed_id FROM rss_crawl_status cs JOIN rss_crawl_records cr ON cs.crawl_record_id = cr.id WHERE cs.status = 'failed' """) failed_ids = [row[0] for row in cursor.fetchall()] return RSSData( date=crawl_date, crawl_time=crawl_time, items=items, id_to_name=id_to_name, failed_ids=failed_ids, ) except Exception as e: print(f"[存储] 读取 RSS 数据失败: {e}") return None def _detect_new_rss_items_impl(self, current_data: RSSData) -> Dict[str, List[RSSItem]]: try: # 获取历史数据 historical_data = self._get_rss_data_impl(current_data.date) if not historical_data: # 没有历史数据,所有都是新的 return current_data.items.copy() # 获取当前批次时间 current_time = current_data.crawl_time # 收集历史 URL(first_time < current_time 的条目) historical_urls: Dict[str, set] = {} for feed_id, rss_list in historical_data.items.items(): historical_urls[feed_id] = set() for item in rss_list: first_time = item.first_time or item.crawl_time if first_time < current_time: if item.url: historical_urls[feed_id].add(item.url) # 检查是否有历史数据 has_historical_data = any(len(urls) > 0 for urls in historical_urls.values()) if not has_historical_data: # 第一次抓取,没有"新增"概念 return {} # 检测新增 new_items: Dict[str, List[RSSItem]] = {} for feed_id, rss_list in current_data.items.items(): hist_set = historical_urls.get(feed_id, set()) for item in rss_list: # 通过 URL 判断是否新增 if item.url and item.url not in hist_set: if feed_id not in new_items: new_items[feed_id] = [] new_items[feed_id].append(item) return new_items except Exception as e: print(f"[存储] 检测新 RSS 条目失败: {e}") return {} def _get_latest_rss_data_impl(self, date: Optional[str] = None) -> Optional[RSSData]: try: conn = self._get_connection(date, db_type="rss") cursor = conn.cursor() # 获取最新的抓取时间 cursor.execute(""" SELECT crawl_time FROM rss_crawl_records ORDER BY crawl_time DESC LIMIT 1 """) time_row = cursor.fetchone() if not time_row: return None latest_time = time_row[0] # 获取该时间的 RSS 数据 cursor.execute(""" SELECT i.id, i.title, i.feed_id, f.name as feed_name, i.url, i.published_at, i.summary, i.author, i.first_crawl_time, i.last_crawl_time, i.crawl_count FROM rss_items i LEFT JOIN rss_feeds f ON i.feed_id = f.id WHERE i.last_crawl_time = ? ORDER BY i.published_at DESC """, (latest_time,)) rows = cursor.fetchall() if not rows: return None items: Dict[str, List[RSSItem]] = {} id_to_name: Dict[str, str] = {} crawl_date = self._format_date_folder(date) for row in rows: feed_id = row[2] feed_name = row[3] or feed_id id_to_name[feed_id] = feed_name if feed_id not in items: items[feed_id] = [] items[feed_id].append(RSSItem( title=row[1], feed_id=feed_id, feed_name=feed_name, url=row[4] or "", published_at=row[5] or "", summary=row[6] or "", author=row[7] or "", crawl_time=row[9], first_time=row[8], last_time=row[9], count=row[10], )) # 获取失败的源(针对最新一次抓取) cursor.execute(""" SELECT cs.feed_id FROM rss_crawl_status cs JOIN rss_crawl_records cr ON cs.crawl_record_id = cr.id WHERE cr.crawl_time = ? AND cs.status = 'failed' """, (latest_time,)) failed_ids = [row[0] for row in cursor.fetchall()] return RSSData( date=crawl_date, crawl_time=latest_time, items=items, id_to_name=id_to_name, failed_ids=failed_ids, ) except Exception as e: print(f"[存储] 获取最新 RSS 数据失败: {e}") return None # ======================================== # AI 智能筛选 - 标签管理 # ======================================== def _get_active_tags_impl(self, date: Optional[str] = None, interests_file: str = "ai_interests.txt") -> List[Dict[str, Any]]: try: conn = self._get_connection(date) cursor = conn.cursor() cursor.execute(""" SELECT id, tag, description, version, prompt_hash, priority FROM ai_filter_tags WHERE status = 'active' AND interests_file = ? ORDER BY priority ASC, id ASC """, (interests_file,)) return [ { "id": row[0], "tag": row[1], "description": row[2], "version": row[3], "prompt_hash": row[4], "priority": row[5], } for row in cursor.fetchall() ] except Exception as e: print(f"[AI筛选] 获取标签失败: {e}") return [] def _get_latest_prompt_hash_impl(self, date: Optional[str] = None, interests_file: str = "ai_interests.txt") -> Optional[str]: try: conn = self._get_connection(date) cursor = conn.cursor() cursor.execute(""" SELECT prompt_hash FROM ai_filter_tags WHERE status = 'active' AND interests_file = ? ORDER BY version DESC LIMIT 1 """, (interests_file,)) row = cursor.fetchone() return row[0] if row else None except Exception as e: print(f"[AI筛选] 获取 prompt_hash 失败: {e}") return None def _get_latest_tag_version_impl(self, date: Optional[str] = None) -> int: try: conn = self._get_connection(date) cursor = conn.cursor() cursor.execute(""" SELECT MAX(version) FROM ai_filter_tags """) row = cursor.fetchone() return row[0] if row and row[0] is not None else 0 except Exception as e: print(f"[AI筛选] 获取版本号失败: {e}") return 0 def _deprecate_all_tags_impl(self, date: Optional[str] = None, interests_file: str = "ai_interests.txt") -> int: try: conn = self._get_connection(date) cursor = conn.cursor() now_str = self._get_configured_time().strftime("%Y-%m-%d %H:%M:%S") # 获取该兴趣文件的 active 标签 id cursor.execute( "SELECT id FROM ai_filter_tags WHERE status = 'active' AND interests_file = ?", (interests_file,) ) tag_ids = [row[0] for row in cursor.fetchall()] if not tag_ids: return 0 # 废弃标签 placeholders = ",".join("?" * len(tag_ids)) cursor.execute(f""" UPDATE ai_filter_tags SET status = 'deprecated', deprecated_at = ? WHERE id IN ({placeholders}) """, [now_str] + tag_ids) tag_count = cursor.rowcount # 废弃关联的分类结果 placeholders = ",".join("?" * len(tag_ids)) cursor.execute(f""" UPDATE ai_filter_results SET status = 'deprecated', deprecated_at = ? WHERE tag_id IN ({placeholders}) AND status = 'active' """, [now_str] + tag_ids) conn.commit() print(f"[AI筛选] 已废弃 {tag_count} 个标签及关联分类结果") return tag_count except Exception as e: print(f"[AI筛选] 废弃标签失败: {e}") return 0 def _save_tags_impl( self, date: Optional[str], tags: List[Dict], version: int, prompt_hash: str, interests_file: str = "ai_interests.txt" ) -> int: try: conn = self._get_connection(date) cursor = conn.cursor() now_str = self._get_configured_time().strftime("%Y-%m-%d %H:%M:%S") count = 0 for idx, tag_data in enumerate(tags, start=1): priority = tag_data.get("priority", idx) try: priority = int(priority) except (TypeError, ValueError): priority = idx cursor.execute(""" INSERT INTO ai_filter_tags (tag, description, priority, version, prompt_hash, interests_file, created_at) VALUES (?, ?, ?, ?, ?, ?, ?) """, ( tag_data["tag"], tag_data.get("description", ""), priority, version, prompt_hash, interests_file, now_str, )) count += 1 conn.commit() return count except Exception as e: print(f"[AI筛选] 保存标签失败: {e}") return 0 def _deprecate_specific_tags_impl( self, date: Optional[str], tag_ids: List[int] ) -> int: if not tag_ids: return 0 try: conn = self._get_connection(date) cursor = conn.cursor() now_str = self._get_configured_time().strftime("%Y-%m-%d %H:%M:%S") placeholders = ",".join("?" * len(tag_ids)) cursor.execute(f""" UPDATE ai_filter_tags SET status = 'deprecated', deprecated_at = ? WHERE id IN ({placeholders}) """, [now_str] + tag_ids) tag_count = cursor.rowcount cursor.execute(f""" UPDATE ai_filter_results SET status = 'deprecated', deprecated_at = ? WHERE tag_id IN ({placeholders}) AND status = 'active' """, [now_str] + tag_ids) conn.commit() return tag_count except Exception as e: print(f"[AI筛选] 废弃指定标签失败: {e}") return 0 def _update_tags_hash_impl( self, date: Optional[str], interests_file: str, new_hash: str ) -> int: try: conn = self._get_connection(date) cursor = conn.cursor() cursor.execute(""" UPDATE ai_filter_tags SET prompt_hash = ? WHERE interests_file = ? AND status = 'active' """, (new_hash, interests_file)) count = cursor.rowcount conn.commit() return count except Exception as e: print(f"[AI筛选] 更新标签 hash 失败: {e}") return 0 # ======================================== # AI 智能筛选 - 分类结果管理 # ======================================== def _update_tag_descriptions_impl( self, date: Optional[str], tag_updates: List[Dict], interests_file: str = "ai_interests.txt" ) -> int: try: conn = self._get_connection(date) cursor = conn.cursor() count = 0 for t in tag_updates: tag_name = t.get("tag", "") description = t.get("description", "") if not tag_name: continue cursor.execute(""" UPDATE ai_filter_tags SET description = ? WHERE tag = ? AND interests_file = ? AND status = 'active' """, (description, tag_name, interests_file)) count += cursor.rowcount conn.commit() return count except Exception as e: print(f"[AI筛选] 更新标签描述失败: {e}") return 0 def _update_tag_priorities_impl( self, date: Optional[str], tag_priorities: List[Dict], interests_file: str = "ai_interests.txt" ) -> int: try: conn = self._get_connection(date) cursor = conn.cursor() count = 0 for t in tag_priorities: tag_name = t.get("tag", "") priority = t.get("priority") if not tag_name: continue try: priority = int(priority) except (TypeError, ValueError): continue cursor.execute(""" UPDATE ai_filter_tags SET priority = ? WHERE tag = ? AND interests_file = ? AND status = 'active' """, (priority, tag_name, interests_file)) count += cursor.rowcount conn.commit() return count except Exception as e: print(f"[AI筛选] 更新标签优先级失败: {e}") return 0 # ======================================== # AI 智能筛选 - 已分析新闻追踪 # ======================================== def _save_analyzed_news_impl( self, date: Optional[str], news_ids: List[int], source_type: str, interests_file: str, prompt_hash: str, matched_ids: set ) -> int: try: conn = self._get_connection(date) cursor = conn.cursor() now_str = self._get_configured_time().strftime("%Y-%m-%d %H:%M:%S") count = 0 for nid in news_ids: try: cursor.execute(""" INSERT OR REPLACE INTO ai_filter_analyzed_news (news_item_id, source_type, interests_file, prompt_hash, matched, created_at) VALUES (?, ?, ?, ?, ?, ?) """, ( nid, source_type, interests_file, prompt_hash, 1 if nid in matched_ids else 0, now_str, )) count += 1 except Exception: pass conn.commit() return count except Exception as e: print(f"[AI筛选] 保存已分析记录失败: {e}") return 0 def _get_analyzed_news_ids_impl( self, date: Optional[str] = None, source_type: str = "hotlist", interests_file: str = "ai_interests.txt" ) -> set: try: conn = self._get_connection(date) cursor = conn.cursor() cursor.execute(""" SELECT news_item_id FROM ai_filter_analyzed_news WHERE source_type = ? AND interests_file = ? """, (source_type, interests_file)) return {row[0] for row in cursor.fetchall()} except Exception as e: print(f"[AI筛选] 获取已分析ID失败: {e}") return set() def _clear_analyzed_news_impl( self, date: Optional[str] = None, interests_file: str = "ai_interests.txt" ) -> int: try: conn = self._get_connection(date) cursor = conn.cursor() cursor.execute(""" DELETE FROM ai_filter_analyzed_news WHERE interests_file = ? """, (interests_file,)) count = cursor.rowcount conn.commit() return count except Exception as e: print(f"[AI筛选] 清除已分析记录失败: {e}") return 0 def _clear_unmatched_analyzed_news_impl( self, date: Optional[str] = None, interests_file: str = "ai_interests.txt" ) -> int: try: conn = self._get_connection(date) cursor = conn.cursor() cursor.execute(""" DELETE FROM ai_filter_analyzed_news WHERE interests_file = ? AND matched = 0 """, (interests_file,)) count = cursor.rowcount conn.commit() return count except Exception as e: print(f"[AI筛选] 清除不匹配记录失败: {e}") return 0 # ======================================== # AI 智能筛选 - 分类结果管理(原有) # ======================================== def _save_filter_results_impl( self, date: Optional[str], results: List[Dict] ) -> int: try: conn = self._get_connection(date) cursor = conn.cursor() now_str = self._get_configured_time().strftime("%Y-%m-%d %H:%M:%S") count = 0 for r in results: try: cursor.execute(""" INSERT INTO ai_filter_results (news_item_id, source_type, tag_id, relevance_score, created_at) VALUES (?, ?, ?, ?, ?) """, ( r["news_item_id"], r.get("source_type", "hotlist"), r["tag_id"], r.get("relevance_score", 0.0), now_str, )) count += 1 except sqlite3.IntegrityError: pass # 重复记录,跳过 conn.commit() return count except Exception as e: print(f"[AI筛选] 保存分类结果失败: {e}") return 0 def _get_active_filter_results_impl(self, date: Optional[str] = None, interests_file: str = "ai_interests.txt") -> List[Dict[str, Any]]: try: conn = self._get_connection(date) cursor = conn.cursor() # 热榜结果 cursor.execute(""" SELECT r.news_item_id, r.source_type, r.tag_id, r.relevance_score, t.tag, t.description as tag_description, t.priority, n.title, n.platform_id as source_id, p.name as source_name, n.url, n.mobile_url, n.rank, n.first_crawl_time, n.last_crawl_time, n.crawl_count FROM ai_filter_results r JOIN ai_filter_tags t ON r.tag_id = t.id JOIN news_items n ON r.news_item_id = n.id LEFT JOIN platforms p ON n.platform_id = p.id WHERE r.status = 'active' AND r.source_type = 'hotlist' AND t.status = 'active' AND t.interests_file = ? ORDER BY t.priority ASC, t.id ASC, r.relevance_score DESC """, (interests_file,)) results = [] hotlist_news_ids = [] for row in cursor.fetchall(): results.append({ "news_item_id": row[0], "source_type": row[1], "tag_id": row[2], "relevance_score": row[3], "tag": row[4], "tag_description": row[5], "tag_priority": row[6], "title": row[7], "source_id": row[8], "source_name": row[9] or row[8], "url": row[10] or "", "mobile_url": row[11] or "", "rank": row[12], "first_time": row[13], "last_time": row[14], "count": row[15], }) hotlist_news_ids.append(row[0]) # 批量查排名历史(热榜) ranks_map: Dict[int, List[int]] = {} if hotlist_news_ids: unique_ids = list(set(hotlist_news_ids)) placeholders = ",".join("?" * len(unique_ids)) cursor.execute(f""" SELECT news_item_id, rank FROM rank_history WHERE news_item_id IN ({placeholders}) AND rank != 0 """, unique_ids) for rh_row in cursor.fetchall(): nid, rank = rh_row[0], rh_row[1] if nid not in ranks_map: ranks_map[nid] = [] if rank not in ranks_map[nid]: ranks_map[nid].append(rank) for item in results: item["ranks"] = ranks_map.get(item["news_item_id"], [item["rank"]]) # RSS 结果(如果有 rss 库) try: rss_conn = self._get_connection(date, db_type="rss") rss_cursor = rss_conn.cursor() # 从 news 库获取 rss 类型的分类结果 ID cursor.execute(""" SELECT r.news_item_id, r.tag_id, r.relevance_score, t.tag, t.description, t.priority FROM ai_filter_results r JOIN ai_filter_tags t ON r.tag_id = t.id WHERE r.status = 'active' AND r.source_type = 'rss' AND t.status = 'active' AND t.interests_file = ? ORDER BY t.priority ASC, t.id ASC, r.relevance_score DESC """, (interests_file,)) rss_filter_rows = cursor.fetchall() if rss_filter_rows: rss_ids = [row[0] for row in rss_filter_rows] placeholders = ",".join("?" * len(rss_ids)) rss_cursor.execute(f""" SELECT i.id, i.title, i.feed_id, f.name as feed_name, i.url, i.published_at FROM rss_items i LEFT JOIN rss_feeds f ON i.feed_id = f.id WHERE i.id IN ({placeholders}) """, rss_ids) rss_info = {row[0]: row for row in rss_cursor.fetchall()} for fr_row in rss_filter_rows: rss_id = fr_row[0] info = rss_info.get(rss_id) if info: results.append({ "news_item_id": rss_id, "source_type": "rss", "tag_id": fr_row[1], "relevance_score": fr_row[2], "tag": fr_row[3], "tag_description": fr_row[4], "tag_priority": fr_row[5], "title": info[1], "source_id": info[2], "source_name": info[3] or info[2], "url": info[4] or "", "mobile_url": "", "rank": 0, "ranks": [], "first_time": info[5] or "", "last_time": info[5] or "", "count": 1, }) except Exception: pass # RSS 库不存在时静默跳过 return results except Exception as e: print(f"[AI筛选] 获取分类结果失败: {e}") return [] def _get_all_news_ids_impl(self, date: Optional[str] = None) -> List[Dict]: try: conn = self._get_connection(date) cursor = conn.cursor() cursor.execute(""" SELECT n.id, n.title, n.platform_id, p.name as platform_name FROM news_items n LEFT JOIN platforms p ON n.platform_id = p.id ORDER BY n.id """) return [ { "id": row[0], "title": row[1], "source_id": row[2], "source_name": row[3] or row[2], } for row in cursor.fetchall() ] except Exception as e: print(f"[AI筛选] 获取新闻列表失败: {e}") return [] def _get_all_rss_ids_impl(self, date: Optional[str] = None) -> List[Dict]: try: conn = self._get_connection(date, db_type="rss") cursor = conn.cursor() cursor.execute(""" SELECT i.id, i.title, i.feed_id, f.name as feed_name, i.published_at FROM rss_items i LEFT JOIN rss_feeds f ON i.feed_id = f.id ORDER BY i.id """) return [ { "id": row[0], "title": row[1], "source_id": row[2], "source_name": row[3] or row[2], "published_at": row[4] or "", } for row in cursor.fetchall() ] except Exception as e: print(f"[AI筛选] 获取 RSS 列表失败: {e}") return []
--- +++ @@ -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, db_type) -> sqlite3.Connection + - _get_configured_time() -> datetime + - _format_date_folder(date) -> str + - _format_time_filename() -> str + """ # ======================================== # 抽象方法 - 子类必须实现 @@ -18,18 +32,22 @@ @abstractmethod def _get_connection(self, date: Optional[str] = None, db_type: str = "news") -> sqlite3.Connection: + """获取数据库连接""" pass @abstractmethod def _get_configured_time(self) -> datetime: + """获取配置时区的当前时间""" pass @abstractmethod def _format_date_folder(self, date: Optional[str] = None) -> str: + """格式化日期文件夹名 (ISO 格式: YYYY-MM-DD)""" pass @abstractmethod def _format_time_filename(self) -> str: + """格式化时间文件名 (格式: HH-MM)""" pass # ======================================== @@ -37,14 +55,31 @@ # ======================================== def _get_schema_path(self, db_type: str = "news") -> Path: + """ + 获取 schema.sql 文件路径 + + Args: + db_type: 数据库类型 ("news" 或 "rss") + + Returns: + schema 文件路径 + """ if db_type == "rss": return Path(__file__).parent / "rss_schema.sql" return Path(__file__).parent / "schema.sql" def _get_ai_filter_schema_path(self) -> Path: + """获取 AI 筛选 schema 文件路径""" return Path(__file__).parent / "ai_filter_schema.sql" def _init_tables(self, conn: sqlite3.Connection, db_type: str = "news") -> None: + """ + 从 schema.sql 初始化数据库表结构 + + Args: + conn: 数据库连接 + db_type: 数据库类型 ("news" 或 "rss") + """ schema_path = self._get_schema_path(db_type) if schema_path.exists(): @@ -68,6 +103,16 @@ # ======================================== def _save_news_data_impl(self, data: NewsData, log_prefix: str = "[存储]") -> tuple[bool, int, int, int, int]: + """ + 保存新闻数据到 SQLite(核心实现) + + Args: + data: 新闻数据 + log_prefix: 日志前缀 + + Returns: + (success, new_count, updated_count, title_changed_count, off_list_count) + """ try: conn = self._get_connection(data.date) cursor = conn.cursor() @@ -277,6 +322,15 @@ return False, 0, 0, 0, 0 def _get_today_all_data_impl(self, date: Optional[str] = None) -> Optional[NewsData]: + """ + 获取指定日期的所有新闻数据(合并后) + + Args: + date: 日期字符串,默认为今天 + + Returns: + 合并后的新闻数据 + """ try: conn = self._get_connection(date) cursor = conn.cursor() @@ -401,6 +455,15 @@ return None def _get_latest_crawl_data_impl(self, date: Optional[str] = None) -> Optional[NewsData]: + """ + 获取最新一次抓取的数据 + + Args: + date: 日期字符串,默认为今天 + + Returns: + 最新抓取的新闻数据 + """ try: conn = self._get_connection(date) cursor = conn.cursor() @@ -524,6 +587,18 @@ return None def _detect_new_titles_impl(self, current_data: NewsData) -> Dict[str, Dict]: + """ + 检测新增的标题 + + 该方法比较当前抓取数据与历史数据,找出新增的标题。 + 关键逻辑:只有在历史批次中从未出现过的标题才算新增。 + + Args: + current_data: 当前抓取的数据 + + Returns: + 新增的标题数据 {source_id: {title: NewsItem}} + """ try: # 获取历史数据 historical_data = self._get_today_all_data_impl(current_data.date) @@ -571,6 +646,15 @@ return {} def _is_first_crawl_today_impl(self, date: Optional[str] = None) -> bool: + """ + 检查是否是当天第一次抓取 + + Args: + date: 日期字符串,默认为今天 + + Returns: + 是否是第一次抓取 + """ try: conn = self._get_connection(date) cursor = conn.cursor() @@ -590,6 +674,15 @@ return True def _get_crawl_times_impl(self, date: Optional[str] = None) -> List[str]: + """ + 获取指定日期的所有抓取时间列表 + + Args: + date: 日期字符串,默认为今天 + + Returns: + 抓取时间列表(按时间排序) + """ try: conn = self._get_connection(date) cursor = conn.cursor() @@ -611,6 +704,17 @@ # ======================================== def _has_period_executed_impl(self, date_str: str, period_key: str, action: str) -> bool: + """ + 检查指定时间段的某个 action 今天是否已执行 + + Args: + date_str: 日期字符串 YYYY-MM-DD + period_key: 时间段 key + action: 动作类型 (analyze / push) + + Returns: + 是否已执行 + """ try: conn = self._get_connection(date_str) cursor = conn.cursor() @@ -635,6 +739,17 @@ return False def _record_period_execution_impl(self, date_str: str, period_key: str, action: str) -> bool: + """ + 记录时间段的 action 执行 + + Args: + date_str: 日期字符串 YYYY-MM-DD + period_key: 时间段 key + action: 动作类型 (analyze / push) + + Returns: + 是否记录成功 + """ try: conn = self._get_connection(date_str) cursor = conn.cursor() @@ -670,6 +785,16 @@ # ======================================== def _save_rss_data_impl(self, data: RSSData, log_prefix: str = "[存储]") -> tuple[bool, int, int]: + """ + 保存 RSS 数据到 SQLite(以 URL 为唯一标识) + + Args: + data: RSS 数据 + log_prefix: 日志前缀 + + Returns: + (success, new_count, updated_count) + """ try: conn = self._get_connection(data.date, db_type="rss") cursor = conn.cursor() @@ -804,6 +929,15 @@ return False, 0, 0 def _get_rss_data_impl(self, date: Optional[str] = None) -> Optional[RSSData]: + """ + 获取指定日期的所有 RSS 数据 + + Args: + date: 日期字符串(YYYY-MM-DD),默认为今天 + + Returns: + RSSData 对象,如果没有数据返回 None + """ try: conn = self._get_connection(date, db_type="rss") cursor = conn.cursor() @@ -880,6 +1014,18 @@ return None def _detect_new_rss_items_impl(self, current_data: RSSData) -> Dict[str, List[RSSItem]]: + """ + 检测新增的 RSS 条目(增量模式) + + 该方法比较当前抓取数据与历史数据,找出新增的 RSS 条目。 + 关键逻辑:只有在历史批次中从未出现过的 URL 才算新增。 + + Args: + current_data: 当前抓取的 RSS 数据 + + Returns: + 新增的 RSS 条目 {feed_id: [RSSItem, ...]} + """ try: # 获取历史数据 historical_data = self._get_rss_data_impl(current_data.date) @@ -925,6 +1071,15 @@ return {} def _get_latest_rss_data_impl(self, date: Optional[str] = None) -> Optional[RSSData]: + """ + 获取最新一次抓取的 RSS 数据(当前榜单模式) + + Args: + date: 日期字符串(YYYY-MM-DD),默认为今天 + + Returns: + 最新抓取的 RSS 数据,如果没有数据返回 None + """ try: conn = self._get_connection(date, db_type="rss") cursor = conn.cursor() @@ -1011,6 +1166,7 @@ # ======================================== def _get_active_tags_impl(self, date: Optional[str] = None, interests_file: str = "ai_interests.txt") -> List[Dict[str, Any]]: + """获取指定兴趣文件的 active 标签列表""" try: conn = self._get_connection(date) cursor = conn.cursor() @@ -1034,6 +1190,7 @@ return [] def _get_latest_prompt_hash_impl(self, date: Optional[str] = None, interests_file: str = "ai_interests.txt") -> Optional[str]: + """获取指定兴趣文件最新版本标签的 prompt_hash""" try: conn = self._get_connection(date) cursor = conn.cursor() @@ -1051,6 +1208,7 @@ return None def _get_latest_tag_version_impl(self, date: Optional[str] = None) -> int: + """获取最新版本号""" try: conn = self._get_connection(date) cursor = conn.cursor() @@ -1065,6 +1223,7 @@ return 0 def _deprecate_all_tags_impl(self, date: Optional[str] = None, interests_file: str = "ai_interests.txt") -> int: + """将指定兴趣文件的 active 标签和关联的分类结果标记为 deprecated""" try: conn = self._get_connection(date) cursor = conn.cursor() @@ -1108,6 +1267,7 @@ self, date: Optional[str], tags: List[Dict], version: int, prompt_hash: str, interests_file: str = "ai_interests.txt" ) -> int: + """保存新提取的标签""" try: conn = self._get_connection(date) cursor = conn.cursor() @@ -1144,6 +1304,7 @@ def _deprecate_specific_tags_impl( self, date: Optional[str], tag_ids: List[int] ) -> int: + """废弃指定 ID 的标签及其关联分类结果(增量更新时使用)""" if not tag_ids: return 0 try: @@ -1175,6 +1336,7 @@ def _update_tags_hash_impl( self, date: Optional[str], interests_file: str, new_hash: str ) -> int: + """更新指定兴趣文件所有 active 标签的 prompt_hash(增量更新时使用)""" try: conn = self._get_connection(date) cursor = conn.cursor() @@ -1200,6 +1362,7 @@ self, date: Optional[str], tag_updates: List[Dict], interests_file: str = "ai_interests.txt" ) -> int: + """按 tag 名匹配,更新 active 标签的 description 字段""" try: conn = self._get_connection(date) cursor = conn.cursor() @@ -1227,6 +1390,7 @@ self, date: Optional[str], tag_priorities: List[Dict], interests_file: str = "ai_interests.txt" ) -> int: + """按 tag 名匹配,更新 active 标签的 priority 字段""" try: conn = self._get_connection(date) cursor = conn.cursor() @@ -1262,6 +1426,7 @@ self, date: Optional[str], news_ids: List[int], source_type: str, interests_file: str, prompt_hash: str, matched_ids: set ) -> int: + """批量记录已分析的新闻(匹配与不匹配都记录)""" try: conn = self._get_connection(date) cursor = conn.cursor() @@ -1293,6 +1458,7 @@ self, date: Optional[str] = None, source_type: str = "hotlist", interests_file: str = "ai_interests.txt" ) -> set: + """获取已分析过的新闻 ID 集合(用于去重)""" try: conn = self._get_connection(date) cursor = conn.cursor() @@ -1310,6 +1476,7 @@ def _clear_analyzed_news_impl( self, date: Optional[str] = None, interests_file: str = "ai_interests.txt" ) -> int: + """清除指定兴趣文件的所有已分析记录(全量重分类时使用)""" try: conn = self._get_connection(date) cursor = conn.cursor() @@ -1329,6 +1496,7 @@ def _clear_unmatched_analyzed_news_impl( self, date: Optional[str] = None, interests_file: str = "ai_interests.txt" ) -> int: + """清除不匹配的已分析记录,让这些新闻有机会被新标签重新分析""" try: conn = self._get_connection(date) cursor = conn.cursor() @@ -1352,6 +1520,7 @@ def _save_filter_results_impl( self, date: Optional[str], results: List[Dict] ) -> int: + """批量保存分类结果""" try: conn = self._get_connection(date) cursor = conn.cursor() @@ -1382,6 +1551,7 @@ return 0 def _get_active_filter_results_impl(self, date: Optional[str] = None, interests_file: str = "ai_interests.txt") -> List[Dict[str, Any]]: + """获取指定兴趣文件的 active 分类结果,JOIN news_items 获取新闻详情""" try: conn = self._get_connection(date) cursor = conn.cursor() @@ -1500,6 +1670,7 @@ return [] def _get_all_news_ids_impl(self, date: Optional[str] = None) -> List[Dict]: + """获取当日所有新闻的 id 和标题(用于 AI 筛选分类)""" try: conn = self._get_connection(date) cursor = conn.cursor() @@ -1523,6 +1694,7 @@ return [] def _get_all_rss_ids_impl(self, date: Optional[str] = None) -> List[Dict]: + """获取当日所有 RSS 条目的 id 和标题(用于 AI 筛选分类)""" try: conn = self._get_connection(date, db_type="rss") cursor = conn.cursor() @@ -1544,4 +1716,4 @@ ] except Exception as e: print(f"[AI筛选] 获取 RSS 列表失败: {e}") - return []+ return []
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 from urllib.parse import urlparse from timm.models.hub import download_cached_file class BLIP_Base(nn.Module): def __init__(self, med_config = 'configs/med_config.json', image_size = 224, vit = 'base', vit_grad_ckpt = False, vit_ckpt_layer = 0, ): super().__init__() self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer) self.tokenizer = init_tokenizer() med_config = BertConfig.from_json_file(med_config) med_config.encoder_width = vision_width self.text_encoder = BertModel(config=med_config, add_pooling_layer=False) def forward(self, image, caption, mode): assert mode in ['image', 'text', 'multimodal'], "mode parameter must be image, text, or multimodal" text = self.tokenizer(caption, return_tensors="pt").to(image.device) if mode=='image': # return image features image_embeds = self.visual_encoder(image) return image_embeds elif mode=='text': # return text features text_output = self.text_encoder(text.input_ids, attention_mask = text.attention_mask, return_dict = True, mode = 'text') return text_output.last_hidden_state elif mode=='multimodal': # return multimodel features image_embeds = self.visual_encoder(image) image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device) text.input_ids[:,0] = self.tokenizer.enc_token_id output = self.text_encoder(text.input_ids, attention_mask = text.attention_mask, encoder_hidden_states = image_embeds, encoder_attention_mask = image_atts, return_dict = True, ) return output.last_hidden_state class BLIP_Decoder(nn.Module): def __init__(self, med_config = 'configs/med_config.json', image_size = 384, vit = 'base', vit_grad_ckpt = False, vit_ckpt_layer = 0, prompt = 'a picture of ', ): super().__init__() self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer) self.tokenizer = init_tokenizer() med_config = BertConfig.from_json_file(med_config) med_config.encoder_width = vision_width self.text_decoder = BertLMHeadModel(config=med_config) self.prompt = prompt self.prompt_length = len(self.tokenizer(self.prompt).input_ids)-1 def forward(self, image, caption): image_embeds = self.visual_encoder(image) image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device) text = self.tokenizer(caption, padding='longest', truncation=True, max_length=40, return_tensors="pt").to(image.device) text.input_ids[:,0] = self.tokenizer.bos_token_id decoder_targets = text.input_ids.masked_fill(text.input_ids == self.tokenizer.pad_token_id, -100) decoder_targets[:,:self.prompt_length] = -100 decoder_output = self.text_decoder(text.input_ids, attention_mask = text.attention_mask, encoder_hidden_states = image_embeds, encoder_attention_mask = image_atts, labels = decoder_targets, return_dict = True, ) loss_lm = decoder_output.loss return loss_lm def generate(self, image, sample=False, num_beams=3, max_length=30, min_length=10, top_p=0.9, repetition_penalty=1.0): image_embeds = self.visual_encoder(image) if not sample: image_embeds = image_embeds.repeat_interleave(num_beams,dim=0) image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device) model_kwargs = {"encoder_hidden_states": image_embeds, "encoder_attention_mask":image_atts} prompt = [self.prompt] * image.size(0) input_ids = self.tokenizer(prompt, return_tensors="pt").input_ids.to(image.device) input_ids[:,0] = self.tokenizer.bos_token_id input_ids = input_ids[:, :-1] if sample: #nucleus sampling outputs = self.text_decoder.generate(input_ids=input_ids, max_length=max_length, min_length=min_length, do_sample=True, top_p=top_p, num_return_sequences=1, eos_token_id=self.tokenizer.sep_token_id, pad_token_id=self.tokenizer.pad_token_id, repetition_penalty=1.1, **model_kwargs) else: #beam search outputs = self.text_decoder.generate(input_ids=input_ids, max_length=max_length, min_length=min_length, num_beams=num_beams, eos_token_id=self.tokenizer.sep_token_id, pad_token_id=self.tokenizer.pad_token_id, repetition_penalty=repetition_penalty, **model_kwargs) captions = [] for output in outputs: caption = self.tokenizer.decode(output, skip_special_tokens=True) captions.append(caption[len(self.prompt):]) return captions def blip_decoder(pretrained='',**kwargs): model = BLIP_Decoder(**kwargs) if pretrained: model,msg = load_checkpoint(model,pretrained) assert(len(msg.missing_keys)==0) return model def blip_feature_extractor(pretrained='',**kwargs): model = BLIP_Base(**kwargs) if pretrained: model,msg = load_checkpoint(model,pretrained) assert(len(msg.missing_keys)==0) return model def init_tokenizer(): tokenizer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "bert_tokenizer") tokenizer = BertTokenizer.from_pretrained(tokenizer_path) tokenizer.add_special_tokens({'bos_token':'[DEC]'}) tokenizer.add_special_tokens({'additional_special_tokens':['[ENC]']}) tokenizer.enc_token_id = tokenizer.additional_special_tokens_ids[0] return tokenizer def create_vit(vit, image_size, use_grad_checkpointing=False, ckpt_layer=0, drop_path_rate=0): assert vit in ['base', 'large'], "vit parameter must be base or large" if vit=='base': vision_width = 768 visual_encoder = VisionTransformer(img_size=image_size, patch_size=16, embed_dim=vision_width, depth=12, num_heads=12, use_grad_checkpointing=use_grad_checkpointing, ckpt_layer=ckpt_layer, drop_path_rate=0 or drop_path_rate ) elif vit=='large': vision_width = 1024 visual_encoder = VisionTransformer(img_size=image_size, patch_size=16, embed_dim=vision_width, depth=24, num_heads=16, use_grad_checkpointing=use_grad_checkpointing, ckpt_layer=ckpt_layer, drop_path_rate=0.1 or drop_path_rate ) return visual_encoder, vision_width def is_url(url_or_filename): parsed = urlparse(url_or_filename) return parsed.scheme in ("http", "https") def load_checkpoint(model,url_or_filename): if is_url(url_or_filename): cached_file = download_cached_file(url_or_filename, check_hash=False, progress=True) checkpoint = torch.load(cached_file, map_location='cpu', weights_only=True) elif os.path.isfile(url_or_filename): checkpoint = torch.load(url_or_filename, map_location='cpu', weights_only=True) else: raise RuntimeError('checkpoint url or path is invalid') state_dict = checkpoint['model'] state_dict['visual_encoder.pos_embed'] = interpolate_pos_embed(state_dict['visual_encoder.pos_embed'],model.visual_encoder) if 'visual_encoder_m.pos_embed' in model.state_dict().keys(): state_dict['visual_encoder_m.pos_embed'] = interpolate_pos_embed(state_dict['visual_encoder_m.pos_embed'], model.visual_encoder_m) for key in model.state_dict().keys(): if key in state_dict.keys(): if state_dict[key].shape!=model.state_dict()[key].shape: del state_dict[key] msg = model.load_state_dict(state_dict,strict=False) print('load checkpoint from %s'%url_or_filename) return model,msg
--- +++ @@ -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("ignore") @@ -21,6 +28,12 @@ vit_grad_ckpt = False, vit_ckpt_layer = 0, ): + """ + Args: + med_config (str): path for the mixture of encoder-decoder model's configuration file + image_size (int): input image size + vit (str): model size of vision transformer + """ super().__init__() self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer) @@ -71,6 +84,12 @@ vit_ckpt_layer = 0, prompt = 'a picture of ', ): + """ + Args: + med_config (str): path for the mixture of encoder-decoder model's configuration file + image_size (int): input image size + vit (str): model size of vision transformer + """ super().__init__() self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer) @@ -217,4 +236,4 @@ msg = model.load_state_dict(state_dict,strict=False) print('load checkpoint from %s'%url_or_filename) return model,msg - +
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 是时间范围参数 # 示例:https://s.weibo.com/weibo?q=xxx&t=31&band_rank=1&Refer=top # 保留:q(关键词) # 移除:band_rank, Refer, t "weibo": {"band_rank", "Refer", "t"}, } # 通用追踪参数(适用于所有平台) # 这些参数通常由分享链接或广告追踪添加,不影响内容识别 COMMON_TRACKING_PARAMS: Set[str] = { # UTM 追踪参数 "utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", # 常见追踪参数 "ref", "referrer", "source", "channel", # 时间戳和随机参数 "_t", "timestamp", "_", "random", # 分享相关 "share_token", "share_id", "share_from", } def normalize_url(url: str, platform_id: str = "") -> str: if not url: return url try: # 解析 URL parsed = urlparse(url) # 如果没有查询参数,直接返回 if not parsed.query: return url # 解析查询参数 params = parse_qs(parsed.query, keep_blank_values=True) # 收集需要移除的参数(使用小写进行比较) params_to_remove: Set[str] = set() # 添加通用追踪参数 params_to_remove.update(COMMON_TRACKING_PARAMS) # 添加平台特定参数 if platform_id and platform_id in PLATFORM_PARAMS_TO_REMOVE: params_to_remove.update(PLATFORM_PARAMS_TO_REMOVE[platform_id]) # 过滤参数(参数名转小写进行比较) filtered_params = { key: values for key, values in params.items() if key.lower() not in {p.lower() for p in params_to_remove} } # 如果过滤后没有参数了,返回不带查询字符串的 URL if not filtered_params: return urlunparse(( parsed.scheme, parsed.netloc, parsed.path, parsed.params, "", # 空查询字符串 "" # 移除 fragment )) # 重建查询字符串(按字母序排序以确保一致性) sorted_params = [] for key in sorted(filtered_params.keys()): for value in filtered_params[key]: sorted_params.append((key, value)) new_query = urlencode(sorted_params) # 重建 URL(移除 fragment) normalized = urlunparse(( parsed.scheme, parsed.netloc, parsed.path, parsed.params, new_query, "" # 移除 fragment )) return normalized except Exception: # 解析失败时返回原始 URL return url def get_url_signature(url: str, platform_id: str = "") -> str: return normalize_url(url, platform_id)
--- +++ @@ -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: + """ + 标准化 URL,去除动态参数 + + 用于数据库去重,确保同一条新闻的不同 URL 变体能被正确识别为同一条。 + + 处理规则: + 1. 去除平台特定的动态参数(如微博的 band_rank) + 2. 去除通用追踪参数(如 utm_*) + 3. 保留核心查询参数(如搜索关键词 q=, wd=, keyword=) + 4. 对查询参数按字母序排序(确保一致性) + + Args: + url: 原始 URL + platform_id: 平台 ID,用于应用平台特定规则 + + Returns: + 标准化后的 URL + + Examples: + >>> normalize_url("https://s.weibo.com/weibo?q=test&band_rank=6&Refer=top", "weibo") + 'https://s.weibo.com/weibo?q=test' + + >>> normalize_url("https://example.com/page?id=1&utm_source=twitter", "") + 'https://example.com/page?id=1' + """ if not url: return url @@ -98,4 +129,18 @@ def get_url_signature(url: str, platform_id: str = "") -> str: - return normalize_url(url, platform_id)+ """ + 获取 URL 的签名(用于快速比较) + + 基于标准化 URL 生成签名,可用于: + - 快速判断两个 URL 是否指向同一内容 + - 作为缓存键 + + Args: + url: 原始 URL + platform_id: 平台 ID + + Returns: + URL 签名字符串 + """ + return normalize_url(url, platform_id)
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: str = "auto", data_dir: str = "output", enable_txt: bool = True, enable_html: bool = True, remote_config: Optional[dict] = None, local_retention_days: int = 0, remote_retention_days: int = 0, pull_enabled: bool = False, pull_days: int = 0, timezone: str = DEFAULT_TIMEZONE, ): self.backend_type = backend_type self.data_dir = data_dir self.enable_txt = enable_txt self.enable_html = enable_html self.remote_config = remote_config or {} self.local_retention_days = local_retention_days self.remote_retention_days = remote_retention_days self.pull_enabled = pull_enabled self.pull_days = pull_days self.timezone = timezone self._backend: Optional[StorageBackend] = None self._remote_backend: Optional[StorageBackend] = None @staticmethod def is_github_actions() -> bool: return os.environ.get("GITHUB_ACTIONS") == "true" @staticmethod def is_docker() -> bool: # 方法1: 检查 /.dockerenv 文件 if os.path.exists("/.dockerenv"): return True # 方法2: 检查 cgroup(Linux) try: with open("/proc/1/cgroup", "r") as f: return "docker" in f.read() except (FileNotFoundError, PermissionError): pass # 方法3: 检查环境变量 return os.environ.get("DOCKER_CONTAINER") == "true" def _resolve_backend_type(self) -> str: if self.backend_type == "auto": if self.is_github_actions(): # GitHub Actions 环境,检查是否配置了远程存储 if self._has_remote_config(): return "remote" else: print("[存储管理器] GitHub Actions 环境但未配置远程存储,使用本地存储") return "local" else: return "local" return self.backend_type def _has_remote_config(self) -> bool: # 检查配置或环境变量 bucket_name = self.remote_config.get("bucket_name") or os.environ.get("S3_BUCKET_NAME") access_key = self.remote_config.get("access_key_id") or os.environ.get("S3_ACCESS_KEY_ID") secret_key = self.remote_config.get("secret_access_key") or os.environ.get("S3_SECRET_ACCESS_KEY") endpoint = self.remote_config.get("endpoint_url") or os.environ.get("S3_ENDPOINT_URL") # 调试日志 has_config = bool(bucket_name and access_key and secret_key and endpoint) if not has_config: print(f"[存储管理器] 远程存储配置检查失败:") print(f" - bucket_name: {'已配置' if bucket_name else '未配置'}") print(f" - access_key_id: {'已配置' if access_key else '未配置'}") print(f" - secret_access_key: {'已配置' if secret_key else '未配置'}") print(f" - endpoint_url: {'已配置' if endpoint else '未配置'}") return has_config def _create_remote_backend(self) -> Optional[StorageBackend]: try: from trendradar.storage.remote import RemoteStorageBackend return RemoteStorageBackend( bucket_name=self.remote_config.get("bucket_name") or os.environ.get("S3_BUCKET_NAME", ""), access_key_id=self.remote_config.get("access_key_id") or os.environ.get("S3_ACCESS_KEY_ID", ""), secret_access_key=self.remote_config.get("secret_access_key") or os.environ.get("S3_SECRET_ACCESS_KEY", ""), endpoint_url=self.remote_config.get("endpoint_url") or os.environ.get("S3_ENDPOINT_URL", ""), region=self.remote_config.get("region") or os.environ.get("S3_REGION", ""), enable_txt=self.enable_txt, enable_html=self.enable_html, timezone=self.timezone, ) except ImportError as e: print(f"[存储管理器] 远程后端导入失败: {e}") print("[存储管理器] 请确保已安装 boto3: pip install boto3") return None except Exception as e: print(f"[存储管理器] 远程后端初始化失败: {e}") return None def get_backend(self) -> StorageBackend: if self._backend is None: resolved_type = self._resolve_backend_type() if resolved_type == "remote": self._backend = self._create_remote_backend() if self._backend: print(f"[存储管理器] 使用远程存储后端") else: print("[存储管理器] 回退到本地存储") resolved_type = "local" if resolved_type == "local" or self._backend is None: from trendradar.storage.local import LocalStorageBackend self._backend = LocalStorageBackend( data_dir=self.data_dir, enable_txt=self.enable_txt, enable_html=self.enable_html, timezone=self.timezone, ) print(f"[存储管理器] 使用本地存储后端 (数据目录: {self.data_dir})") return self._backend def pull_from_remote(self) -> int: if not self.pull_enabled or self.pull_days <= 0: return 0 if not self._has_remote_config(): print("[存储管理器] 未配置远程存储,无法拉取") return 0 # 创建远程后端(如果还没有) if self._remote_backend is None: self._remote_backend = self._create_remote_backend() if self._remote_backend is None: print("[存储管理器] 无法创建远程后端,拉取失败") return 0 # 调用拉取方法 return self._remote_backend.pull_recent_days(self.pull_days, self.data_dir) def save_news_data(self, data: NewsData) -> bool: return self.get_backend().save_news_data(data) def save_rss_data(self, data: RSSData) -> bool: return self.get_backend().save_rss_data(data) def get_rss_data(self, date: Optional[str] = None) -> Optional[RSSData]: return self.get_backend().get_rss_data(date) def get_latest_rss_data(self, date: Optional[str] = None) -> Optional[RSSData]: return self.get_backend().get_latest_rss_data(date) def detect_new_rss_items(self, current_data: RSSData) -> dict: return self.get_backend().detect_new_rss_items(current_data) def get_today_all_data(self, date: Optional[str] = None) -> Optional[NewsData]: return self.get_backend().get_today_all_data(date) def get_latest_crawl_data(self, date: Optional[str] = None) -> Optional[NewsData]: return self.get_backend().get_latest_crawl_data(date) def detect_new_titles(self, current_data: NewsData) -> dict: return self.get_backend().detect_new_titles(current_data) def save_txt_snapshot(self, data: NewsData) -> Optional[str]: return self.get_backend().save_txt_snapshot(data) def save_html_report(self, html_content: str, filename: str) -> Optional[str]: return self.get_backend().save_html_report(html_content, filename) def is_first_crawl_today(self, date: Optional[str] = None) -> bool: return self.get_backend().is_first_crawl_today(date) def cleanup(self) -> None: if self._backend: self._backend.cleanup() if self._remote_backend: self._remote_backend.cleanup() def cleanup_old_data(self) -> int: total_deleted = 0 # 清理本地数据 if self.local_retention_days > 0: total_deleted += self.get_backend().cleanup_old_data(self.local_retention_days) # 清理远程数据(如果配置了) if self.remote_retention_days > 0 and self._has_remote_config(): if self._remote_backend is None: self._remote_backend = self._create_remote_backend() if self._remote_backend: total_deleted += self._remote_backend.cleanup_old_data(self.remote_retention_days) return total_deleted @property def backend_name(self) -> str: return self.get_backend().backend_name @property def supports_txt(self) -> bool: return self.get_backend().supports_txt def has_period_executed(self, date_str: str, period_key: str, action: str) -> bool: return self.get_backend().has_period_executed(date_str, period_key, action) def record_period_execution(self, date_str: str, period_key: str, action: str) -> bool: return self.get_backend().record_period_execution(date_str, period_key, action) # === AI 智能筛选存储操作 === def begin_batch(self): self.get_backend().begin_batch() def end_batch(self): self.get_backend().end_batch() def get_active_ai_filter_tags(self, date=None, interests_file="ai_interests.txt"): return self.get_backend().get_active_ai_filter_tags(date, interests_file) def get_latest_prompt_hash(self, date=None, interests_file="ai_interests.txt"): return self.get_backend().get_latest_prompt_hash(date, interests_file) def get_latest_ai_filter_tag_version(self, date=None): return self.get_backend().get_latest_ai_filter_tag_version(date) def deprecate_all_ai_filter_tags(self, date=None, interests_file="ai_interests.txt"): return self.get_backend().deprecate_all_ai_filter_tags(date, interests_file) def save_ai_filter_tags(self, tags, version, prompt_hash, date=None, interests_file="ai_interests.txt"): return self.get_backend().save_ai_filter_tags(tags, version, prompt_hash, date, interests_file) def save_ai_filter_results(self, results, date=None): return self.get_backend().save_ai_filter_results(results, date) def get_active_ai_filter_results(self, date=None, interests_file="ai_interests.txt"): return self.get_backend().get_active_ai_filter_results(date, interests_file) def deprecate_specific_ai_filter_tags(self, tag_ids, date=None): return self.get_backend().deprecate_specific_ai_filter_tags(tag_ids, date) def update_ai_filter_tags_hash(self, interests_file, new_hash, date=None): return self.get_backend().update_ai_filter_tags_hash(interests_file, new_hash, date) def update_ai_filter_tag_descriptions(self, tag_updates, date=None, interests_file="ai_interests.txt"): return self.get_backend().update_ai_filter_tag_descriptions(tag_updates, date, interests_file) def update_ai_filter_tag_priorities(self, tag_priorities, date=None, interests_file="ai_interests.txt"): return self.get_backend().update_ai_filter_tag_priorities(tag_priorities, date, interests_file) def save_analyzed_news(self, news_ids, source_type, interests_file, prompt_hash, matched_ids, date=None): return self.get_backend().save_analyzed_news(news_ids, source_type, interests_file, prompt_hash, matched_ids, date) def get_analyzed_news_ids(self, source_type="hotlist", date=None, interests_file="ai_interests.txt"): return self.get_backend().get_analyzed_news_ids(source_type, date, interests_file) def clear_analyzed_news(self, date=None, interests_file="ai_interests.txt"): return self.get_backend().clear_analyzed_news(date, interests_file) def clear_unmatched_analyzed_news(self, date=None, interests_file="ai_interests.txt"): return self.get_backend().clear_unmatched_analyzed_news(date, interests_file) def get_all_news_ids(self, date=None): return self.get_backend().get_all_news_ids(date) def get_all_rss_ids(self, date=None): return self.get_backend().get_all_rss_ids(date) def get_storage_manager( backend_type: str = "auto", data_dir: str = "output", enable_txt: bool = True, enable_html: bool = True, remote_config: Optional[dict] = None, local_retention_days: int = 0, remote_retention_days: int = 0, pull_enabled: bool = False, pull_days: int = 0, timezone: str = DEFAULT_TIMEZONE, force_new: bool = False, ) -> StorageManager: global _storage_manager if _storage_manager is None or force_new: _storage_manager = StorageManager( backend_type=backend_type, data_dir=data_dir, enable_txt=enable_txt, enable_html=enable_html, remote_config=remote_config, local_retention_days=local_retention_days, remote_retention_days=remote_retention_days, pull_enabled=pull_enabled, pull_days=pull_days, timezone=timezone, ) return _storage_manager
--- +++ @@ -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) + - 提供统一的存储接口 + - 支持从远程拉取数据到本地 + """ def __init__( self, @@ -26,6 +40,21 @@ pull_days: int = 0, timezone: str = DEFAULT_TIMEZONE, ): + """ + 初始化存储管理器 + + Args: + backend_type: 存储后端类型 (local / remote / auto) + data_dir: 本地数据目录 + enable_txt: 是否启用 TXT 快照 + enable_html: 是否启用 HTML 报告 + remote_config: 远程存储配置(endpoint_url, bucket_name, access_key_id 等) + local_retention_days: 本地数据保留天数(0 = 无限制) + remote_retention_days: 远程数据保留天数(0 = 无限制) + pull_enabled: 是否启用启动时自动拉取 + pull_days: 拉取最近 N 天的数据 + timezone: 时区配置 + """ self.backend_type = backend_type self.data_dir = data_dir self.enable_txt = enable_txt @@ -42,10 +71,12 @@ @staticmethod def is_github_actions() -> bool: + """检测是否在 GitHub Actions 环境中运行""" return os.environ.get("GITHUB_ACTIONS") == "true" @staticmethod def is_docker() -> bool: + """检测是否在 Docker 容器中运行""" # 方法1: 检查 /.dockerenv 文件 if os.path.exists("/.dockerenv"): return True @@ -61,6 +92,7 @@ return os.environ.get("DOCKER_CONTAINER") == "true" def _resolve_backend_type(self) -> str: + """解析实际使用的后端类型""" if self.backend_type == "auto": if self.is_github_actions(): # GitHub Actions 环境,检查是否配置了远程存储 @@ -74,6 +106,7 @@ return self.backend_type def _has_remote_config(self) -> bool: + """检查是否有有效的远程存储配置""" # 检查配置或环境变量 bucket_name = self.remote_config.get("bucket_name") or os.environ.get("S3_BUCKET_NAME") access_key = self.remote_config.get("access_key_id") or os.environ.get("S3_ACCESS_KEY_ID") @@ -92,6 +125,7 @@ return has_config def _create_remote_backend(self) -> Optional[StorageBackend]: + """创建远程存储后端""" try: from trendradar.storage.remote import RemoteStorageBackend @@ -114,6 +148,7 @@ return None def get_backend(self) -> StorageBackend: + """获取存储后端实例""" if self._backend is None: resolved_type = self._resolve_backend_type() @@ -139,6 +174,12 @@ return self._backend def pull_from_remote(self) -> int: + """ + 从远程拉取数据到本地 + + Returns: + 成功拉取的文件数量 + """ if not self.pull_enabled or self.pull_days <= 0: return 0 @@ -158,45 +199,63 @@ return self._remote_backend.pull_recent_days(self.pull_days, self.data_dir) def save_news_data(self, data: NewsData) -> bool: + """保存新闻数据""" return self.get_backend().save_news_data(data) def save_rss_data(self, data: RSSData) -> bool: + """保存 RSS 数据""" return self.get_backend().save_rss_data(data) def get_rss_data(self, date: Optional[str] = None) -> Optional[RSSData]: + """获取指定日期的所有 RSS 数据(当日汇总模式)""" return self.get_backend().get_rss_data(date) def get_latest_rss_data(self, date: Optional[str] = None) -> Optional[RSSData]: + """获取最新一次抓取的 RSS 数据(当前榜单模式)""" return self.get_backend().get_latest_rss_data(date) def detect_new_rss_items(self, current_data: RSSData) -> dict: + """检测新增的 RSS 条目(增量模式)""" return self.get_backend().detect_new_rss_items(current_data) def get_today_all_data(self, date: Optional[str] = None) -> Optional[NewsData]: + """获取当天所有数据""" return self.get_backend().get_today_all_data(date) def get_latest_crawl_data(self, date: Optional[str] = None) -> Optional[NewsData]: + """获取最新抓取数据""" return self.get_backend().get_latest_crawl_data(date) def detect_new_titles(self, current_data: NewsData) -> dict: + """检测新增标题""" return self.get_backend().detect_new_titles(current_data) def save_txt_snapshot(self, data: NewsData) -> Optional[str]: + """保存 TXT 快照""" return self.get_backend().save_txt_snapshot(data) def save_html_report(self, html_content: str, filename: str) -> Optional[str]: + """保存 HTML 报告""" return self.get_backend().save_html_report(html_content, filename) def is_first_crawl_today(self, date: Optional[str] = None) -> bool: + """检查是否是当天第一次抓取""" return self.get_backend().is_first_crawl_today(date) def cleanup(self) -> None: + """清理资源""" if self._backend: self._backend.cleanup() if self._remote_backend: self._remote_backend.cleanup() def cleanup_old_data(self) -> int: + """ + 清理过期数据 + + Returns: + 删除的日期目录数量 + """ total_deleted = 0 # 清理本地数据 @@ -214,75 +273,98 @@ @property def backend_name(self) -> str: + """获取当前后端名称""" return self.get_backend().backend_name @property def supports_txt(self) -> bool: + """是否支持 TXT 快照""" return self.get_backend().supports_txt def has_period_executed(self, date_str: str, period_key: str, action: str) -> bool: + """检查指定时间段的某个 action 是否已执行""" return self.get_backend().has_period_executed(date_str, period_key, action) def record_period_execution(self, date_str: str, period_key: str, action: str) -> bool: + """记录时间段的 action 执行""" return self.get_backend().record_period_execution(date_str, period_key, action) # === AI 智能筛选存储操作 === def begin_batch(self): + """开启批量模式(远程后端延迟上传)""" self.get_backend().begin_batch() def end_batch(self): + """结束批量模式(统一上传脏数据库)""" self.get_backend().end_batch() def get_active_ai_filter_tags(self, date=None, interests_file="ai_interests.txt"): + """获取指定兴趣文件的 active 标签""" return self.get_backend().get_active_ai_filter_tags(date, interests_file) def get_latest_prompt_hash(self, date=None, interests_file="ai_interests.txt"): + """获取指定兴趣文件的最新 prompt_hash""" return self.get_backend().get_latest_prompt_hash(date, interests_file) def get_latest_ai_filter_tag_version(self, date=None): + """获取最新标签版本号""" return self.get_backend().get_latest_ai_filter_tag_version(date) def deprecate_all_ai_filter_tags(self, date=None, interests_file="ai_interests.txt"): + """废弃指定兴趣文件的 active 标签和分类结果""" return self.get_backend().deprecate_all_ai_filter_tags(date, interests_file) def save_ai_filter_tags(self, tags, version, prompt_hash, date=None, interests_file="ai_interests.txt"): + """保存新提取的标签""" return self.get_backend().save_ai_filter_tags(tags, version, prompt_hash, date, interests_file) def save_ai_filter_results(self, results, date=None): + """保存分类结果""" return self.get_backend().save_ai_filter_results(results, date) def get_active_ai_filter_results(self, date=None, interests_file="ai_interests.txt"): + """获取指定兴趣文件的 active 分类结果""" return self.get_backend().get_active_ai_filter_results(date, interests_file) def deprecate_specific_ai_filter_tags(self, tag_ids, date=None): + """废弃指定 ID 的标签及其关联分类结果""" return self.get_backend().deprecate_specific_ai_filter_tags(tag_ids, date) def update_ai_filter_tags_hash(self, interests_file, new_hash, date=None): + """更新指定兴趣文件所有 active 标签的 prompt_hash""" return self.get_backend().update_ai_filter_tags_hash(interests_file, new_hash, date) def update_ai_filter_tag_descriptions(self, tag_updates, date=None, interests_file="ai_interests.txt"): + """按 tag 名匹配,更新 active 标签的 description""" return self.get_backend().update_ai_filter_tag_descriptions(tag_updates, date, interests_file) def update_ai_filter_tag_priorities(self, tag_priorities, date=None, interests_file="ai_interests.txt"): + """按 tag 名匹配,更新 active 标签的 priority""" return self.get_backend().update_ai_filter_tag_priorities(tag_priorities, date, interests_file) def save_analyzed_news(self, news_ids, source_type, interests_file, prompt_hash, matched_ids, date=None): + """批量记录已分析的新闻(匹配与不匹配都记录)""" return self.get_backend().save_analyzed_news(news_ids, source_type, interests_file, prompt_hash, matched_ids, date) def get_analyzed_news_ids(self, source_type="hotlist", date=None, interests_file="ai_interests.txt"): + """获取已分析过的新闻 ID 集合""" return self.get_backend().get_analyzed_news_ids(source_type, date, interests_file) def clear_analyzed_news(self, date=None, interests_file="ai_interests.txt"): + """清除指定兴趣文件的所有已分析记录""" return self.get_backend().clear_analyzed_news(date, interests_file) def clear_unmatched_analyzed_news(self, date=None, interests_file="ai_interests.txt"): + """清除不匹配的已分析记录""" return self.get_backend().clear_unmatched_analyzed_news(date, interests_file) def get_all_news_ids(self, date=None): + """获取所有新闻 ID 和标题""" return self.get_backend().get_all_news_ids(date) def get_all_rss_ids(self, date=None): + """获取所有 RSS ID 和标题""" return self.get_backend().get_all_rss_ids(date) @@ -300,6 +382,25 @@ timezone: str = DEFAULT_TIMEZONE, force_new: bool = False, ) -> StorageManager: + """ + 获取存储管理器单例 + + Args: + backend_type: 存储后端类型 + data_dir: 本地数据目录 + enable_txt: 是否启用 TXT 快照 + enable_html: 是否启用 HTML 报告 + remote_config: 远程存储配置 + local_retention_days: 本地数据保留天数(0 = 无限制) + remote_retention_days: 远程数据保留天数(0 = 无限制) + pull_enabled: 是否启用启动时自动拉取 + pull_days: 拉取最近 N 天的数据 + timezone: 时区配置 + force_new: 是否强制创建新实例 + + Returns: + StorageManager 实例 + """ global _storage_manager if _storage_manager is None or force_new: @@ -316,4 +417,4 @@ timezone=timezone, ) - return _storage_manager+ return _storage_manager
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 ClientError HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False boto3 = None BotoConfig = None ClientError = Exception from trendradar.storage.base import StorageBackend, NewsData, RSSItem, RSSData from trendradar.storage.sqlite_mixin import SQLiteStorageMixin from trendradar.utils.time import ( DEFAULT_TIMEZONE, get_configured_time, format_date_folder, format_time_filename, ) class RemoteStorageBackend(SQLiteStorageMixin, StorageBackend): def __init__( self, bucket_name: str, access_key_id: str, secret_access_key: str, endpoint_url: str, region: str = "", enable_txt: bool = False, # 远程模式默认不生成 TXT enable_html: bool = True, temp_dir: Optional[str] = None, timezone: str = DEFAULT_TIMEZONE, ): if not HAS_BOTO3: raise ImportError("远程存储后端需要安装 boto3: pip install boto3") self.bucket_name = bucket_name self.endpoint_url = endpoint_url self.region = region self.enable_txt = enable_txt self.enable_html = enable_html self.timezone = timezone # 创建临时目录 self.temp_dir = Path(temp_dir) if temp_dir else Path(tempfile.mkdtemp(prefix="trendradar_")) self.temp_dir.mkdir(parents=True, exist_ok=True) # 初始化 S3 客户端 # 使用 virtual-hosted style addressing(主流) # 根据服务商选择签名版本: # - 腾讯云 COS 和 阿里云 OSS 使用 SigV2 以避免 chunked encoding 问题 # - 其他服务商(AWS S3、Cloudflare R2、MinIO 等)默认使用 SigV4 use_sigv2 = "myqcloud.com" in endpoint_url.lower() or "aliyuncs.com" in endpoint_url.lower() signature_version = 's3' if use_sigv2 else 's3v4' s3_config = BotoConfig( s3={"addressing_style": "virtual"}, signature_version=signature_version, ) client_kwargs = { "endpoint_url": endpoint_url, "aws_access_key_id": access_key_id, "aws_secret_access_key": secret_access_key, "config": s3_config, } if region: client_kwargs["region_name"] = region self.s3_client = boto3.client("s3", **client_kwargs) # 跟踪下载的文件(用于清理) self._downloaded_files: List[Path] = [] self._db_connections: Dict[str, sqlite3.Connection] = {} # 批量模式:延迟上传,避免频繁上传同一文件 self._batch_mode = False self._batch_dirty: set = set() # 待上传的 (date, db_type) 集合 print(f"[远程存储] 初始化完成,存储桶: {bucket_name},签名版本: {signature_version}") @property def backend_name(self) -> str: return "remote" @property def supports_txt(self) -> bool: return self.enable_txt # ======================================== # SQLiteStorageMixin 抽象方法实现 # ======================================== def _get_configured_time(self) -> datetime: return get_configured_time(self.timezone) def _format_date_folder(self, date: Optional[str] = None) -> str: return format_date_folder(date, self.timezone) def _format_time_filename(self) -> str: return format_time_filename(self.timezone) def _get_remote_db_key(self, date: Optional[str] = None, db_type: str = "news") -> str: date_folder = self._format_date_folder(date) return f"{db_type}/{date_folder}.db" def _get_local_db_path(self, date: Optional[str] = None, db_type: str = "news") -> Path: date_folder = self._format_date_folder(date) db_dir = self.temp_dir / db_type db_dir.mkdir(parents=True, exist_ok=True) return db_dir / f"{date_folder}.db" def _check_object_exists(self, r2_key: str) -> bool: try: self.s3_client.head_object(Bucket=self.bucket_name, Key=r2_key) return True except ClientError as e: error_code = e.response.get("Error", {}).get("Code", "") # S3 兼容存储可能返回 404, NoSuchKey, 或其他变体 if error_code in ("404", "NoSuchKey", "Not Found"): return False # 其他错误(如权限问题)也视为不存在,但打印警告 print(f"[远程存储] 检查对象存在性失败 ({r2_key}): {e}") return False except Exception as e: print(f"[远程存储] 检查对象存在性异常 ({r2_key}): {e}") return False def _download_sqlite(self, date: Optional[str] = None, db_type: str = "news") -> Optional[Path]: r2_key = self._get_remote_db_key(date, db_type) local_path = self._get_local_db_path(date, db_type) # 确保目录存在 local_path.parent.mkdir(parents=True, exist_ok=True) # 先检查文件是否存在 if not self._check_object_exists(r2_key): print(f"[远程存储] 文件不存在,将创建新数据库: {r2_key}") return None try: # 使用 get_object + iter_chunks 替代 download_file # iter_chunks 会自动处理 chunked transfer encoding response = self.s3_client.get_object(Bucket=self.bucket_name, Key=r2_key) with open(local_path, 'wb') as f: for chunk in response['Body'].iter_chunks(chunk_size=1024*1024): f.write(chunk) self._downloaded_files.append(local_path) print(f"[远程存储] 已下载: {r2_key} -> {local_path}") return local_path except ClientError as e: error_code = e.response.get("Error", {}).get("Code", "") # S3 兼容存储可能返回不同的错误码 if error_code in ("404", "NoSuchKey", "Not Found"): print(f"[远程存储] 文件不存在,将创建新数据库: {r2_key}") return None else: print(f"[远程存储] 下载失败 (错误码: {error_code}): {e}") raise except Exception as e: print(f"[远程存储] 下载异常: {e}") raise def begin_batch(self): self._batch_mode = True self._batch_dirty.clear() def end_batch(self): self._batch_mode = False for date, db_type in self._batch_dirty: self._upload_sqlite(date, db_type) self._batch_dirty.clear() def _upload_sqlite(self, date: Optional[str] = None, db_type: str = "news") -> bool: if self._batch_mode: self._batch_dirty.add((date, db_type)) return True local_path = self._get_local_db_path(date, db_type) r2_key = self._get_remote_db_key(date, db_type) if not local_path.exists(): print(f"[远程存储] 本地文件不存在,无法上传: {local_path}") return False try: # 获取本地文件大小 local_size = local_path.stat().st_size print(f"[远程存储] 准备上传: {local_path} ({local_size} bytes) -> {r2_key}") # 读取文件内容为 bytes 后上传 # 避免传入文件对象时 requests 库使用 chunked transfer encoding # 腾讯云 COS 等 S3 兼容服务可能无法正确处理 chunked encoding with open(local_path, 'rb') as f: file_content = f.read() # 使用 put_object 并明确设置 ContentLength,确保不使用 chunked encoding self.s3_client.put_object( Bucket=self.bucket_name, Key=r2_key, Body=file_content, ContentLength=local_size, ContentType='application/x-sqlite3', ) print(f"[远程存储] 已上传: {local_path} -> {r2_key}") # 验证上传成功 if self._check_object_exists(r2_key): print(f"[远程存储] 上传验证成功: {r2_key}") return True else: print(f"[远程存储] 上传验证失败: 文件未在远程存储中找到") return False except Exception as e: print(f"[远程存储] 上传失败: {e}") return False def _get_connection(self, date: Optional[str] = None, db_type: str = "news") -> sqlite3.Connection: local_path = self._get_local_db_path(date, db_type) db_path = str(local_path) if db_path not in self._db_connections: # 确保目录存在 local_path.parent.mkdir(parents=True, exist_ok=True) # 如果本地不存在,尝试从远程存储下载 if not local_path.exists(): self._download_sqlite(date, db_type) conn = sqlite3.connect(db_path) conn.row_factory = sqlite3.Row self._init_tables(conn, db_type) self._db_connections[db_path] = conn return self._db_connections[db_path] # ======================================== # StorageBackend 接口实现(委托给 mixin + 上传) # ======================================== def save_news_data(self, data: NewsData) -> bool: # 查询已有记录数 conn = self._get_connection(data.date) cursor = conn.cursor() cursor.execute("SELECT COUNT(*) as count FROM news_items") row = cursor.fetchone() existing_count = row[0] if row else 0 if existing_count > 0: print(f"[远程存储] 已有 {existing_count} 条历史记录,将合并新数据") # 使用 mixin 的实现保存数据 success, new_count, updated_count, title_changed_count, off_list_count = \ self._save_news_data_impl(data, "[远程存储]") if not success: return False # 查询合并后的总记录数 cursor.execute("SELECT COUNT(*) as count FROM news_items") row = cursor.fetchone() final_count = row[0] if row else 0 # 输出详细的存储统计日志 log_parts = [f"[远程存储] 处理完成:新增 {new_count} 条"] if updated_count > 0: log_parts.append(f"更新 {updated_count} 条") if title_changed_count > 0: log_parts.append(f"标题变更 {title_changed_count} 条") if off_list_count > 0: log_parts.append(f"脱榜 {off_list_count} 条") log_parts.append(f"(去重后总计: {final_count} 条)") print(",".join(log_parts)) # 上传到远程存储 if self._upload_sqlite(data.date): print(f"[远程存储] 数据已同步到远程存储") return True else: print(f"[远程存储] 上传远程存储失败") return False def get_today_all_data(self, date: Optional[str] = None) -> Optional[NewsData]: return self._get_today_all_data_impl(date) def get_latest_crawl_data(self, date: Optional[str] = None) -> Optional[NewsData]: return self._get_latest_crawl_data_impl(date) def detect_new_titles(self, current_data: NewsData) -> Dict[str, Dict]: return self._detect_new_titles_impl(current_data) def is_first_crawl_today(self, date: Optional[str] = None) -> bool: return self._is_first_crawl_today_impl(date) # ======================================== # 时间段执行记录(调度系统) # ======================================== def has_period_executed(self, date_str: str, period_key: str, action: str) -> bool: return self._has_period_executed_impl(date_str, period_key, action) def record_period_execution(self, date_str: str, period_key: str, action: str) -> bool: success = self._record_period_execution_impl(date_str, period_key, action) if success: now_str = self._get_configured_time().strftime("%Y-%m-%d %H:%M:%S") print(f"[远程存储] 时间段执行记录已保存: {period_key}/{action} at {now_str}") # 上传到远程存储确保记录持久化 if self._upload_sqlite(date_str): print(f"[远程存储] 时间段执行记录已同步到远程存储") return True else: print(f"[远程存储] 时间段执行记录同步到远程存储失败") return False return False # ======================================== # RSS 数据存储方法 # ======================================== def save_rss_data(self, data: RSSData) -> bool: success, new_count, updated_count = self._save_rss_data_impl(data, "[远程存储]") if not success: return False # 输出统计日志 log_parts = [f"[远程存储] RSS 处理完成:新增 {new_count} 条"] if updated_count > 0: log_parts.append(f"更新 {updated_count} 条") print(",".join(log_parts)) # 上传到远程存储 if self._upload_sqlite(data.date, db_type="rss"): print(f"[远程存储] RSS 数据已同步到远程存储") return True else: print(f"[远程存储] RSS 上传远程存储失败") return False def get_rss_data(self, date: Optional[str] = None) -> Optional[RSSData]: return self._get_rss_data_impl(date) def detect_new_rss_items(self, current_data: RSSData) -> Dict[str, List[RSSItem]]: return self._detect_new_rss_items_impl(current_data) def get_latest_rss_data(self, date: Optional[str] = None) -> Optional[RSSData]: return self._get_latest_rss_data_impl(date) # ======================================== # AI 智能筛选存储方法 # ======================================== def get_active_ai_filter_tags(self, date=None, interests_file="ai_interests.txt"): return self._get_active_tags_impl(date, interests_file) def get_latest_prompt_hash(self, date=None, interests_file="ai_interests.txt"): return self._get_latest_prompt_hash_impl(date, interests_file) def get_latest_ai_filter_tag_version(self, date=None): return self._get_latest_tag_version_impl(date) def deprecate_all_ai_filter_tags(self, date=None, interests_file="ai_interests.txt"): count = self._deprecate_all_tags_impl(date, interests_file) if count > 0: self._upload_sqlite(date) return count def save_ai_filter_tags(self, tags, version, prompt_hash, date=None, interests_file="ai_interests.txt"): count = self._save_tags_impl(date, tags, version, prompt_hash, interests_file) if count > 0: self._upload_sqlite(date) return count def save_ai_filter_results(self, results, date=None): count = self._save_filter_results_impl(date, results) if count > 0: self._upload_sqlite(date) return count def get_active_ai_filter_results(self, date=None, interests_file="ai_interests.txt"): return self._get_active_filter_results_impl(date, interests_file) def deprecate_specific_ai_filter_tags(self, tag_ids, date=None): count = self._deprecate_specific_tags_impl(date, tag_ids) if count > 0: self._upload_sqlite(date) return count def update_ai_filter_tags_hash(self, interests_file, new_hash, date=None): count = self._update_tags_hash_impl(date, interests_file, new_hash) if count > 0: self._upload_sqlite(date) return count def update_ai_filter_tag_descriptions(self, tag_updates, date=None, interests_file="ai_interests.txt"): count = self._update_tag_descriptions_impl(date, tag_updates, interests_file) if count > 0: self._upload_sqlite(date) return count def update_ai_filter_tag_priorities(self, tag_priorities, date=None, interests_file="ai_interests.txt"): count = self._update_tag_priorities_impl(date, tag_priorities, interests_file) if count > 0: self._upload_sqlite(date) return count def save_analyzed_news(self, news_ids, source_type, interests_file, prompt_hash, matched_ids, date=None): count = self._save_analyzed_news_impl(date, news_ids, source_type, interests_file, prompt_hash, matched_ids) if count > 0: self._upload_sqlite(date) return count def get_analyzed_news_ids(self, source_type="hotlist", date=None, interests_file="ai_interests.txt"): return self._get_analyzed_news_ids_impl(date, source_type, interests_file) def clear_analyzed_news(self, date=None, interests_file="ai_interests.txt"): count = self._clear_analyzed_news_impl(date, interests_file) if count > 0: self._upload_sqlite(date) return count def clear_unmatched_analyzed_news(self, date=None, interests_file="ai_interests.txt"): count = self._clear_unmatched_analyzed_news_impl(date, interests_file) if count > 0: self._upload_sqlite(date) return count def get_all_news_ids(self, date=None): return self._get_all_news_ids_impl(date) def get_all_rss_ids(self, date=None): return self._get_all_rss_ids_impl(date) # ======================================== # 远程特有功能:TXT/HTML 快照(临时目录) # ======================================== def save_txt_snapshot(self, data: NewsData) -> Optional[str]: if not self.enable_txt: return None # 如果启用,保存到本地临时目录 try: date_folder = self._format_date_folder(data.date) txt_dir = self.temp_dir / date_folder / "txt" txt_dir.mkdir(parents=True, exist_ok=True) file_path = txt_dir / f"{data.crawl_time}.txt" with open(file_path, "w", encoding="utf-8") as f: for source_id, news_list in data.items.items(): source_name = data.id_to_name.get(source_id, source_id) if source_name and source_name != source_id: f.write(f"{source_id} | {source_name}\n") else: f.write(f"{source_id}\n") sorted_news = sorted(news_list, key=lambda x: x.rank) for item in sorted_news: line = f"{item.rank}. {item.title}" if item.url: line += f" [URL:{item.url}]" if item.mobile_url: line += f" [MOBILE:{item.mobile_url}]" f.write(line + "\n") f.write("\n") if data.failed_ids: f.write("==== 以下ID请求失败 ====\n") for failed_id in data.failed_ids: f.write(f"{failed_id}\n") print(f"[远程存储] TXT 快照已保存: {file_path}") return str(file_path) except Exception as e: print(f"[远程存储] 保存 TXT 快照失败: {e}") return None def save_html_report(self, html_content: str, filename: str) -> Optional[str]: if not self.enable_html: return None try: date_folder = self._format_date_folder() html_dir = self.temp_dir / date_folder / "html" html_dir.mkdir(parents=True, exist_ok=True) file_path = html_dir / filename with open(file_path, "w", encoding="utf-8") as f: f.write(html_content) print(f"[远程存储] HTML 报告已保存: {file_path}") return str(file_path) except Exception as e: print(f"[远程存储] 保存 HTML 报告失败: {e}") return None # ======================================== # 远程特有功能:资源清理 # ======================================== def cleanup(self) -> None: # 检查 Python 是否正在关闭 if sys.meta_path is None: return # 关闭数据库连接 db_connections = getattr(self, "_db_connections", {}) for db_path, conn in list(db_connections.items()): try: conn.close() print(f"[远程存储] 关闭数据库连接: {db_path}") except Exception as e: print(f"[远程存储] 关闭连接失败 {db_path}: {e}") if db_connections: db_connections.clear() # 删除临时目录 temp_dir = getattr(self, "temp_dir", None) if temp_dir: try: if temp_dir.exists(): shutil.rmtree(temp_dir) print(f"[远程存储] 临时目录已清理: {temp_dir}") except Exception as e: # 忽略 Python 关闭时的错误 if sys.meta_path is not None: print(f"[远程存储] 清理临时目录失败: {e}") downloaded_files = getattr(self, "_downloaded_files", None) if downloaded_files: downloaded_files.clear() def cleanup_old_data(self, retention_days: int) -> int: if retention_days <= 0: return 0 deleted_count = 0 cutoff_date = self._get_configured_time() - timedelta(days=retention_days) try: # 列出远程存储中 news/ 前缀下的所有对象 paginator = self.s3_client.get_paginator('list_objects_v2') pages = paginator.paginate(Bucket=self.bucket_name, Prefix="news/") # 收集需要删除的对象键 objects_to_delete = [] deleted_dates = set() for page in pages: if 'Contents' not in page: continue for obj in page['Contents']: key = obj['Key'] # 解析日期(格式: news/YYYY-MM-DD.db) folder_date = None date_str = None try: date_match = re.match(r'news/(\d{4})-(\d{2})-(\d{2})\.db$', key) if date_match: folder_date = datetime( int(date_match.group(1)), int(date_match.group(2)), int(date_match.group(3)), tzinfo=pytz.timezone(self.timezone) ) date_str = f"{date_match.group(1)}-{date_match.group(2)}-{date_match.group(3)}" except Exception: continue if folder_date and folder_date < cutoff_date: objects_to_delete.append({'Key': key}) deleted_dates.add(date_str) # 批量删除对象(每次最多 1000 个) if objects_to_delete: batch_size = 1000 for i in range(0, len(objects_to_delete), batch_size): batch = objects_to_delete[i:i + batch_size] try: self.s3_client.delete_objects( Bucket=self.bucket_name, Delete={'Objects': batch} ) print(f"[远程存储] 删除 {len(batch)} 个对象") except Exception as e: print(f"[远程存储] 批量删除失败: {e}") deleted_count = len(deleted_dates) for date_str in sorted(deleted_dates): print(f"[远程存储] 清理过期数据: news/{date_str}.db") print(f"[远程存储] 共清理 {deleted_count} 个过期日期数据库文件") return deleted_count except Exception as e: print(f"[远程存储] 清理过期数据失败: {e}") return deleted_count def __del__(self): # 检查 Python 是否正在关闭 if sys.meta_path is None: return try: self.cleanup() except Exception: # Python 关闭时可能会出错,忽略即可 pass # ======================================== # 远程特有功能:数据拉取和列表 # ======================================== def pull_recent_days(self, days: int, local_data_dir: str = "output") -> int: if days <= 0: return 0 local_dir = Path(local_data_dir) local_dir.mkdir(parents=True, exist_ok=True) pulled_count = 0 now = self._get_configured_time() print(f"[远程存储] 开始拉取最近 {days} 天的数据...") for i in range(days): date = now - timedelta(days=i) date_str = date.strftime("%Y-%m-%d") # 本地目标路径 local_date_dir = local_dir / date_str local_db_path = local_date_dir / "news.db" # 如果本地已存在,跳过 if local_db_path.exists(): print(f"[远程存储] 跳过(本地已存在): {date_str}") continue # 远程对象键 remote_key = f"news/{date_str}.db" # 检查远程是否存在 if not self._check_object_exists(remote_key): print(f"[远程存储] 跳过(远程不存在): {date_str}") continue # 下载(使用 get_object + iter_chunks 处理 chunked encoding) try: local_date_dir.mkdir(parents=True, exist_ok=True) response = self.s3_client.get_object(Bucket=self.bucket_name, Key=remote_key) with open(local_db_path, 'wb') as f: for chunk in response['Body'].iter_chunks(chunk_size=1024*1024): f.write(chunk) print(f"[远程存储] 已拉取: {remote_key} -> {local_db_path}") pulled_count += 1 except Exception as e: print(f"[远程存储] 拉取失败 ({date_str}): {e}") print(f"[远程存储] 拉取完成,共下载 {pulled_count} 个数据库文件") return pulled_count def list_remote_dates(self) -> List[str]: dates = [] try: paginator = self.s3_client.get_paginator('list_objects_v2') pages = paginator.paginate(Bucket=self.bucket_name, Prefix="news/") for page in pages: if 'Contents' not in page: continue for obj in page['Contents']: key = obj['Key'] # 解析日期 date_match = re.match(r'news/(\d{4}-\d{2}-\d{2})\.db$', key) if date_match: dates.append(date_match.group(1)) return sorted(dates, reverse=True) except Exception as e: print(f"[远程存储] 列出远程日期失败: {e}") return []
--- +++ @@ -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 兼容协议) + + 特点: + - 使用 S3 兼容 API 访问远程存储 + - 支持 Cloudflare R2、阿里云 OSS、腾讯云 COS、AWS S3、MinIO 等 + - 下载 SQLite 到临时目录进行操作 + - 支持数据合并和上传 + - 支持从远程拉取历史数据到本地 + - 运行结束后自动清理临时文件 + """ def __init__( self, @@ -45,6 +63,20 @@ temp_dir: Optional[str] = None, timezone: str = DEFAULT_TIMEZONE, ): + """ + 初始化远程存储后端 + + Args: + bucket_name: 存储桶名称 + access_key_id: 访问密钥 ID + secret_access_key: 访问密钥 + endpoint_url: 服务端点 URL + region: 区域(可选,部分服务商需要) + enable_txt: 是否启用 TXT 快照(默认关闭) + enable_html: 是否启用 HTML 报告 + temp_dir: 临时目录路径(默认使用系统临时目录) + timezone: 时区配置 + """ if not HAS_BOTO3: raise ImportError("远程存储后端需要安装 boto3: pip install boto3") @@ -106,25 +138,57 @@ # ======================================== def _get_configured_time(self) -> datetime: + """获取配置时区的当前时间""" return get_configured_time(self.timezone) def _format_date_folder(self, date: Optional[str] = None) -> str: + """格式化日期文件夹名 (ISO 格式: YYYY-MM-DD)""" return format_date_folder(date, self.timezone) def _format_time_filename(self) -> str: + """格式化时间文件名 (格式: HH-MM)""" return format_time_filename(self.timezone) def _get_remote_db_key(self, date: Optional[str] = None, db_type: str = "news") -> str: + """ + 获取远程存储中 SQLite 文件的对象键 + + Args: + date: 日期字符串 + db_type: 数据库类型 ("news" 或 "rss") + + Returns: + 远程对象键,如 "news/2025-12-28.db" 或 "rss/2025-12-28.db" + """ date_folder = self._format_date_folder(date) return f"{db_type}/{date_folder}.db" def _get_local_db_path(self, date: Optional[str] = None, db_type: str = "news") -> Path: + """ + 获取本地临时 SQLite 文件路径 + + Args: + date: 日期字符串 + db_type: 数据库类型 ("news" 或 "rss") + + Returns: + 本地临时文件路径 + """ date_folder = self._format_date_folder(date) db_dir = self.temp_dir / db_type db_dir.mkdir(parents=True, exist_ok=True) return db_dir / f"{date_folder}.db" def _check_object_exists(self, r2_key: str) -> bool: + """ + 检查远程存储中对象是否存在 + + Args: + r2_key: 远程对象键 + + Returns: + 是否存在 + """ try: self.s3_client.head_object(Bucket=self.bucket_name, Key=r2_key) return True @@ -141,6 +205,19 @@ return False def _download_sqlite(self, date: Optional[str] = None, db_type: str = "news") -> Optional[Path]: + """ + 从远程存储下载当天的 SQLite 文件到本地临时目录 + + 使用 get_object + iter_chunks 替代 download_file, + 以正确处理腾讯云 COS 的 chunked transfer encoding。 + + Args: + date: 日期字符串 + db_type: 数据库类型 ("news" 或 "rss") + + Returns: + 本地文件路径,如果不存在返回 None + """ r2_key = self._get_remote_db_key(date, db_type) local_path = self._get_local_db_path(date, db_type) @@ -176,16 +253,30 @@ raise def begin_batch(self): + """开启批量模式:延迟上传,避免频繁上传同一文件""" self._batch_mode = True self._batch_dirty.clear() def end_batch(self): + """结束批量模式:统一上传所有脏数据库""" self._batch_mode = False for date, db_type in self._batch_dirty: self._upload_sqlite(date, db_type) self._batch_dirty.clear() def _upload_sqlite(self, date: Optional[str] = None, db_type: str = "news") -> bool: + """ + 上传本地 SQLite 文件到远程存储 + + 批量模式下延迟上传,由 end_batch() 统一触发。 + + Args: + date: 日期字符串 + db_type: 数据库类型 ("news" 或 "rss") + + Returns: + 是否上传成功 + """ if self._batch_mode: self._batch_dirty.add((date, db_type)) return True @@ -230,6 +321,16 @@ return False def _get_connection(self, date: Optional[str] = None, db_type: str = "news") -> sqlite3.Connection: + """ + 获取数据库连接 + + Args: + date: 日期字符串 + db_type: 数据库类型 ("news" 或 "rss") + + Returns: + 数据库连接 + """ local_path = self._get_local_db_path(date, db_type) db_path = str(local_path) @@ -253,6 +354,11 @@ # ======================================== def save_news_data(self, data: NewsData) -> bool: + """ + 保存新闻数据到远程存储 + + 流程:下载现有数据库 → 插入/更新数据 → 上传回远程存储 + """ # 查询已有记录数 conn = self._get_connection(data.date) cursor = conn.cursor() @@ -294,15 +400,19 @@ return False def get_today_all_data(self, date: Optional[str] = None) -> Optional[NewsData]: + """获取指定日期的所有新闻数据(合并后)""" return self._get_today_all_data_impl(date) def get_latest_crawl_data(self, date: Optional[str] = None) -> Optional[NewsData]: + """获取最新一次抓取的数据""" return self._get_latest_crawl_data_impl(date) def detect_new_titles(self, current_data: NewsData) -> Dict[str, Dict]: + """检测新增的标题""" return self._detect_new_titles_impl(current_data) def is_first_crawl_today(self, date: Optional[str] = None) -> bool: + """检查是否是当天第一次抓取""" return self._is_first_crawl_today_impl(date) # ======================================== @@ -310,9 +420,11 @@ # ======================================== def has_period_executed(self, date_str: str, period_key: str, action: str) -> bool: + """检查指定时间段的某个 action 是否已执行""" return self._has_period_executed_impl(date_str, period_key, action) def record_period_execution(self, date_str: str, period_key: str, action: str) -> bool: + """记录时间段的 action 执行""" success = self._record_period_execution_impl(date_str, period_key, action) if success: @@ -334,6 +446,11 @@ # ======================================== def save_rss_data(self, data: RSSData) -> bool: + """ + 保存 RSS 数据到远程存储 + + 流程:下载现有数据库 → 插入/更新数据 → 上传回远程存储 + """ success, new_count, updated_count = self._save_rss_data_impl(data, "[远程存储]") if not success: @@ -354,12 +471,15 @@ return False def get_rss_data(self, date: Optional[str] = None) -> Optional[RSSData]: + """获取指定日期的所有 RSS 数据""" return self._get_rss_data_impl(date) def detect_new_rss_items(self, current_data: RSSData) -> Dict[str, List[RSSItem]]: + """检测新增的 RSS 条目""" return self._detect_new_rss_items_impl(current_data) def get_latest_rss_data(self, date: Optional[str] = None) -> Optional[RSSData]: + """获取最新一次抓取的 RSS 数据""" return self._get_latest_rss_data_impl(date) # ======================================== @@ -452,6 +572,7 @@ # ======================================== def save_txt_snapshot(self, data: NewsData) -> Optional[str]: + """保存 TXT 快照(远程存储模式下默认不支持)""" if not self.enable_txt: return None @@ -497,6 +618,7 @@ return None def save_html_report(self, html_content: str, filename: str) -> Optional[str]: + """保存 HTML 报告到临时目录""" if not self.enable_html: return None @@ -522,6 +644,7 @@ # ======================================== def cleanup(self) -> None: + """清理资源(关闭连接和删除临时文件)""" # 检查 Python 是否正在关闭 if sys.meta_path is None: return @@ -555,6 +678,15 @@ downloaded_files.clear() def cleanup_old_data(self, retention_days: int) -> int: + """ + 清理远程存储上的过期数据 + + Args: + retention_days: 保留天数(0 表示不清理) + + Returns: + 删除的数据库文件数量 + """ if retention_days <= 0: return 0 @@ -624,6 +756,7 @@ return deleted_count def __del__(self): + """析构函数""" # 检查 Python 是否正在关闭 if sys.meta_path is None: return @@ -638,6 +771,16 @@ # ======================================== def pull_recent_days(self, days: int, local_data_dir: str = "output") -> int: + """ + 从远程拉取最近 N 天的数据到本地 + + Args: + days: 拉取天数 + local_data_dir: 本地数据目录 + + Returns: + 成功拉取的数据库文件数量 + """ if days <= 0: return 0 @@ -686,6 +829,12 @@ return pulled_count def list_remote_dates(self) -> List[str]: + """ + 列出远程存储中所有可用的日期 + + Returns: + 日期字符串列表(YYYY-MM-DD 格式) + """ dates = [] try: @@ -707,4 +856,4 @@ except Exception as e: print(f"[远程存储] 列出远程日期失败: {e}") - return []+ return []
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: dir_name = os.path.abspath(os.path.dirname(file_path)) os.makedirs(dir_name, exist_ok=True) return cv2.imwrite(file_path, img, params) def img2tensor(imgs, bgr2rgb=True, float32=True): def _totensor(img, bgr2rgb, float32): if img.shape[2] == 3 and bgr2rgb: if img.dtype == 'float64': img = img.astype('float32') img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = torch.from_numpy(img.transpose(2, 0, 1)) if float32: img = img.float() return img if isinstance(imgs, list): return [_totensor(img, bgr2rgb, float32) for img in imgs] else: return _totensor(imgs, bgr2rgb, float32) def load_file_from_url(url, model_dir=None, progress=True, file_name=None, save_dir=None): if model_dir is None: hub_dir = get_dir() model_dir = os.path.join(hub_dir, 'checkpoints') if save_dir is None: save_dir = os.path.join(ROOT_DIR, model_dir) os.makedirs(save_dir, exist_ok=True) parts = urlparse(url) filename = os.path.basename(parts.path) if file_name is not None: filename = file_name cached_file = os.path.abspath(os.path.join(save_dir, filename)) if not os.path.exists(cached_file): print(f'Downloading: "{url}" to {cached_file}\n') download_url_to_file(url, cached_file, hash_prefix=None, progress=progress) return cached_file def scandir(dir_path, suffix=None, recursive=False, full_path=False): if (suffix is not None) and not isinstance(suffix, (str, tuple)): raise TypeError('"suffix" must be a string or tuple of strings') root = dir_path def _scandir(dir_path, suffix, recursive): for entry in os.scandir(dir_path): if not entry.name.startswith('.') and entry.is_file(): if full_path: return_path = entry.path else: return_path = osp.relpath(entry.path, root) if suffix is None: yield return_path elif return_path.endswith(suffix): yield return_path else: if recursive: yield from _scandir(entry.path, suffix=suffix, recursive=recursive) else: continue return _scandir(dir_path, suffix=suffix, recursive=recursive)
--- +++ @@ -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 (bool): If the parent folder of `file_path` does not exist, + whether to create it automatically. + + Returns: + bool: Successful or not. + """ if auto_mkdir: dir_name = os.path.abspath(os.path.dirname(file_path)) os.makedirs(dir_name, exist_ok=True) @@ -16,6 +28,17 @@ def img2tensor(imgs, bgr2rgb=True, float32=True): + """Numpy array to tensor. + + Args: + imgs (list[ndarray] | ndarray): Input images. + bgr2rgb (bool): Whether to change bgr to rgb. + float32 (bool): Whether to change to float32. + + Returns: + list[tensor] | tensor: Tensor images. If returned results only have + one element, just return tensor. + """ def _totensor(img, bgr2rgb, float32): if img.shape[2] == 3 and bgr2rgb: @@ -34,6 +57,8 @@ def load_file_from_url(url, model_dir=None, progress=True, file_name=None, save_dir=None): + """Ref:https://github.com/1adrianb/face-alignment/blob/master/face_alignment/utils.py + """ if model_dir is None: hub_dir = get_dir() model_dir = os.path.join(hub_dir, 'checkpoints') @@ -54,6 +79,18 @@ def scandir(dir_path, suffix=None, recursive=False, full_path=False): + """Scan a directory to find the interested files. + Args: + dir_path (str): Path of the directory. + suffix (str | tuple(str), optional): File suffix that we are + interested in. Default: None. + recursive (bool, optional): If set to True, recursively scan the + directory. Default: False. + full_path (bool, optional): If set to True, include the dir_path. + Default: False. + Returns: + A generator for all the interested files with relative paths. + """ if (suffix is not None) and not isinstance(suffix, (str, tuple)): raise TypeError('"suffix" must be a string or tuple of strings') @@ -78,4 +115,4 @@ else: continue - return _scandir(dir_path, suffix=suffix, recursive=recursive)+ return _scandir(dir_path, suffix=suffix, recursive=recursive)
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, default from ldm_patched.ldm.util import exists import ldm_patched.modules.ops ops = ldm_patched.modules.ops.disable_weight_init class TimestepBlock(nn.Module): @abstractmethod def forward(self, x, emb): #This is needed because accelerate makes a copy of transformer_options which breaks "transformer_index" def forward_timestep_embed(ts, x, emb, context=None, transformer_options={}, output_shape=None, time_context=None, num_video_frames=None, image_only_indicator=None): for layer in ts: if isinstance(layer, VideoResBlock): x = layer(x, emb, num_video_frames, image_only_indicator) elif isinstance(layer, TimestepBlock): x = layer(x, emb) elif isinstance(layer, SpatialVideoTransformer): x = layer(x, context, time_context, num_video_frames, image_only_indicator, transformer_options) if "transformer_index" in transformer_options: transformer_options["transformer_index"] += 1 elif isinstance(layer, SpatialTransformer): x = layer(x, context, transformer_options) if "transformer_index" in transformer_options: transformer_options["transformer_index"] += 1 elif isinstance(layer, Upsample): x = layer(x, output_shape=output_shape) else: x = layer(x) return x class TimestepEmbedSequential(nn.Sequential, TimestepBlock): def forward(self, *args, **kwargs): return forward_timestep_embed(self, *args, **kwargs) class Upsample(nn.Module): def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1, dtype=None, device=None, operations=ops): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.use_conv = use_conv self.dims = dims if use_conv: self.conv = operations.conv_nd(dims, self.channels, self.out_channels, 3, padding=padding, dtype=dtype, device=device) def forward(self, x, output_shape=None): assert x.shape[1] == self.channels if self.dims == 3: shape = [x.shape[2], x.shape[3] * 2, x.shape[4] * 2] if output_shape is not None: shape[1] = output_shape[3] shape[2] = output_shape[4] else: shape = [x.shape[2] * 2, x.shape[3] * 2] if output_shape is not None: shape[0] = output_shape[2] shape[1] = output_shape[3] x = F.interpolate(x, size=shape, mode="nearest") if self.use_conv: x = self.conv(x) return x class Downsample(nn.Module): def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1, dtype=None, device=None, operations=ops): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.use_conv = use_conv self.dims = dims stride = 2 if dims != 3 else (1, 2, 2) if use_conv: self.op = operations.conv_nd( dims, self.channels, self.out_channels, 3, stride=stride, padding=padding, dtype=dtype, device=device ) else: assert self.channels == self.out_channels self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride) def forward(self, x): assert x.shape[1] == self.channels return self.op(x) class ResBlock(TimestepBlock): def __init__( self, channels, emb_channels, dropout, out_channels=None, use_conv=False, use_scale_shift_norm=False, dims=2, use_checkpoint=False, up=False, down=False, kernel_size=3, exchange_temb_dims=False, skip_t_emb=False, dtype=None, device=None, operations=ops ): super().__init__() self.channels = channels self.emb_channels = emb_channels self.dropout = dropout self.out_channels = out_channels or channels self.use_conv = use_conv self.use_checkpoint = use_checkpoint self.use_scale_shift_norm = use_scale_shift_norm self.exchange_temb_dims = exchange_temb_dims if isinstance(kernel_size, list): padding = [k // 2 for k in kernel_size] else: padding = kernel_size // 2 self.in_layers = nn.Sequential( operations.GroupNorm(32, channels, dtype=dtype, device=device), nn.SiLU(), operations.conv_nd(dims, channels, self.out_channels, kernel_size, padding=padding, dtype=dtype, device=device), ) self.updown = up or down if up: self.h_upd = Upsample(channels, False, dims, dtype=dtype, device=device) self.x_upd = Upsample(channels, False, dims, dtype=dtype, device=device) elif down: self.h_upd = Downsample(channels, False, dims, dtype=dtype, device=device) self.x_upd = Downsample(channels, False, dims, dtype=dtype, device=device) else: self.h_upd = self.x_upd = nn.Identity() self.skip_t_emb = skip_t_emb if self.skip_t_emb: self.emb_layers = None self.exchange_temb_dims = False else: self.emb_layers = nn.Sequential( nn.SiLU(), operations.Linear( emb_channels, 2 * self.out_channels if use_scale_shift_norm else self.out_channels, dtype=dtype, device=device ), ) self.out_layers = nn.Sequential( operations.GroupNorm(32, self.out_channels, dtype=dtype, device=device), nn.SiLU(), nn.Dropout(p=dropout), operations.conv_nd(dims, self.out_channels, self.out_channels, kernel_size, padding=padding, dtype=dtype, device=device) , ) if self.out_channels == channels: self.skip_connection = nn.Identity() elif use_conv: self.skip_connection = operations.conv_nd( dims, channels, self.out_channels, kernel_size, padding=padding, dtype=dtype, device=device ) else: self.skip_connection = operations.conv_nd(dims, channels, self.out_channels, 1, dtype=dtype, device=device) def forward(self, x, emb): return checkpoint( self._forward, (x, emb), self.parameters(), self.use_checkpoint ) def _forward(self, x, emb): if self.updown: in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1] h = in_rest(x) h = self.h_upd(h) x = self.x_upd(x) h = in_conv(h) else: h = self.in_layers(x) emb_out = None if not self.skip_t_emb: emb_out = self.emb_layers(emb).type(h.dtype) while len(emb_out.shape) < len(h.shape): emb_out = emb_out[..., None] if self.use_scale_shift_norm: out_norm, out_rest = self.out_layers[0], self.out_layers[1:] h = out_norm(h) if emb_out is not None: scale, shift = th.chunk(emb_out, 2, dim=1) h *= (1 + scale) h += shift h = out_rest(h) else: if emb_out is not None: if self.exchange_temb_dims: emb_out = rearrange(emb_out, "b t c ... -> b c t ...") h = h + emb_out h = self.out_layers(h) return self.skip_connection(x) + h class VideoResBlock(ResBlock): def __init__( self, channels: int, emb_channels: int, dropout: float, video_kernel_size=3, merge_strategy: str = "fixed", merge_factor: float = 0.5, out_channels=None, use_conv: bool = False, use_scale_shift_norm: bool = False, dims: int = 2, use_checkpoint: bool = False, up: bool = False, down: bool = False, dtype=None, device=None, operations=ops ): super().__init__( channels, emb_channels, dropout, out_channels=out_channels, use_conv=use_conv, use_scale_shift_norm=use_scale_shift_norm, dims=dims, use_checkpoint=use_checkpoint, up=up, down=down, dtype=dtype, device=device, operations=operations ) self.time_stack = ResBlock( default(out_channels, channels), emb_channels, dropout=dropout, dims=3, out_channels=default(out_channels, channels), use_scale_shift_norm=False, use_conv=False, up=False, down=False, kernel_size=video_kernel_size, use_checkpoint=use_checkpoint, exchange_temb_dims=True, dtype=dtype, device=device, operations=operations ) self.time_mixer = AlphaBlender( alpha=merge_factor, merge_strategy=merge_strategy, rearrange_pattern="b t -> b 1 t 1 1", ) def forward( self, x: th.Tensor, emb: th.Tensor, num_video_frames: int, image_only_indicator = None, ) -> th.Tensor: x = super().forward(x, emb) x_mix = rearrange(x, "(b t) c h w -> b c t h w", t=num_video_frames) x = rearrange(x, "(b t) c h w -> b c t h w", t=num_video_frames) x = self.time_stack( x, rearrange(emb, "(b t) ... -> b t ...", t=num_video_frames) ) x = self.time_mixer( x_spatial=x_mix, x_temporal=x, image_only_indicator=image_only_indicator ) x = rearrange(x, "b c t h w -> (b t) c h w") return x class Timestep(nn.Module): def __init__(self, dim): super().__init__() self.dim = dim def forward(self, t): return timestep_embedding(t, self.dim) def apply_control(h, control, name): if control is not None and name in control and len(control[name]) > 0: ctrl = control[name].pop() if ctrl is not None: try: h += ctrl except: print("warning control could not be applied", h.shape, ctrl.shape) return h class UNetModel(nn.Module): def __init__( self, image_size, in_channels, model_channels, out_channels, num_res_blocks, dropout=0, channel_mult=(1, 2, 4, 8), conv_resample=True, dims=2, num_classes=None, use_checkpoint=False, dtype=th.float32, num_heads=-1, num_head_channels=-1, num_heads_upsample=-1, use_scale_shift_norm=False, resblock_updown=False, use_new_attention_order=False, use_spatial_transformer=False, # custom transformer support transformer_depth=1, # custom transformer support context_dim=None, # custom transformer support n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model legacy=True, disable_self_attentions=None, num_attention_blocks=None, disable_middle_self_attn=False, use_linear_in_transformer=False, adm_in_channels=None, transformer_depth_middle=None, transformer_depth_output=None, use_temporal_resblock=False, use_temporal_attention=False, time_context_dim=None, extra_ff_mix_layer=False, use_spatial_context=False, merge_strategy=None, merge_factor=0.0, video_kernel_size=None, disable_temporal_crossattention=False, max_ddpm_temb_period=10000, device=None, operations=ops, ): super().__init__() if context_dim is not None: assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...' # from omegaconf.listconfig import ListConfig # if type(context_dim) == ListConfig: # context_dim = list(context_dim) if num_heads_upsample == -1: num_heads_upsample = num_heads if num_heads == -1: assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set' if num_head_channels == -1: assert num_heads != -1, 'Either num_heads or num_head_channels has to be set' self.in_channels = in_channels self.model_channels = model_channels self.out_channels = out_channels if isinstance(num_res_blocks, int): self.num_res_blocks = len(channel_mult) * [num_res_blocks] else: if len(num_res_blocks) != len(channel_mult): raise ValueError("provide num_res_blocks either as an int (globally constant) or " "as a list/tuple (per-level) with the same length as channel_mult") self.num_res_blocks = num_res_blocks if disable_self_attentions is not None: # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not assert len(disable_self_attentions) == len(channel_mult) if num_attention_blocks is not None: assert len(num_attention_blocks) == len(self.num_res_blocks) transformer_depth = transformer_depth[:] transformer_depth_output = transformer_depth_output[:] self.dropout = dropout self.channel_mult = channel_mult self.conv_resample = conv_resample self.num_classes = num_classes self.use_checkpoint = use_checkpoint self.dtype = dtype self.num_heads = num_heads self.num_head_channels = num_head_channels self.num_heads_upsample = num_heads_upsample self.use_temporal_resblocks = use_temporal_resblock self.predict_codebook_ids = n_embed is not None self.default_num_video_frames = None self.default_image_only_indicator = None time_embed_dim = model_channels * 4 self.time_embed = nn.Sequential( operations.Linear(model_channels, time_embed_dim, dtype=self.dtype, device=device), nn.SiLU(), operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device), ) if self.num_classes is not None: if isinstance(self.num_classes, int): self.label_emb = nn.Embedding(num_classes, time_embed_dim, dtype=self.dtype, device=device) elif self.num_classes == "continuous": print("setting up linear c_adm embedding layer") self.label_emb = nn.Linear(1, time_embed_dim) elif self.num_classes == "sequential": assert adm_in_channels is not None self.label_emb = nn.Sequential( nn.Sequential( operations.Linear(adm_in_channels, time_embed_dim, dtype=self.dtype, device=device), nn.SiLU(), operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device), ) ) else: raise ValueError() self.input_blocks = nn.ModuleList( [ TimestepEmbedSequential( operations.conv_nd(dims, in_channels, model_channels, 3, padding=1, dtype=self.dtype, device=device) ) ] ) self._feature_size = model_channels input_block_chans = [model_channels] ch = model_channels ds = 1 def get_attention_layer( ch, num_heads, dim_head, depth=1, context_dim=None, use_checkpoint=False, disable_self_attn=False, ): if use_temporal_attention: return SpatialVideoTransformer( ch, num_heads, dim_head, depth=depth, context_dim=context_dim, time_context_dim=time_context_dim, dropout=dropout, ff_in=extra_ff_mix_layer, use_spatial_context=use_spatial_context, merge_strategy=merge_strategy, merge_factor=merge_factor, checkpoint=use_checkpoint, use_linear=use_linear_in_transformer, disable_self_attn=disable_self_attn, disable_temporal_crossattention=disable_temporal_crossattention, max_time_embed_period=max_ddpm_temb_period, dtype=self.dtype, device=device, operations=operations ) else: return SpatialTransformer( ch, num_heads, dim_head, depth=depth, context_dim=context_dim, disable_self_attn=disable_self_attn, use_linear=use_linear_in_transformer, use_checkpoint=use_checkpoint, dtype=self.dtype, device=device, operations=operations ) def get_resblock( merge_factor, merge_strategy, video_kernel_size, ch, time_embed_dim, dropout, out_channels, dims, use_checkpoint, use_scale_shift_norm, down=False, up=False, dtype=None, device=None, operations=ops ): if self.use_temporal_resblocks: return VideoResBlock( merge_factor=merge_factor, merge_strategy=merge_strategy, video_kernel_size=video_kernel_size, channels=ch, emb_channels=time_embed_dim, dropout=dropout, out_channels=out_channels, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, down=down, up=up, dtype=dtype, device=device, operations=operations ) else: return ResBlock( channels=ch, emb_channels=time_embed_dim, dropout=dropout, out_channels=out_channels, use_checkpoint=use_checkpoint, dims=dims, use_scale_shift_norm=use_scale_shift_norm, down=down, up=up, dtype=dtype, device=device, operations=operations ) for level, mult in enumerate(channel_mult): for nr in range(self.num_res_blocks[level]): layers = [ get_resblock( merge_factor=merge_factor, merge_strategy=merge_strategy, video_kernel_size=video_kernel_size, ch=ch, time_embed_dim=time_embed_dim, dropout=dropout, out_channels=mult * model_channels, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, dtype=self.dtype, device=device, operations=operations, ) ] ch = mult * model_channels num_transformers = transformer_depth.pop(0) if num_transformers > 0: if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels if legacy: #num_heads = 1 dim_head = ch // num_heads if use_spatial_transformer else num_head_channels if exists(disable_self_attentions): disabled_sa = disable_self_attentions[level] else: disabled_sa = False if not exists(num_attention_blocks) or nr < num_attention_blocks[level]: layers.append(get_attention_layer( ch, num_heads, dim_head, depth=num_transformers, context_dim=context_dim, disable_self_attn=disabled_sa, use_checkpoint=use_checkpoint) ) self.input_blocks.append(TimestepEmbedSequential(*layers)) self._feature_size += ch input_block_chans.append(ch) if level != len(channel_mult) - 1: out_ch = ch self.input_blocks.append( TimestepEmbedSequential( get_resblock( merge_factor=merge_factor, merge_strategy=merge_strategy, video_kernel_size=video_kernel_size, ch=ch, time_embed_dim=time_embed_dim, dropout=dropout, out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, down=True, dtype=self.dtype, device=device, operations=operations ) if resblock_updown else Downsample( ch, conv_resample, dims=dims, out_channels=out_ch, dtype=self.dtype, device=device, operations=operations ) ) ) ch = out_ch input_block_chans.append(ch) ds *= 2 self._feature_size += ch if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels if legacy: #num_heads = 1 dim_head = ch // num_heads if use_spatial_transformer else num_head_channels mid_block = [ get_resblock( merge_factor=merge_factor, merge_strategy=merge_strategy, video_kernel_size=video_kernel_size, ch=ch, time_embed_dim=time_embed_dim, dropout=dropout, out_channels=None, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, dtype=self.dtype, device=device, operations=operations )] if transformer_depth_middle >= 0: mid_block += [get_attention_layer( # always uses a self-attn ch, num_heads, dim_head, depth=transformer_depth_middle, context_dim=context_dim, disable_self_attn=disable_middle_self_attn, use_checkpoint=use_checkpoint ), get_resblock( merge_factor=merge_factor, merge_strategy=merge_strategy, video_kernel_size=video_kernel_size, ch=ch, time_embed_dim=time_embed_dim, dropout=dropout, out_channels=None, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, dtype=self.dtype, device=device, operations=operations )] self.middle_block = TimestepEmbedSequential(*mid_block) self._feature_size += ch self.output_blocks = nn.ModuleList([]) for level, mult in list(enumerate(channel_mult))[::-1]: for i in range(self.num_res_blocks[level] + 1): ich = input_block_chans.pop() layers = [ get_resblock( merge_factor=merge_factor, merge_strategy=merge_strategy, video_kernel_size=video_kernel_size, ch=ch + ich, time_embed_dim=time_embed_dim, dropout=dropout, out_channels=model_channels * mult, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, dtype=self.dtype, device=device, operations=operations ) ] ch = model_channels * mult num_transformers = transformer_depth_output.pop() if num_transformers > 0: if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels if legacy: #num_heads = 1 dim_head = ch // num_heads if use_spatial_transformer else num_head_channels if exists(disable_self_attentions): disabled_sa = disable_self_attentions[level] else: disabled_sa = False if not exists(num_attention_blocks) or i < num_attention_blocks[level]: layers.append( get_attention_layer( ch, num_heads, dim_head, depth=num_transformers, context_dim=context_dim, disable_self_attn=disabled_sa, use_checkpoint=use_checkpoint ) ) if level and i == self.num_res_blocks[level]: out_ch = ch layers.append( get_resblock( merge_factor=merge_factor, merge_strategy=merge_strategy, video_kernel_size=video_kernel_size, ch=ch, time_embed_dim=time_embed_dim, dropout=dropout, out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, up=True, dtype=self.dtype, device=device, operations=operations ) if resblock_updown else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch, dtype=self.dtype, device=device, operations=operations) ) ds //= 2 self.output_blocks.append(TimestepEmbedSequential(*layers)) self._feature_size += ch self.out = nn.Sequential( operations.GroupNorm(32, ch, dtype=self.dtype, device=device), nn.SiLU(), zero_module(operations.conv_nd(dims, model_channels, out_channels, 3, padding=1, dtype=self.dtype, device=device)), ) if self.predict_codebook_ids: self.id_predictor = nn.Sequential( operations.GroupNorm(32, ch, dtype=self.dtype, device=device), operations.conv_nd(dims, model_channels, n_embed, 1, dtype=self.dtype, device=device), #nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits ) def forward(self, x, timesteps=None, context=None, y=None, control=None, transformer_options={}, **kwargs): transformer_options["original_shape"] = list(x.shape) transformer_options["transformer_index"] = 0 transformer_patches = transformer_options.get("patches", {}) num_video_frames = kwargs.get("num_video_frames", self.default_num_video_frames) image_only_indicator = kwargs.get("image_only_indicator", self.default_image_only_indicator) time_context = kwargs.get("time_context", None) assert (y is not None) == ( self.num_classes is not None ), "must specify y if and only if the model is class-conditional" hs = [] t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype) emb = self.time_embed(t_emb) if self.num_classes is not None: assert y.shape[0] == x.shape[0] emb = emb + self.label_emb(y) h = x for id, module in enumerate(self.input_blocks): transformer_options["block"] = ("input", id) h = forward_timestep_embed(module, h, emb, context, transformer_options, time_context=time_context, num_video_frames=num_video_frames, image_only_indicator=image_only_indicator) h = apply_control(h, control, 'input') if "input_block_patch" in transformer_patches: patch = transformer_patches["input_block_patch"] for p in patch: h = p(h, transformer_options) hs.append(h) if "input_block_patch_after_skip" in transformer_patches: patch = transformer_patches["input_block_patch_after_skip"] for p in patch: h = p(h, transformer_options) transformer_options["block"] = ("middle", 0) h = forward_timestep_embed(self.middle_block, h, emb, context, transformer_options, time_context=time_context, num_video_frames=num_video_frames, image_only_indicator=image_only_indicator) h = apply_control(h, control, 'middle') for id, module in enumerate(self.output_blocks): transformer_options["block"] = ("output", id) hsp = hs.pop() hsp = apply_control(hsp, control, 'output') if "output_block_patch" in transformer_patches: patch = transformer_patches["output_block_patch"] for p in patch: h, hsp = p(h, hsp, transformer_options) h = th.cat([h, hsp], dim=1) del hsp if len(hs) > 0: output_shape = hs[-1].shape else: output_shape = None h = forward_timestep_embed(module, h, emb, context, transformer_options, output_shape, time_context=time_context, num_video_frames=num_video_frames, image_only_indicator=image_only_indicator) h = h.type(x.dtype) if self.predict_codebook_ids: return self.id_predictor(h) else: return self.out(h)
--- +++ @@ -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 `emb` timestep embeddings. + """ #This is needed because accelerate makes a copy of transformer_options which breaks "transformer_index" def forward_timestep_embed(ts, x, emb, context=None, transformer_options={}, output_shape=None, time_context=None, num_video_frames=None, image_only_indicator=None): @@ -44,11 +50,22 @@ return x class TimestepEmbedSequential(nn.Sequential, TimestepBlock): + """ + A sequential module that passes timestep embeddings to the children that + support it as an extra input. + """ def forward(self, *args, **kwargs): return forward_timestep_embed(self, *args, **kwargs) class Upsample(nn.Module): + """ + An upsampling layer with an optional convolution. + :param channels: channels in the inputs and outputs. + :param use_conv: a bool determining if a convolution is applied. + :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then + upsampling occurs in the inner-two dimensions. + """ def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1, dtype=None, device=None, operations=ops): super().__init__() @@ -78,6 +95,13 @@ return x class Downsample(nn.Module): + """ + A downsampling layer with an optional convolution. + :param channels: channels in the inputs and outputs. + :param use_conv: a bool determining if a convolution is applied. + :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then + downsampling occurs in the inner-two dimensions. + """ def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1, dtype=None, device=None, operations=ops): super().__init__() @@ -100,6 +124,20 @@ class ResBlock(TimestepBlock): + """ + A residual block that can optionally change the number of channels. + :param channels: the number of input channels. + :param emb_channels: the number of timestep embedding channels. + :param dropout: the rate of dropout. + :param out_channels: if specified, the number of out channels. + :param use_conv: if True and out_channels is specified, use a spatial + convolution instead of a smaller 1x1 convolution to change the + channels in the skip connection. + :param dims: determines if the signal is 1D, 2D, or 3D. + :param use_checkpoint: if True, use gradient checkpointing on this module. + :param up: if True, use this block for upsampling. + :param down: if True, use this block for downsampling. + """ def __init__( self, @@ -182,6 +220,12 @@ self.skip_connection = operations.conv_nd(dims, channels, self.out_channels, 1, dtype=dtype, device=device) def forward(self, x, emb): + """ + Apply the block to a Tensor, conditioned on a timestep embedding. + :param x: an [N x C x ...] Tensor of features. + :param emb: an [N x emb_channels] Tensor of timestep embeddings. + :return: an [N x C x ...] Tensor of outputs. + """ return checkpoint( self._forward, (x, emb), self.parameters(), self.use_checkpoint ) @@ -319,6 +363,30 @@ return h class UNetModel(nn.Module): + """ + The full UNet model with attention and timestep embedding. + :param in_channels: channels in the input Tensor. + :param model_channels: base channel count for the model. + :param out_channels: channels in the output Tensor. + :param num_res_blocks: number of residual blocks per downsample. + :param dropout: the dropout probability. + :param channel_mult: channel multiplier for each level of the UNet. + :param conv_resample: if True, use learned convolutions for upsampling and + downsampling. + :param dims: determines if the signal is 1D, 2D, or 3D. + :param num_classes: if specified (as an int), then this model will be + class-conditional with `num_classes` classes. + :param use_checkpoint: use gradient checkpointing to reduce memory usage. + :param num_heads: the number of attention heads in each attention layer. + :param num_heads_channels: if specified, ignore num_heads and instead use + a fixed channel width per attention head. + :param num_heads_upsample: works with num_heads to set a different number + of heads for upsampling. Deprecated. + :param use_scale_shift_norm: use a FiLM-like conditioning mechanism. + :param resblock_updown: use residual blocks for up/downsampling. + :param use_new_attention_order: use a different attention pattern for potentially + increased efficiency. + """ def __init__( self, @@ -746,6 +814,14 @@ ) def forward(self, x, timesteps=None, context=None, y=None, control=None, transformer_options={}, **kwargs): + """ + Apply the model to an input batch. + :param x: an [N x C x ...] Tensor of inputs. + :param timesteps: a 1-D batch of timesteps. + :param context: conditioning plugged in via crossattn + :param y: an [N] Tensor of labels, if class-conditional. + :return: an [N x C x ...] Tensor of outputs. + """ transformer_options["original_shape"] = list(x.shape) transformer_options["transformer_index"] = 0 transformer_patches = transformer_options.get("patches", {}) @@ -807,4 +883,4 @@ if self.predict_codebook_ids: return self.id_predictor(h) else: - return self.out(h)+ return self.out(h)
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_checkpoint class BLIP_Pretrain(nn.Module): def __init__(self, med_config = 'configs/bert_config.json', image_size = 224, vit = 'base', vit_grad_ckpt = False, vit_ckpt_layer = 0, embed_dim = 256, queue_size = 57600, momentum = 0.995, ): super().__init__() self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer, 0) if vit=='base': checkpoint = torch.hub.load_state_dict_from_url( url="https://dl.fbaipublicfiles.com/deit/deit_base_patch16_224-b5f2ef4d.pth", map_location="cpu", check_hash=True) state_dict = checkpoint["model"] msg = self.visual_encoder.load_state_dict(state_dict,strict=False) elif vit=='large': from timm.models.helpers import load_custom_pretrained from timm.models.vision_transformer import default_cfgs load_custom_pretrained(self.visual_encoder,default_cfgs['vit_large_patch16_224_in21k']) self.tokenizer = init_tokenizer() encoder_config = BertConfig.from_json_file(med_config) encoder_config.encoder_width = vision_width self.text_encoder = BertModel.from_pretrained('bert-base-uncased',config=encoder_config, add_pooling_layer=False) self.text_encoder.resize_token_embeddings(len(self.tokenizer)) text_width = self.text_encoder.config.hidden_size self.vision_proj = nn.Linear(vision_width, embed_dim) self.text_proj = nn.Linear(text_width, embed_dim) self.itm_head = nn.Linear(text_width, 2) # create momentum encoders self.visual_encoder_m, vision_width = create_vit(vit,image_size) self.vision_proj_m = nn.Linear(vision_width, embed_dim) self.text_encoder_m = BertModel(config=encoder_config, add_pooling_layer=False) self.text_proj_m = nn.Linear(text_width, embed_dim) self.model_pairs = [[self.visual_encoder,self.visual_encoder_m], [self.vision_proj,self.vision_proj_m], [self.text_encoder,self.text_encoder_m], [self.text_proj,self.text_proj_m], ] self.copy_params() # create the queue self.register_buffer("image_queue", torch.randn(embed_dim, queue_size)) self.register_buffer("text_queue", torch.randn(embed_dim, queue_size)) self.register_buffer("queue_ptr", torch.zeros(1, dtype=torch.long)) self.image_queue = nn.functional.normalize(self.image_queue, dim=0) self.text_queue = nn.functional.normalize(self.text_queue, dim=0) self.queue_size = queue_size self.momentum = momentum self.temp = nn.Parameter(0.07*torch.ones([])) # create the decoder decoder_config = BertConfig.from_json_file(med_config) decoder_config.encoder_width = vision_width self.text_decoder = BertLMHeadModel.from_pretrained('bert-base-uncased',config=decoder_config) self.text_decoder.resize_token_embeddings(len(self.tokenizer)) tie_encoder_decoder_weights(self.text_encoder,self.text_decoder.bert,'','/attention') def forward(self, image, caption, alpha): with torch.no_grad(): self.temp.clamp_(0.001,0.5) image_embeds = self.visual_encoder(image) image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device) image_feat = F.normalize(self.vision_proj(image_embeds[:,0,:]),dim=-1) text = self.tokenizer(caption, padding='max_length', truncation=True, max_length=30, return_tensors="pt").to(image.device) text_output = self.text_encoder(text.input_ids, attention_mask = text.attention_mask, return_dict = True, mode = 'text') text_feat = F.normalize(self.text_proj(text_output.last_hidden_state[:,0,:]),dim=-1) # get momentum features with torch.no_grad(): self._momentum_update() image_embeds_m = self.visual_encoder_m(image) image_feat_m = F.normalize(self.vision_proj_m(image_embeds_m[:,0,:]),dim=-1) image_feat_all = torch.cat([image_feat_m.t(),self.image_queue.clone().detach()],dim=1) text_output_m = self.text_encoder_m(text.input_ids, attention_mask = text.attention_mask, return_dict = True, mode = 'text') text_feat_m = F.normalize(self.text_proj_m(text_output_m.last_hidden_state[:,0,:]),dim=-1) text_feat_all = torch.cat([text_feat_m.t(),self.text_queue.clone().detach()],dim=1) sim_i2t_m = image_feat_m @ text_feat_all / self.temp sim_t2i_m = text_feat_m @ image_feat_all / self.temp sim_targets = torch.zeros(sim_i2t_m.size()).to(image.device) sim_targets.fill_diagonal_(1) sim_i2t_targets = alpha * F.softmax(sim_i2t_m, dim=1) + (1 - alpha) * sim_targets sim_t2i_targets = alpha * F.softmax(sim_t2i_m, dim=1) + (1 - alpha) * sim_targets sim_i2t = image_feat @ text_feat_all / self.temp sim_t2i = text_feat @ image_feat_all / self.temp loss_i2t = -torch.sum(F.log_softmax(sim_i2t, dim=1)*sim_i2t_targets,dim=1).mean() loss_t2i = -torch.sum(F.log_softmax(sim_t2i, dim=1)*sim_t2i_targets,dim=1).mean() loss_ita = (loss_i2t+loss_t2i)/2 self._dequeue_and_enqueue(image_feat_m, text_feat_m) ###============== Image-text Matching ===================### encoder_input_ids = text.input_ids.clone() encoder_input_ids[:,0] = self.tokenizer.enc_token_id # forward the positve image-text pair bs = image.size(0) output_pos = self.text_encoder(encoder_input_ids, attention_mask = text.attention_mask, encoder_hidden_states = image_embeds, encoder_attention_mask = image_atts, return_dict = True, ) with torch.no_grad(): weights_t2i = F.softmax(sim_t2i[:,:bs],dim=1)+1e-4 weights_t2i.fill_diagonal_(0) weights_i2t = F.softmax(sim_i2t[:,:bs],dim=1)+1e-4 weights_i2t.fill_diagonal_(0) # select a negative image for each text image_embeds_neg = [] for b in range(bs): neg_idx = torch.multinomial(weights_t2i[b], 1).item() image_embeds_neg.append(image_embeds[neg_idx]) image_embeds_neg = torch.stack(image_embeds_neg,dim=0) # select a negative text for each image text_ids_neg = [] text_atts_neg = [] for b in range(bs): neg_idx = torch.multinomial(weights_i2t[b], 1).item() text_ids_neg.append(encoder_input_ids[neg_idx]) text_atts_neg.append(text.attention_mask[neg_idx]) text_ids_neg = torch.stack(text_ids_neg,dim=0) text_atts_neg = torch.stack(text_atts_neg,dim=0) text_ids_all = torch.cat([encoder_input_ids, text_ids_neg],dim=0) text_atts_all = torch.cat([text.attention_mask, text_atts_neg],dim=0) image_embeds_all = torch.cat([image_embeds_neg,image_embeds],dim=0) image_atts_all = torch.cat([image_atts,image_atts],dim=0) output_neg = self.text_encoder(text_ids_all, attention_mask = text_atts_all, encoder_hidden_states = image_embeds_all, encoder_attention_mask = image_atts_all, return_dict = True, ) vl_embeddings = torch.cat([output_pos.last_hidden_state[:,0,:], output_neg.last_hidden_state[:,0,:]],dim=0) vl_output = self.itm_head(vl_embeddings) itm_labels = torch.cat([torch.ones(bs,dtype=torch.long),torch.zeros(2*bs,dtype=torch.long)], dim=0).to(image.device) loss_itm = F.cross_entropy(vl_output, itm_labels) ##================= LM ========================## decoder_input_ids = text.input_ids.clone() decoder_input_ids[:,0] = self.tokenizer.bos_token_id decoder_targets = decoder_input_ids.masked_fill(decoder_input_ids == self.tokenizer.pad_token_id, -100) decoder_output = self.text_decoder(decoder_input_ids, attention_mask = text.attention_mask, encoder_hidden_states = image_embeds, encoder_attention_mask = image_atts, labels = decoder_targets, return_dict = True, ) loss_lm = decoder_output.loss return loss_ita, loss_itm, loss_lm @torch.no_grad() def copy_params(self): for model_pair in self.model_pairs: for param, param_m in zip(model_pair[0].parameters(), model_pair[1].parameters()): param_m.data.copy_(param.data) # initialize param_m.requires_grad = False # not update by gradient @torch.no_grad() def _momentum_update(self): for model_pair in self.model_pairs: for param, param_m in zip(model_pair[0].parameters(), model_pair[1].parameters()): param_m.data = param_m.data * self.momentum + param.data * (1. - self.momentum) @torch.no_grad() def _dequeue_and_enqueue(self, image_feat, text_feat): # gather keys before updating queue image_feats = concat_all_gather(image_feat) text_feats = concat_all_gather(text_feat) batch_size = image_feats.shape[0] ptr = int(self.queue_ptr) assert self.queue_size % batch_size == 0 # for simplicity # replace the keys at ptr (dequeue and enqueue) self.image_queue[:, ptr:ptr + batch_size] = image_feats.T self.text_queue[:, ptr:ptr + batch_size] = text_feats.T ptr = (ptr + batch_size) % self.queue_size # move pointer self.queue_ptr[0] = ptr def blip_pretrain(**kwargs): model = BLIP_Pretrain(**kwargs) return model @torch.no_grad() def concat_all_gather(tensor): tensors_gather = [torch.ones_like(tensor) for _ in range(torch.distributed.get_world_size())] torch.distributed.all_gather(tensors_gather, tensor, async_op=False) output = torch.cat(tensors_gather, dim=0) return output from typing import List def tie_encoder_decoder_weights(encoder: nn.Module, decoder: nn.Module, base_model_prefix: str, skip_key:str): uninitialized_encoder_weights: List[str] = [] if decoder.__class__ != encoder.__class__: print( f"{decoder.__class__} and {encoder.__class__} are not equal. In this case make sure that all encoder weights are correctly initialized." ) def tie_encoder_to_decoder_recursively( decoder_pointer: nn.Module, encoder_pointer: nn.Module, module_name: str, uninitialized_encoder_weights: List[str], skip_key: str, depth=0, ): assert isinstance(decoder_pointer, nn.Module) and isinstance( encoder_pointer, nn.Module ), f"{decoder_pointer} and {encoder_pointer} have to be of type torch.nn.Module" if hasattr(decoder_pointer, "weight") and skip_key not in module_name: assert hasattr(encoder_pointer, "weight") encoder_pointer.weight = decoder_pointer.weight if hasattr(decoder_pointer, "bias"): assert hasattr(encoder_pointer, "bias") encoder_pointer.bias = decoder_pointer.bias print(module_name+' is tied') return encoder_modules = encoder_pointer._modules decoder_modules = decoder_pointer._modules if len(decoder_modules) > 0: assert ( len(encoder_modules) > 0 ), f"Encoder module {encoder_pointer} does not match decoder module {decoder_pointer}" all_encoder_weights = set([module_name + "/" + sub_name for sub_name in encoder_modules.keys()]) encoder_layer_pos = 0 for name, module in decoder_modules.items(): if name.isdigit(): encoder_name = str(int(name) + encoder_layer_pos) decoder_name = name if not isinstance(decoder_modules[decoder_name], type(encoder_modules[encoder_name])) and len( encoder_modules ) != len(decoder_modules): # this can happen if the name corresponds to the position in a list module list of layers # in this case the decoder has added a cross-attention that the encoder does not have # thus skip this step and subtract one layer pos from encoder encoder_layer_pos -= 1 continue elif name not in encoder_modules: continue elif depth > 500: raise ValueError( "Max depth of recursive function `tie_encoder_to_decoder` reached. It seems that there is a circular dependency between two or more `nn.Modules` of your model." ) else: decoder_name = encoder_name = name tie_encoder_to_decoder_recursively( decoder_modules[decoder_name], encoder_modules[encoder_name], module_name + "/" + name, uninitialized_encoder_weights, skip_key, depth=depth + 1, ) all_encoder_weights.remove(module_name + "/" + encoder_name) uninitialized_encoder_weights += list(all_encoder_weights) # tie weights recursively tie_encoder_to_decoder_recursively(decoder, encoder, base_model_prefix, uninitialized_encoder_weights, skip_key)
--- +++ @@ -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 BertConfig, BertModel, BertLMHeadModel from transformers import BertTokenizer import transformers @@ -20,6 +27,12 @@ queue_size = 57600, momentum = 0.995, ): + """ + Args: + med_config (str): path for the mixture of encoder-decoder model's configuration file + image_size (int): input image size + vit (str): model size of vision transformer + """ super().__init__() self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer, 0) @@ -241,6 +254,10 @@ @torch.no_grad() def concat_all_gather(tensor): + """ + Performs all_gather operation on the provided tensors. + *** Warning ***: torch.distributed.all_gather has no gradient. + """ tensors_gather = [torch.ones_like(tensor) for _ in range(torch.distributed.get_world_size())] torch.distributed.all_gather(tensors_gather, tensor, async_op=False) @@ -319,4 +336,4 @@ uninitialized_encoder_weights += list(all_encoder_weights) # tie weights recursively - tie_encoder_to_decoder_recursively(decoder, encoder, base_model_prefix, uninitialized_encoder_weights, skip_key) + tie_encoder_to_decoder_recursively(decoder, encoder, base_model_prefix, uninitialized_encoder_weights, skip_key)
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('decay', torch.tensor(decay, dtype=torch.float32)) self.register_buffer('num_updates', torch.tensor(0, dtype=torch.int) if use_num_upates else torch.tensor(-1, dtype=torch.int)) for name, p in model.named_parameters(): if p.requires_grad: # remove as '.'-character is not allowed in buffers s_name = name.replace('.', '') self.m_name2s_name.update({name: s_name}) self.register_buffer(s_name, p.clone().detach().data) self.collected_params = [] def reset_num_updates(self): del self.num_updates self.register_buffer('num_updates', torch.tensor(0, dtype=torch.int)) def forward(self, model): decay = self.decay if self.num_updates >= 0: self.num_updates += 1 decay = min(self.decay, (1 + self.num_updates) / (10 + self.num_updates)) one_minus_decay = 1.0 - decay with torch.no_grad(): m_param = dict(model.named_parameters()) shadow_params = dict(self.named_buffers()) for key in m_param: if m_param[key].requires_grad: sname = self.m_name2s_name[key] shadow_params[sname] = shadow_params[sname].type_as(m_param[key]) shadow_params[sname].sub_(one_minus_decay * (shadow_params[sname] - m_param[key])) else: assert not key in self.m_name2s_name def copy_to(self, model): m_param = dict(model.named_parameters()) shadow_params = dict(self.named_buffers()) for key in m_param: if m_param[key].requires_grad: m_param[key].data.copy_(shadow_params[self.m_name2s_name[key]].data) else: assert not key in self.m_name2s_name def store(self, parameters): self.collected_params = [param.clone() for param in parameters] def restore(self, parameters): for c_param, param in zip(self.collected_params, parameters): param.data.copy_(c_param.data)
--- +++ @@ -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. + """ self.collected_params = [param.clone() for param in parameters] def restore(self, parameters): + """ + Restore the parameters stored with the `store` method. + Useful to validate the model with EMA parameters without affecting the + original optimization process. Store the parameters before the + `copy_to` method. After validation (or model saving), use this to + restore the former parameters. + Args: + parameters: Iterable of `torch.nn.Parameter`; the parameters to be + updated with the stored parameters. + """ for c_param, param in zip(self.collected_params, parameters): - param.data.copy_(c_param.data)+ param.data.copy_(c_param.data)
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/guided-diffusion/blob/0ba878e517b276c45d1195eb29f6f5f72659a05b/guided_diffusion/nn.py # # thanks! import os import math import torch import torch.nn as nn import numpy as np from einops import repeat, rearrange from ldm_patched.ldm.util import instantiate_from_config class AlphaBlender(nn.Module): strategies = ["learned", "fixed", "learned_with_images"] def __init__( self, alpha: float, merge_strategy: str = "learned_with_images", rearrange_pattern: str = "b t -> (b t) 1 1", ): super().__init__() self.merge_strategy = merge_strategy self.rearrange_pattern = rearrange_pattern assert ( merge_strategy in self.strategies ), f"merge_strategy needs to be in {self.strategies}" if self.merge_strategy == "fixed": self.register_buffer("mix_factor", torch.Tensor([alpha])) elif ( self.merge_strategy == "learned" or self.merge_strategy == "learned_with_images" ): self.register_parameter( "mix_factor", torch.nn.Parameter(torch.Tensor([alpha])) ) else: raise ValueError(f"unknown merge strategy {self.merge_strategy}") def get_alpha(self, image_only_indicator: torch.Tensor) -> torch.Tensor: # skip_time_mix = rearrange(repeat(skip_time_mix, 'b -> (b t) () () ()', t=t), '(b t) 1 ... -> b 1 t ...', t=t) if self.merge_strategy == "fixed": # make shape compatible # alpha = repeat(self.mix_factor, '1 -> b () t () ()', t=t, b=bs) alpha = self.mix_factor.to(image_only_indicator.device) elif self.merge_strategy == "learned": alpha = torch.sigmoid(self.mix_factor.to(image_only_indicator.device)) # make shape compatible # alpha = repeat(alpha, '1 -> s () ()', s = t * bs) elif self.merge_strategy == "learned_with_images": assert image_only_indicator is not None, "need image_only_indicator ..." alpha = torch.where( image_only_indicator.bool(), torch.ones(1, 1, device=image_only_indicator.device), rearrange(torch.sigmoid(self.mix_factor.to(image_only_indicator.device)), "... -> ... 1"), ) alpha = rearrange(alpha, self.rearrange_pattern) # make shape compatible # alpha = repeat(alpha, '1 -> s () ()', s = t * bs) else: raise NotImplementedError() return alpha def forward( self, x_spatial, x_temporal, image_only_indicator=None, ) -> torch.Tensor: alpha = self.get_alpha(image_only_indicator) x = ( alpha.to(x_spatial.dtype) * x_spatial + (1.0 - alpha).to(x_spatial.dtype) * x_temporal ) return x def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): if schedule == "linear": betas = ( torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2 ) elif schedule == "cosine": timesteps = ( torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s ) alphas = timesteps / (1 + cosine_s) * np.pi / 2 alphas = torch.cos(alphas).pow(2) alphas = alphas / alphas[0] betas = 1 - alphas[1:] / alphas[:-1] betas = np.clip(betas, a_min=0, a_max=0.999) elif schedule == "squaredcos_cap_v2": # used for karlo prior # return early return betas_for_alpha_bar( n_timestep, lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2, ) elif schedule == "sqrt_linear": betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) elif schedule == "sqrt": betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) ** 0.5 else: raise ValueError(f"schedule '{schedule}' unknown.") return betas.numpy() def make_ddim_timesteps(ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True): if ddim_discr_method == 'uniform': c = num_ddpm_timesteps // num_ddim_timesteps ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c))) elif ddim_discr_method == 'quad': ddim_timesteps = ((np.linspace(0, np.sqrt(num_ddpm_timesteps * .8), num_ddim_timesteps)) ** 2).astype(int) else: raise NotImplementedError(f'There is no ddim discretization method called "{ddim_discr_method}"') # assert ddim_timesteps.shape[0] == num_ddim_timesteps # add one to get the final alpha values right (the ones from first scale to data during sampling) steps_out = ddim_timesteps + 1 if verbose: print(f'Selected timesteps for ddim sampler: {steps_out}') return steps_out def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True): # select alphas for computing the variance schedule alphas = alphacums[ddim_timesteps] alphas_prev = np.asarray([alphacums[0]] + alphacums[ddim_timesteps[:-1]].tolist()) # according the the formula provided in https://arxiv.org/abs/2010.02502 sigmas = eta * np.sqrt((1 - alphas_prev) / (1 - alphas) * (1 - alphas / alphas_prev)) if verbose: print(f'Selected alphas for ddim sampler: a_t: {alphas}; a_(t-1): {alphas_prev}') print(f'For the chosen value of eta, which is {eta}, ' f'this results in the following sigma_t schedule for ddim sampler {sigmas}') return sigmas, alphas, alphas_prev def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999): betas = [] for i in range(num_diffusion_timesteps): t1 = i / num_diffusion_timesteps t2 = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta)) return np.array(betas) def extract_into_tensor(a, t, x_shape): b, *_ = t.shape out = a.gather(-1, t) return out.reshape(b, *((1,) * (len(x_shape) - 1))) def checkpoint(func, inputs, params, flag): if flag: args = tuple(inputs) + tuple(params) return CheckpointFunction.apply(func, len(inputs), *args) else: return func(*inputs) class CheckpointFunction(torch.autograd.Function): @staticmethod def forward(ctx, run_function, length, *args): ctx.run_function = run_function ctx.input_tensors = list(args[:length]) ctx.input_params = list(args[length:]) ctx.gpu_autocast_kwargs = {"enabled": torch.is_autocast_enabled(), "dtype": torch.get_autocast_gpu_dtype(), "cache_enabled": torch.is_autocast_cache_enabled()} with torch.no_grad(): output_tensors = ctx.run_function(*ctx.input_tensors) return output_tensors @staticmethod def backward(ctx, *output_grads): ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors] with torch.enable_grad(), \ torch.cuda.amp.autocast(**ctx.gpu_autocast_kwargs): # Fixes a bug where the first op in run_function modifies the # Tensor storage in place, which is not allowed for detach()'d # Tensors. shallow_copies = [x.view_as(x) for x in ctx.input_tensors] output_tensors = ctx.run_function(*shallow_copies) input_grads = torch.autograd.grad( output_tensors, ctx.input_tensors + ctx.input_params, output_grads, allow_unused=True, ) del ctx.input_tensors del ctx.input_params del output_tensors return (None, None) + input_grads def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False): if not repeat_only: half = dim // 2 freqs = torch.exp( -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=timesteps.device) / half ) args = timesteps[:, None].float() * freqs[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) if dim % 2: embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) else: embedding = repeat(timesteps, 'b -> b d', d=dim) return embedding def zero_module(module): for p in module.parameters(): p.detach().zero_() return module def scale_module(module, scale): for p in module.parameters(): p.detach().mul_(scale) return module def mean_flat(tensor): return tensor.mean(dim=list(range(1, len(tensor.shape)))) def avg_pool_nd(dims, *args, **kwargs): if dims == 1: return nn.AvgPool1d(*args, **kwargs) elif dims == 2: return nn.AvgPool2d(*args, **kwargs) elif dims == 3: return nn.AvgPool3d(*args, **kwargs) raise ValueError(f"unsupported dimensions: {dims}") class HybridConditioner(nn.Module): def __init__(self, c_concat_config, c_crossattn_config): super().__init__() self.concat_conditioner = instantiate_from_config(c_concat_config) self.crossattn_conditioner = instantiate_from_config(c_crossattn_config) def forward(self, c_concat, c_crossattn): c_concat = self.concat_conditioner(c_concat) c_crossattn = self.crossattn_conditioner(c_crossattn) return {'c_concat': [c_concat], 'c_crossattn': [c_crossattn]} def noise_like(shape, device, repeat=False): repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1))) noise = lambda: torch.randn(shape, device=device) return repeat_noise() if repeat else noise()
--- +++ @@ -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 number of betas to produce. + :param alpha_bar: a lambda that takes an argument t from 0 to 1 and + produces the cumulative product of (1-beta) up to that + part of the diffusion process. + :param max_beta: the maximum beta to use; use values lower than 1 to + prevent singularities. + """ betas = [] for i in range(num_diffusion_timesteps): t1 = i / num_diffusion_timesteps @@ -163,6 +173,15 @@ def checkpoint(func, inputs, params, flag): + """ + Evaluate a function without caching intermediate activations, allowing for + reduced memory at the expense of extra compute in the backward pass. + :param func: the function to evaluate. + :param inputs: the argument sequence to pass to `func`. + :param params: a sequence of parameters `func` depends on but does not + explicitly take as arguments. + :param flag: if False, disable gradient checkpointing. + """ if flag: args = tuple(inputs) + tuple(params) return CheckpointFunction.apply(func, len(inputs), *args) @@ -206,6 +225,14 @@ def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False): + """ + Create sinusoidal timestep embeddings. + :param timesteps: a 1-D Tensor of N indices, one per batch element. + These may be fractional. + :param dim: the dimension of the output. + :param max_period: controls the minimum frequency of the embeddings. + :return: an [N x dim] Tensor of positional embeddings. + """ if not repeat_only: half = dim // 2 freqs = torch.exp( @@ -221,22 +248,34 @@ def zero_module(module): + """ + Zero out the parameters of a module and return it. + """ for p in module.parameters(): p.detach().zero_() return module def scale_module(module, scale): + """ + Scale the parameters of a module and return it. + """ for p in module.parameters(): p.detach().mul_(scale) return module def mean_flat(tensor): + """ + Take the mean over all non-batch dimensions. + """ return tensor.mean(dim=list(range(1, len(tensor.shape)))) def avg_pool_nd(dims, *args, **kwargs): + """ + Create a 1D, 2D, or 3D average pooling module. + """ if dims == 1: return nn.AvgPool1d(*args, **kwargs) elif dims == 2: @@ -262,4 +301,4 @@ def noise_like(shape, device, repeat=False): repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1))) noise = lambda: torch.randn(shape, device=device) - return repeat_noise() if repeat else noise()+ return repeat_noise() if repeat else noise()
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_config from ldm_patched.ldm.modules.ema import LitEma import ldm_patched.modules.ops class DiagonalGaussianRegularizer(torch.nn.Module): def __init__(self, sample: bool = True): super().__init__() self.sample = sample def get_trainable_parameters(self) -> Any: yield from () def forward(self, z: torch.Tensor) -> Tuple[torch.Tensor, dict]: log = dict() posterior = DiagonalGaussianDistribution(z) if self.sample: z = posterior.sample() else: z = posterior.mode() kl_loss = posterior.kl() kl_loss = torch.sum(kl_loss) / kl_loss.shape[0] log["kl_loss"] = kl_loss return z, log class AbstractAutoencoder(torch.nn.Module): def __init__( self, ema_decay: Union[None, float] = None, monitor: Union[None, str] = None, input_key: str = "jpg", **kwargs, ): super().__init__() self.input_key = input_key self.use_ema = ema_decay is not None if monitor is not None: self.monitor = monitor if self.use_ema: self.model_ema = LitEma(self, decay=ema_decay) logpy.info(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") def get_input(self, batch) -> Any: raise NotImplementedError() def on_train_batch_end(self, *args, **kwargs): # for EMA computation if self.use_ema: self.model_ema(self) @contextmanager def ema_scope(self, context=None): if self.use_ema: self.model_ema.store(self.parameters()) self.model_ema.copy_to(self) if context is not None: logpy.info(f"{context}: Switched to EMA weights") try: yield None finally: if self.use_ema: self.model_ema.restore(self.parameters()) if context is not None: logpy.info(f"{context}: Restored training weights") def encode(self, *args, **kwargs) -> torch.Tensor: raise NotImplementedError("encode()-method of abstract base class called") def decode(self, *args, **kwargs) -> torch.Tensor: raise NotImplementedError("decode()-method of abstract base class called") def instantiate_optimizer_from_config(self, params, lr, cfg): logpy.info(f"loading >>> {cfg['target']} <<< optimizer from config") return get_obj_from_str(cfg["target"])( params, lr=lr, **cfg.get("params", dict()) ) def configure_optimizers(self) -> Any: raise NotImplementedError() class AutoencodingEngine(AbstractAutoencoder): def __init__( self, *args, encoder_config: Dict, decoder_config: Dict, regularizer_config: Dict, **kwargs, ): super().__init__(*args, **kwargs) self.encoder: torch.nn.Module = instantiate_from_config(encoder_config) self.decoder: torch.nn.Module = instantiate_from_config(decoder_config) self.regularization: AbstractRegularizer = instantiate_from_config( regularizer_config ) def get_last_layer(self): return self.decoder.get_last_layer() def encode( self, x: torch.Tensor, return_reg_log: bool = False, unregularized: bool = False, ) -> Union[torch.Tensor, Tuple[torch.Tensor, dict]]: z = self.encoder(x) if unregularized: return z, dict() z, reg_log = self.regularization(z) if return_reg_log: return z, reg_log return z def decode(self, z: torch.Tensor, **kwargs) -> torch.Tensor: x = self.decoder(z, **kwargs) return x def forward( self, x: torch.Tensor, **additional_decode_kwargs ) -> Tuple[torch.Tensor, torch.Tensor, dict]: z, reg_log = self.encode(x, return_reg_log=True) dec = self.decode(z, **additional_decode_kwargs) return z, dec, reg_log class AutoencodingEngineLegacy(AutoencodingEngine): def __init__(self, embed_dim: int, **kwargs): self.max_batch_size = kwargs.pop("max_batch_size", None) ddconfig = kwargs.pop("ddconfig") super().__init__( encoder_config={ "target": "ldm_patched.ldm.modules.diffusionmodules.model.Encoder", "params": ddconfig, }, decoder_config={ "target": "ldm_patched.ldm.modules.diffusionmodules.model.Decoder", "params": ddconfig, }, **kwargs, ) self.quant_conv = ldm_patched.modules.ops.disable_weight_init.Conv2d( (1 + ddconfig["double_z"]) * ddconfig["z_channels"], (1 + ddconfig["double_z"]) * embed_dim, 1, ) self.post_quant_conv = ldm_patched.modules.ops.disable_weight_init.Conv2d(embed_dim, ddconfig["z_channels"], 1) self.embed_dim = embed_dim def get_autoencoder_params(self) -> list: params = super().get_autoencoder_params() return params def encode( self, x: torch.Tensor, return_reg_log: bool = False ) -> Union[torch.Tensor, Tuple[torch.Tensor, dict]]: if self.max_batch_size is None: z = self.encoder(x) z = self.quant_conv(z) else: N = x.shape[0] bs = self.max_batch_size n_batches = int(math.ceil(N / bs)) z = list() for i_batch in range(n_batches): z_batch = self.encoder(x[i_batch * bs : (i_batch + 1) * bs]) z_batch = self.quant_conv(z_batch) z.append(z_batch) z = torch.cat(z, 0) z, reg_log = self.regularization(z) if return_reg_log: return z, reg_log return z def decode(self, z: torch.Tensor, **decoder_kwargs) -> torch.Tensor: if self.max_batch_size is None: dec = self.post_quant_conv(z) dec = self.decoder(dec, **decoder_kwargs) else: N = z.shape[0] bs = self.max_batch_size n_batches = int(math.ceil(N / bs)) dec = list() for i_batch in range(n_batches): dec_batch = self.post_quant_conv(z[i_batch * bs : (i_batch + 1) * bs]) dec_batch = self.decoder(dec_batch, **decoder_kwargs) dec.append(dec_batch) dec = torch.cat(dec, 0) return dec class AutoencoderKL(AutoencodingEngineLegacy): def __init__(self, **kwargs): if "lossconfig" in kwargs: kwargs["loss_config"] = kwargs.pop("lossconfig") super().__init__( regularizer_config={ "target": ( "ldm_patched.ldm.models.autoencoder.DiagonalGaussianRegularizer" ) }, **kwargs, )
--- +++ @@ -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, encoding, decoding) must be implemented in subclasses. + """ def __init__( self, @@ -91,6 +96,11 @@ class AutoencodingEngine(AbstractAutoencoder): + """ + Base class for all image autoencoders that we train, like VQGAN or AutoencoderKL + (we also restore them explicitly as special cases for legacy reasons). + Regularizations such as KL or VQ are moved to the regularizer class. + """ def __init__( self, @@ -215,4 +225,4 @@ ) }, **kwargs, - )+ )
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 import ACT2FN from transformers.file_utils import ( ModelOutput, ) from transformers.modeling_outputs import ( BaseModelOutputWithPastAndCrossAttentions, BaseModelOutputWithPoolingAndCrossAttentions, CausalLMOutputWithCrossAttentions, MaskedLMOutput, MultipleChoiceModelOutput, NextSentencePredictorOutput, QuestionAnsweringModelOutput, SequenceClassifierOutput, TokenClassifierOutput, ) from transformers.modeling_utils import ( PreTrainedModel, apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer, ) from transformers.utils import logging from transformers.models.bert.configuration_bert import BertConfig logger = logging.get_logger(__name__) class BertEmbeddings(nn.Module): def __init__(self, config): super().__init__() self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size) # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load # any TensorFlow checkpoint file self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) # position_ids (1, len position emb) is contiguous in memory and exported when serialized self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))) self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") self.config = config def forward( self, input_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0 ): if input_ids is not None: input_shape = input_ids.size() else: input_shape = inputs_embeds.size()[:-1] seq_length = input_shape[1] if position_ids is None: position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length] if inputs_embeds is None: inputs_embeds = self.word_embeddings(input_ids) embeddings = inputs_embeds if self.position_embedding_type == "absolute": position_embeddings = self.position_embeddings(position_ids) embeddings += position_embeddings embeddings = self.LayerNorm(embeddings) embeddings = self.dropout(embeddings) return embeddings class BertSelfAttention(nn.Module): def __init__(self, config, is_cross_attention): super().__init__() self.config = config if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( "The hidden size (%d) is not a multiple of the number of attention " "heads (%d)" % (config.hidden_size, config.num_attention_heads) ) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query = nn.Linear(config.hidden_size, self.all_head_size) if is_cross_attention: self.key = nn.Linear(config.encoder_width, self.all_head_size) self.value = nn.Linear(config.encoder_width, self.all_head_size) else: self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": self.max_position_embeddings = config.max_position_embeddings self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size) self.save_attention = False def save_attn_gradients(self, attn_gradients): self.attn_gradients = attn_gradients def get_attn_gradients(self): return self.attn_gradients def save_attention_map(self, attention_map): self.attention_map = attention_map def get_attention_map(self): return self.attention_map def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_value=None, output_attentions=False, ): mixed_query_layer = self.query(hidden_states) # If this is instantiated as a cross-attention module, the keys # and values come from an encoder; the attention mask needs to be # such that the encoder's padding tokens are not attended to. is_cross_attention = encoder_hidden_states is not None if is_cross_attention: key_layer = self.transpose_for_scores(self.key(encoder_hidden_states)) value_layer = self.transpose_for_scores(self.value(encoder_hidden_states)) attention_mask = encoder_attention_mask elif past_key_value is not None: key_layer = self.transpose_for_scores(self.key(hidden_states)) value_layer = self.transpose_for_scores(self.value(hidden_states)) key_layer = torch.cat([past_key_value[0], key_layer], dim=2) value_layer = torch.cat([past_key_value[1], value_layer], dim=2) else: key_layer = self.transpose_for_scores(self.key(hidden_states)) value_layer = self.transpose_for_scores(self.value(hidden_states)) query_layer = self.transpose_for_scores(mixed_query_layer) past_key_value = (key_layer, value_layer) # Take the dot product between "query" and "key" to get the raw attention scores. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": seq_length = hidden_states.size()[1] position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1) position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1) distance = position_ids_l - position_ids_r positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1) positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility if self.position_embedding_type == "relative_key": relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) attention_scores = attention_scores + relative_position_scores elif self.position_embedding_type == "relative_key_query": relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding) attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key attention_scores = attention_scores / math.sqrt(self.attention_head_size) if attention_mask is not None: # Apply the attention mask is (precomputed for all layers in BertModel forward() function) attention_scores = attention_scores + attention_mask # Normalize the attention scores to probabilities. attention_probs = nn.Softmax(dim=-1)(attention_scores) if is_cross_attention and self.save_attention: self.save_attention_map(attention_probs) attention_probs.register_hook(self.save_attn_gradients) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs_dropped = self.dropout(attention_probs) # Mask heads if we want to if head_mask is not None: attention_probs_dropped = attention_probs_dropped * head_mask context_layer = torch.matmul(attention_probs_dropped, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) context_layer = context_layer.view(*new_context_layer_shape) outputs = (context_layer, attention_probs) if output_attentions else (context_layer,) outputs = outputs + (past_key_value,) return outputs class BertSelfOutput(nn.Module): def __init__(self, config, twin=False, merge=False): super().__init__() self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) if twin: self.dense0 = nn.Linear(config.hidden_size, config.hidden_size) self.dense1 = nn.Linear(config.hidden_size, config.hidden_size) else: self.dense = nn.Linear(config.hidden_size, config.hidden_size) if merge: self.act = ACT2FN[config.hidden_act] self.merge_layer = nn.Linear(config.hidden_size * 2, config.hidden_size) self.merge = True else: self.merge = False def forward(self, hidden_states, input_tensor): if type(hidden_states) == list: hidden_states0 = self.dense0(hidden_states[0]) hidden_states1 = self.dense1(hidden_states[1]) if self.merge: #hidden_states = self.merge_layer(self.act(torch.cat([hidden_states0,hidden_states1],dim=-1))) hidden_states = self.merge_layer(torch.cat([hidden_states0,hidden_states1],dim=-1)) else: hidden_states = (hidden_states0+hidden_states1)/2 else: hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states class BertAttention(nn.Module): def __init__(self, config, is_cross_attention=False, layer_num=-1): super().__init__() if is_cross_attention: self.self0 = BertSelfAttention(config, is_cross_attention) self.self1 = BertSelfAttention(config, is_cross_attention) else: self.self = BertSelfAttention(config, is_cross_attention) self.output = BertSelfOutput(config, twin=is_cross_attention, merge=(is_cross_attention and layer_num>=6)) self.pruned_heads = set() def prune_heads(self, heads): if len(heads) == 0: return heads, index = find_pruneable_heads_and_indices( heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads ) # Prune linear layers self.self.query = prune_linear_layer(self.self.query, index) self.self.key = prune_linear_layer(self.self.key, index) self.self.value = prune_linear_layer(self.self.value, index) self.output.dense = prune_linear_layer(self.output.dense, index, dim=1) # Update hyper params and store pruned heads self.self.num_attention_heads = self.self.num_attention_heads - len(heads) self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads self.pruned_heads = self.pruned_heads.union(heads) def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_value=None, output_attentions=False, ): if type(encoder_hidden_states)==list: self_outputs0 = self.self0( hidden_states, attention_mask, head_mask, encoder_hidden_states[0], encoder_attention_mask[0], past_key_value, output_attentions, ) self_outputs1 = self.self1( hidden_states, attention_mask, head_mask, encoder_hidden_states[1], encoder_attention_mask[1], past_key_value, output_attentions, ) attention_output = self.output([self_outputs0[0],self_outputs1[0]], hidden_states) outputs = (attention_output,) + self_outputs0[1:] # add attentions if we output them else: self_outputs = self.self( hidden_states, attention_mask, head_mask, encoder_hidden_states, encoder_attention_mask, past_key_value, output_attentions, ) attention_output = self.output(self_outputs[0], hidden_states) outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them return outputs class BertIntermediate(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.intermediate_act_fn = config.hidden_act def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.intermediate_act_fn(hidden_states) return hidden_states class BertOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states class BertLayer(nn.Module): def __init__(self, config, layer_num): super().__init__() self.config = config self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = BertAttention(config) self.layer_num = layer_num if self.config.add_cross_attention: self.crossattention = BertAttention(config, is_cross_attention=self.config.add_cross_attention, layer_num=layer_num) self.intermediate = BertIntermediate(config) self.output = BertOutput(config) def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_value=None, output_attentions=False, mode=None, ): # decoder uni-directional self-attention cached key/values tuple is at positions 1,2 self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None self_attention_outputs = self.attention( hidden_states, attention_mask, head_mask, output_attentions=output_attentions, past_key_value=self_attn_past_key_value, ) attention_output = self_attention_outputs[0] outputs = self_attention_outputs[1:-1] present_key_value = self_attention_outputs[-1] if mode=='multimodal': assert encoder_hidden_states is not None, "encoder_hidden_states must be given for cross-attention layers" cross_attention_outputs = self.crossattention( attention_output, attention_mask, head_mask, encoder_hidden_states, encoder_attention_mask, output_attentions=output_attentions, ) attention_output = cross_attention_outputs[0] outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights layer_output = apply_chunking_to_forward( self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output ) outputs = (layer_output,) + outputs outputs = outputs + (present_key_value,) return outputs def feed_forward_chunk(self, attention_output): intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output) return layer_output class BertEncoder(nn.Module): def __init__(self, config): super().__init__() self.config = config self.layer = nn.ModuleList([BertLayer(config,i) for i in range(config.num_hidden_layers)]) self.gradient_checkpointing = False def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, use_cache=None, output_attentions=False, output_hidden_states=False, return_dict=True, mode='multimodal', ): all_hidden_states = () if output_hidden_states else None all_self_attentions = () if output_attentions else None all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None next_decoder_cache = () if use_cache else None for i in range(self.config.num_hidden_layers): layer_module = self.layer[i] if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) layer_head_mask = head_mask[i] if head_mask is not None else None past_key_value = past_key_values[i] if past_key_values is not None else None if self.gradient_checkpointing and self.training: if use_cache: logger.warn( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." ) use_cache = False def create_custom_forward(module): def custom_forward(*inputs): return module(*inputs, past_key_value, output_attentions) return custom_forward layer_outputs = torch.utils.checkpoint.checkpoint( create_custom_forward(layer_module), hidden_states, attention_mask, layer_head_mask, encoder_hidden_states, encoder_attention_mask, mode=mode, ) else: layer_outputs = layer_module( hidden_states, attention_mask, layer_head_mask, encoder_hidden_states, encoder_attention_mask, past_key_value, output_attentions, mode=mode, ) hidden_states = layer_outputs[0] if use_cache: next_decoder_cache += (layer_outputs[-1],) if output_attentions: all_self_attentions = all_self_attentions + (layer_outputs[1],) if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if not return_dict: return tuple( v for v in [ hidden_states, next_decoder_cache, all_hidden_states, all_self_attentions, all_cross_attentions, ] if v is not None ) return BaseModelOutputWithPastAndCrossAttentions( last_hidden_state=hidden_states, past_key_values=next_decoder_cache, hidden_states=all_hidden_states, attentions=all_self_attentions, cross_attentions=all_cross_attentions, ) class BertPooler(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.activation = nn.Tanh() def forward(self, hidden_states): # We "pool" the model by simply taking the hidden state corresponding # to the first token. first_token_tensor = hidden_states[:, 0] pooled_output = self.dense(first_token_tensor) pooled_output = self.activation(pooled_output) return pooled_output class BertPredictionHeadTransform(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) if isinstance(config.hidden_act, str): self.transform_act_fn = ACT2FN[config.hidden_act] else: self.transform_act_fn = config.hidden_act self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.transform_act_fn(hidden_states) hidden_states = self.LayerNorm(hidden_states) return hidden_states class BertLMPredictionHead(nn.Module): def __init__(self, config): super().__init__() self.transform = BertPredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = self.decoder(hidden_states) return hidden_states class BertOnlyMLMHead(nn.Module): def __init__(self, config): super().__init__() self.predictions = BertLMPredictionHead(config) def forward(self, sequence_output): prediction_scores = self.predictions(sequence_output) return prediction_scores class BertPreTrainedModel(PreTrainedModel): config_class = BertConfig base_model_prefix = "bert" _keys_to_ignore_on_load_missing = [r"position_ids"] def _init_weights(self, module): if isinstance(module, (nn.Linear, nn.Embedding)): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) elif isinstance(module, nn.LayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) if isinstance(module, nn.Linear) and module.bias is not None: module.bias.data.zero_() class BertModel(BertPreTrainedModel): def __init__(self, config, add_pooling_layer=True): super().__init__(config) self.config = config self.embeddings = BertEmbeddings(config) self.encoder = BertEncoder(config) self.pooler = BertPooler(config) if add_pooling_layer else None self.init_weights() def get_input_embeddings(self): return self.embeddings.word_embeddings def set_input_embeddings(self, value): self.embeddings.word_embeddings = value def _prune_heads(self, heads_to_prune): for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(heads) def get_extended_attention_mask(self, attention_mask: Tensor, input_shape: Tuple[int], device: device, is_decoder: bool) -> Tensor: # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. if attention_mask.dim() == 3: extended_attention_mask = attention_mask[:, None, :, :] elif attention_mask.dim() == 2: # Provided a padding mask of dimensions [batch_size, seq_length] # - if the model is a decoder, apply a causal mask in addition to the padding mask # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length] if is_decoder: batch_size, seq_length = input_shape seq_ids = torch.arange(seq_length, device=device) causal_mask = seq_ids[None, None, :].repeat(batch_size, seq_length, 1) <= seq_ids[None, :, None] # in case past_key_values are used we need to add a prefix ones mask to the causal mask # causal and attention masks must have same type with pytorch version < 1.3 causal_mask = causal_mask.to(attention_mask.dtype) if causal_mask.shape[1] < attention_mask.shape[1]: prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1] causal_mask = torch.cat( [ torch.ones((batch_size, seq_length, prefix_seq_len), device=device, dtype=causal_mask.dtype), causal_mask, ], axis=-1, ) extended_attention_mask = causal_mask[:, None, :, :] * attention_mask[:, None, None, :] else: extended_attention_mask = attention_mask[:, None, None, :] else: raise ValueError( "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format( input_shape, attention_mask.shape ) ) # Since attention_mask is 1.0 for positions we want to attend and 0.0 for # masked positions, this operation will create a tensor which is 0.0 for # positions we want to attend and -10000.0 for masked positions. # Since we are adding it to the raw scores before the softmax, this is # effectively the same as removing these entirely. extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0 return extended_attention_mask def forward( self, input_ids=None, attention_mask=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None, is_decoder=False, mode='multimodal', ): output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict if is_decoder: use_cache = use_cache if use_cache is not None else self.config.use_cache else: use_cache = False if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_shape = input_ids.size() batch_size, seq_length = input_shape device = input_ids.device elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] batch_size, seq_length = input_shape device = inputs_embeds.device elif encoder_embeds is not None: input_shape = encoder_embeds.size()[:-1] batch_size, seq_length = input_shape device = encoder_embeds.device else: raise ValueError("You have to specify either input_ids or inputs_embeds or encoder_embeds") # past_key_values_length past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0 if attention_mask is None: attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape, device, is_decoder) # If a 2D or 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_hidden_states is not None: if type(encoder_hidden_states) == list: encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[0].size() else: encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size() encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) if type(encoder_attention_mask) == list: encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask] elif encoder_attention_mask is None: encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) else: encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) else: encoder_extended_attention_mask = None # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) if encoder_embeds is None: embedding_output = self.embeddings( input_ids=input_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, past_key_values_length=past_key_values_length, ) else: embedding_output = encoder_embeds encoder_outputs = self.encoder( embedding_output, attention_mask=extended_attention_mask, head_mask=head_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_extended_attention_mask, past_key_values=past_key_values, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, mode=mode, ) sequence_output = encoder_outputs[0] pooled_output = self.pooler(sequence_output) if self.pooler is not None else None if not return_dict: return (sequence_output, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndCrossAttentions( last_hidden_state=sequence_output, pooler_output=pooled_output, past_key_values=encoder_outputs.past_key_values, hidden_states=encoder_outputs.hidden_states, attentions=encoder_outputs.attentions, cross_attentions=encoder_outputs.cross_attentions, )
--- +++ @@ -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 initialization and a simple interface for downloading and loading pretrained + models. + """ config_class = BertConfig base_model_prefix = "bert" _keys_to_ignore_on_load_missing = [r"position_ids"] def _init_weights(self, module): + """ Initialize the weights """ if isinstance(module, (nn.Linear, nn.Embedding)): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 @@ -598,6 +604,14 @@ class BertModel(BertPreTrainedModel): + """ + The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of + cross-attention is added between the self-attention layers, following the architecture described in `Attention is + all you need <https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, + Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. + argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an + input to the forward pass. + """ def __init__(self, config, add_pooling_layer=True): super().__init__(config) @@ -619,11 +633,29 @@ self.embeddings.word_embeddings = value def _prune_heads(self, heads_to_prune): + """ + Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base + class PreTrainedModel + """ for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(heads) def get_extended_attention_mask(self, attention_mask: Tensor, input_shape: Tuple[int], device: device, is_decoder: bool) -> Tensor: + """ + Makes broadcastable attention and causal masks so that future and masked tokens are ignored. + + Arguments: + attention_mask (:obj:`torch.Tensor`): + Mask with ones indicating tokens to attend to, zeros for tokens to ignore. + input_shape (:obj:`Tuple[int]`): + The shape of the input to the model. + device: (:obj:`torch.device`): + The device of the input to the model. + + Returns: + :obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`. + """ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. if attention_mask.dim() == 3: @@ -688,6 +720,24 @@ is_decoder=False, mode='multimodal', ): + r""" + encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): + Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if + the model is configured as a decoder. + encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): + Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in + the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``: + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): + Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. + If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` + (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` + instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`. + use_cache (:obj:`bool`, `optional`): + If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up + decoding (see :obj:`past_key_values`). + """ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states @@ -790,3 +840,4 @@ attentions=encoder_outputs.attentions, cross_attentions=encoder_outputs.cross_attentions, ) +
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}), }} RETURN_TYPES = ("LATENT",) INPUT_IS_LIST = True OUTPUT_IS_LIST = (True, ) FUNCTION = "rebatch" CATEGORY = "latent/batch" @staticmethod def get_batch(latents, list_ind, offset): samples = latents[list_ind]['samples'] shape = samples.shape mask = latents[list_ind]['noise_mask'] if 'noise_mask' in latents[list_ind] else torch.ones((shape[0], 1, shape[2]*8, shape[3]*8), device='cpu') if mask.shape[-1] != shape[-1] * 8 or mask.shape[-2] != shape[-2]: torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(shape[-2]*8, shape[-1]*8), mode="bilinear") if mask.shape[0] < samples.shape[0]: mask = mask.repeat((shape[0] - 1) // mask.shape[0] + 1, 1, 1, 1)[:shape[0]] if 'batch_index' in latents[list_ind]: batch_inds = latents[list_ind]['batch_index'] else: batch_inds = [x+offset for x in range(shape[0])] return samples, mask, batch_inds @staticmethod def get_slices(indexable, num, batch_size): slices = [] for i in range(num): slices.append(indexable[i*batch_size:(i+1)*batch_size]) if num * batch_size < len(indexable): return slices, indexable[num * batch_size:] else: return slices, None @staticmethod def slice_batch(batch, num, batch_size): result = [LatentRebatch.get_slices(x, num, batch_size) for x in batch] return list(zip(*result)) @staticmethod def cat_batch(batch1, batch2): if batch1[0] is None: return batch2 result = [torch.cat((b1, b2)) if torch.is_tensor(b1) else b1 + b2 for b1, b2 in zip(batch1, batch2)] return result def rebatch(self, latents, batch_size): batch_size = batch_size[0] output_list = [] current_batch = (None, None, None) processed = 0 for i in range(len(latents)): # fetch new entry of list #samples, masks, indices = self.get_batch(latents, i) next_batch = self.get_batch(latents, i, processed) processed += len(next_batch[2]) # set to current if current is None if current_batch[0] is None: current_batch = next_batch # add previous to list if dimensions do not match elif next_batch[0].shape[-1] != current_batch[0].shape[-1] or next_batch[0].shape[-2] != current_batch[0].shape[-2]: sliced, _ = self.slice_batch(current_batch, 1, batch_size) output_list.append({'samples': sliced[0][0], 'noise_mask': sliced[1][0], 'batch_index': sliced[2][0]}) current_batch = next_batch # cat if everything checks out else: current_batch = self.cat_batch(current_batch, next_batch) # add to list if dimensions gone above target batch size if current_batch[0].shape[0] > batch_size: num = current_batch[0].shape[0] // batch_size sliced, remainder = self.slice_batch(current_batch, num, batch_size) for i in range(num): output_list.append({'samples': sliced[0][i], 'noise_mask': sliced[1][i], 'batch_index': sliced[2][i]}) current_batch = remainder #add remainder if current_batch[0] is not None: sliced, _ = self.slice_batch(current_batch, 1, batch_size) output_list.append({'samples': sliced[0][0], 'noise_mask': sliced[1][0], 'batch_index': sliced[2][0]}) #get rid of empty masks for s in output_list: if s['noise_mask'].mean() == 1.0: del s['noise_mask'] return (output_list,) class ImageRebatch: @classmethod def INPUT_TYPES(s): return {"required": { "images": ("IMAGE",), "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}), }} RETURN_TYPES = ("IMAGE",) INPUT_IS_LIST = True OUTPUT_IS_LIST = (True, ) FUNCTION = "rebatch" CATEGORY = "image/batch" def rebatch(self, images, batch_size): batch_size = batch_size[0] output_list = [] all_images = [] for img in images: for i in range(img.shape[0]): all_images.append(img[i:i+1]) for i in range(0, len(all_images), batch_size): output_list.append(torch.cat(all_images[i:i+batch_size], dim=0)) return (output_list,) NODE_CLASS_MAPPINGS = { "RebatchLatents": LatentRebatch, "RebatchImages": ImageRebatch, } NODE_DISPLAY_NAME_MAPPINGS = { "RebatchLatents": "Rebatch Latents", "RebatchImages": "Rebatch Images", }
--- +++ @@ -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 torch.ones((shape[0], 1, shape[2]*8, shape[3]*8), device='cpu') @@ -33,6 +34,7 @@ @staticmethod def get_slices(indexable, num, batch_size): + '''divides an indexable object into num slices of length batch_size, and a remainder''' slices = [] for i in range(num): slices.append(indexable[i*batch_size:(i+1)*batch_size]) @@ -135,4 +137,4 @@ NODE_DISPLAY_NAME_MAPPINGS = { "RebatchLatents": "Rebatch Latents", "RebatchImages": "Rebatch Images", -}+}
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 = [transform(image.convert(mode)) for image in examples[image_key]] return {image_key: images} def append_dims(x, target_dims): dims_to_append = target_dims - x.ndim if dims_to_append < 0: raise ValueError(f'input has {x.ndim} dims but target_dims is {target_dims}, which is less') expanded = x[(...,) + (None,) * dims_to_append] # MPS will get inf values if it tries to index into the new axes, but detaching fixes this. # https://github.com/pytorch/pytorch/issues/84364 return expanded.detach().clone() if expanded.device.type == 'mps' else expanded def n_params(module): return sum(p.numel() for p in module.parameters()) def download_file(path, url, digest=None): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) if not path.exists(): with urllib.request.urlopen(url) as response, open(path, 'wb') as f: shutil.copyfileobj(response, f) if digest is not None: file_digest = hashlib.sha256(open(path, 'rb').read()).hexdigest() if digest != file_digest: raise OSError(f'hash of {path} (url: {url}) failed to validate') return path @contextmanager def train_mode(model, mode=True): modes = [module.training for module in model.modules()] try: yield model.train(mode) finally: for i, module in enumerate(model.modules()): module.training = modes[i] def eval_mode(model): return train_mode(model, False) @torch.no_grad() def ema_update(model, averaged_model, decay): model_params = dict(model.named_parameters()) averaged_params = dict(averaged_model.named_parameters()) assert model_params.keys() == averaged_params.keys() for name, param in model_params.items(): averaged_params[name].mul_(decay).add_(param, alpha=1 - decay) model_buffers = dict(model.named_buffers()) averaged_buffers = dict(averaged_model.named_buffers()) assert model_buffers.keys() == averaged_buffers.keys() for name, buf in model_buffers.items(): averaged_buffers[name].copy_(buf) class EMAWarmup: def __init__(self, inv_gamma=1., power=1., min_value=0., max_value=1., start_at=0, last_epoch=0): self.inv_gamma = inv_gamma self.power = power self.min_value = min_value self.max_value = max_value self.start_at = start_at self.last_epoch = last_epoch def state_dict(self): return dict(self.__dict__.items()) def load_state_dict(self, state_dict): self.__dict__.update(state_dict) def get_value(self): epoch = max(0, self.last_epoch - self.start_at) value = 1 - (1 + epoch / self.inv_gamma) ** -self.power return 0. if epoch < 0 else min(self.max_value, max(self.min_value, value)) def step(self): self.last_epoch += 1 class InverseLR(optim.lr_scheduler._LRScheduler): def __init__(self, optimizer, inv_gamma=1., power=1., warmup=0., min_lr=0., last_epoch=-1, verbose=False): self.inv_gamma = inv_gamma self.power = power if not 0. <= warmup < 1: raise ValueError('Invalid value for warmup') self.warmup = warmup self.min_lr = min_lr super().__init__(optimizer, last_epoch, verbose) def get_lr(self): if not self._get_lr_called_within_step: warnings.warn("To get the last learning rate computed by the scheduler, " "please use `get_last_lr()`.") return self._get_closed_form_lr() def _get_closed_form_lr(self): warmup = 1 - self.warmup ** (self.last_epoch + 1) lr_mult = (1 + self.last_epoch / self.inv_gamma) ** -self.power return [warmup * max(self.min_lr, base_lr * lr_mult) for base_lr in self.base_lrs] class ExponentialLR(optim.lr_scheduler._LRScheduler): def __init__(self, optimizer, num_steps, decay=0.5, warmup=0., min_lr=0., last_epoch=-1, verbose=False): self.num_steps = num_steps self.decay = decay if not 0. <= warmup < 1: raise ValueError('Invalid value for warmup') self.warmup = warmup self.min_lr = min_lr super().__init__(optimizer, last_epoch, verbose) def get_lr(self): if not self._get_lr_called_within_step: warnings.warn("To get the last learning rate computed by the scheduler, " "please use `get_last_lr()`.") return self._get_closed_form_lr() def _get_closed_form_lr(self): warmup = 1 - self.warmup ** (self.last_epoch + 1) lr_mult = (self.decay ** (1 / self.num_steps)) ** self.last_epoch return [warmup * max(self.min_lr, base_lr * lr_mult) for base_lr in self.base_lrs] def rand_log_normal(shape, loc=0., scale=1., device='cpu', dtype=torch.float32): return (torch.randn(shape, device=device, dtype=dtype) * scale + loc).exp() def rand_log_logistic(shape, loc=0., scale=1., min_value=0., max_value=float('inf'), device='cpu', dtype=torch.float32): min_value = torch.as_tensor(min_value, device=device, dtype=torch.float64) max_value = torch.as_tensor(max_value, device=device, dtype=torch.float64) min_cdf = min_value.log().sub(loc).div(scale).sigmoid() max_cdf = max_value.log().sub(loc).div(scale).sigmoid() u = torch.rand(shape, device=device, dtype=torch.float64) * (max_cdf - min_cdf) + min_cdf return u.logit().mul(scale).add(loc).exp().to(dtype) def rand_log_uniform(shape, min_value, max_value, device='cpu', dtype=torch.float32): min_value = math.log(min_value) max_value = math.log(max_value) return (torch.rand(shape, device=device, dtype=dtype) * (max_value - min_value) + min_value).exp() def rand_v_diffusion(shape, sigma_data=1., min_value=0., max_value=float('inf'), device='cpu', dtype=torch.float32): min_cdf = math.atan(min_value / sigma_data) * 2 / math.pi max_cdf = math.atan(max_value / sigma_data) * 2 / math.pi u = torch.rand(shape, device=device, dtype=dtype) * (max_cdf - min_cdf) + min_cdf return torch.tan(u * math.pi / 2) * sigma_data def rand_split_log_normal(shape, loc, scale_1, scale_2, device='cpu', dtype=torch.float32): n = torch.randn(shape, device=device, dtype=dtype).abs() u = torch.rand(shape, device=device, dtype=dtype) n_left = n * -scale_1 + loc n_right = n * scale_2 + loc ratio = scale_1 / (scale_1 + scale_2) return torch.where(u < ratio, n_left, n_right).exp() class FolderOfImages(data.Dataset): IMG_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp'} def __init__(self, root, transform=None): super().__init__() self.root = Path(root) self.transform = nn.Identity() if transform is None else transform self.paths = sorted(path for path in self.root.rglob('*') if path.suffix.lower() in self.IMG_EXTENSIONS) def __repr__(self): return f'FolderOfImages(root="{self.root}", len: {len(self)})' def __len__(self): return len(self.paths) def __getitem__(self, key): path = self.paths[key] with open(path, 'rb') as f: image = Image.open(f).convert('RGB') image = self.transform(image) return image, class CSVLogger: def __init__(self, filename, columns): self.filename = Path(filename) self.columns = columns if self.filename.exists(): self.file = open(self.filename, 'a') else: self.file = open(self.filename, 'w') self.write(*self.columns) def write(self, *args): print(*args, sep=',', file=self.file, flush=True) @contextmanager def tf32_mode(cudnn=None, matmul=None): cudnn_old = torch.backends.cudnn.allow_tf32 matmul_old = torch.backends.cuda.matmul.allow_tf32 try: if cudnn is not None: torch.backends.cudnn.allow_tf32 = cudnn if matmul is not None: torch.backends.cuda.matmul.allow_tf32 = matmul yield finally: if cudnn is not None: torch.backends.cudnn.allow_tf32 = cudnn_old if matmul is not None: torch.backends.cuda.matmul.allow_tf32 = matmul_old
--- +++ @@ -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): + """Appends dimensions to the end of a tensor until it has target_dims dimensions.""" dims_to_append = target_dims - x.ndim if dims_to_append < 0: raise ValueError(f'input has {x.ndim} dims but target_dims is {target_dims}, which is less') @@ -28,10 +30,12 @@ def n_params(module): + """Returns the number of trainable parameters in a module.""" return sum(p.numel() for p in module.parameters()) def download_file(path, url, digest=None): + """Downloads a file if it does not exist, optionally checking its SHA-256 hash.""" path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) if not path.exists(): @@ -46,6 +50,8 @@ @contextmanager def train_mode(model, mode=True): + """A context manager that places a model into training mode and restores + the previous mode on exit.""" modes = [module.training for module in model.modules()] try: yield model.train(mode) @@ -55,11 +61,15 @@ def eval_mode(model): + """A context manager that places a model into evaluation mode and restores + the previous mode on exit.""" return train_mode(model, False) @torch.no_grad() def ema_update(model, averaged_model, decay): + """Incorporates updated model parameters into an exponential moving averaged + version of a model. It should be called after each optimizer step.""" model_params = dict(model.named_parameters()) averaged_params = dict(averaged_model.named_parameters()) assert model_params.keys() == averaged_params.keys() @@ -76,6 +86,20 @@ class EMAWarmup: + """Implements an EMA warmup using an inverse decay schedule. + If inv_gamma=1 and power=1, implements a simple average. inv_gamma=1, power=2/3 are + good values for models you plan to train for a million or more steps (reaches decay + factor 0.999 at 31.6K steps, 0.9999 at 1M steps), inv_gamma=1, power=3/4 for models + you plan to train for less (reaches decay factor 0.999 at 10K steps, 0.9999 at + 215.4k steps). + Args: + inv_gamma (float): Inverse multiplicative factor of EMA warmup. Default: 1. + power (float): Exponential factor of EMA warmup. Default: 1. + min_value (float): The minimum EMA decay rate. Default: 0. + max_value (float): The maximum EMA decay rate. Default: 1. + start_at (int): The epoch to start averaging at. Default: 0. + last_epoch (int): The index of last epoch. Default: 0. + """ def __init__(self, inv_gamma=1., power=1., min_value=0., max_value=1., start_at=0, last_epoch=0): @@ -87,21 +111,44 @@ self.last_epoch = last_epoch def state_dict(self): + """Returns the state of the class as a :class:`dict`.""" return dict(self.__dict__.items()) def load_state_dict(self, state_dict): + """Loads the class's state. + Args: + state_dict (dict): scaler state. Should be an object returned + from a call to :meth:`state_dict`. + """ self.__dict__.update(state_dict) def get_value(self): + """Gets the current EMA decay rate.""" epoch = max(0, self.last_epoch - self.start_at) value = 1 - (1 + epoch / self.inv_gamma) ** -self.power return 0. if epoch < 0 else min(self.max_value, max(self.min_value, value)) def step(self): + """Updates the step count.""" self.last_epoch += 1 class InverseLR(optim.lr_scheduler._LRScheduler): + """Implements an inverse decay learning rate schedule with an optional exponential + warmup. When last_epoch=-1, sets initial lr as lr. + inv_gamma is the number of steps/epochs required for the learning rate to decay to + (1 / 2)**power of its original value. + Args: + optimizer (Optimizer): Wrapped optimizer. + inv_gamma (float): Inverse multiplicative factor of learning rate decay. Default: 1. + power (float): Exponential factor of learning rate decay. Default: 1. + warmup (float): Exponential warmup factor (0 <= warmup < 1, 0 to disable) + Default: 0. + min_lr (float): The minimum learning rate. Default: 0. + last_epoch (int): The index of last epoch. Default: -1. + verbose (bool): If ``True``, prints a message to stdout for + each update. Default: ``False``. + """ def __init__(self, optimizer, inv_gamma=1., power=1., warmup=0., min_lr=0., last_epoch=-1, verbose=False): @@ -128,6 +175,21 @@ class ExponentialLR(optim.lr_scheduler._LRScheduler): + """Implements an exponential learning rate schedule with an optional exponential + warmup. When last_epoch=-1, sets initial lr as lr. Decays the learning rate + continuously by decay (default 0.5) every num_steps steps. + Args: + optimizer (Optimizer): Wrapped optimizer. + num_steps (float): The number of steps to decay the learning rate by decay in. + decay (float): The factor by which to decay the learning rate every num_steps + steps. Default: 0.5. + warmup (float): Exponential warmup factor (0 <= warmup < 1, 0 to disable) + Default: 0. + min_lr (float): The minimum learning rate. Default: 0. + last_epoch (int): The index of last epoch. Default: -1. + verbose (bool): If ``True``, prints a message to stdout for + each update. Default: ``False``. + """ def __init__(self, optimizer, num_steps, decay=0.5, warmup=0., min_lr=0., last_epoch=-1, verbose=False): @@ -154,10 +216,12 @@ def rand_log_normal(shape, loc=0., scale=1., device='cpu', dtype=torch.float32): + """Draws samples from an lognormal distribution.""" return (torch.randn(shape, device=device, dtype=dtype) * scale + loc).exp() def rand_log_logistic(shape, loc=0., scale=1., min_value=0., max_value=float('inf'), device='cpu', dtype=torch.float32): + """Draws samples from an optionally truncated log-logistic distribution.""" min_value = torch.as_tensor(min_value, device=device, dtype=torch.float64) max_value = torch.as_tensor(max_value, device=device, dtype=torch.float64) min_cdf = min_value.log().sub(loc).div(scale).sigmoid() @@ -167,12 +231,14 @@ def rand_log_uniform(shape, min_value, max_value, device='cpu', dtype=torch.float32): + """Draws samples from an log-uniform distribution.""" min_value = math.log(min_value) max_value = math.log(max_value) return (torch.rand(shape, device=device, dtype=dtype) * (max_value - min_value) + min_value).exp() def rand_v_diffusion(shape, sigma_data=1., min_value=0., max_value=float('inf'), device='cpu', dtype=torch.float32): + """Draws samples from a truncated v-diffusion training timestep distribution.""" min_cdf = math.atan(min_value / sigma_data) * 2 / math.pi max_cdf = math.atan(max_value / sigma_data) * 2 / math.pi u = torch.rand(shape, device=device, dtype=dtype) * (max_cdf - min_cdf) + min_cdf @@ -180,6 +246,7 @@ def rand_split_log_normal(shape, loc, scale_1, scale_2, device='cpu', dtype=torch.float32): + """Draws samples from a split lognormal distribution.""" n = torch.randn(shape, device=device, dtype=dtype).abs() u = torch.rand(shape, device=device, dtype=dtype) n_left = n * -scale_1 + loc @@ -189,6 +256,8 @@ class FolderOfImages(data.Dataset): + """Recursively finds all images in a directory. It does not support + classes/targets.""" IMG_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp'} @@ -228,6 +297,7 @@ @contextmanager def tf32_mode(cudnn=None, matmul=None): + """A context manager that sets whether TF32 is allowed on cuDNN or matmul.""" cudnn_old = torch.backends.cudnn.allow_tf32 matmul_old = torch.backends.cuda.matmul.allow_tf32 try: @@ -240,4 +310,4 @@ if cudnn is not None: torch.backends.cudnn.allow_tf32 = cudnn_old if matmul is not None: - torch.backends.cuda.matmul.allow_tf32 = matmul_old+ torch.backends.cuda.matmul.allow_tf32 = matmul_old
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, 0.0], [0.0, 1.0, -1.0], [0.0, 0.0, 0.0]]], [[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]]], [[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, -1.0, 0.0]]], [[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 0.0]]], [[[0.0, 0.0, 0.0], [-1.0, 1.0, 0.0], [0.0, 0.0, 0.0]]], [[[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]]], [[[0.0, -1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]]], [[[0.0, 0.0, -1.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]]], ], device=device, dtype=dtype, ) def get_hysteresis_kernel(device=None, dtype=None): return torch.tensor( [ [[[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 0.0]]], [[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]], [[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]]], [[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]], [[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0]]], [[[1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]], [[[0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]], [[[0.0, 0.0, 1.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]], ], device=device, dtype=dtype, ) def gaussian_blur_2d(img, kernel_size, sigma): ksize_half = (kernel_size - 1) * 0.5 x = torch.linspace(-ksize_half, ksize_half, steps=kernel_size) pdf = torch.exp(-0.5 * (x / sigma).pow(2)) x_kernel = pdf / pdf.sum() x_kernel = x_kernel.to(device=img.device, dtype=img.dtype) kernel2d = torch.mm(x_kernel[:, None], x_kernel[None, :]) kernel2d = kernel2d.expand(img.shape[-3], 1, kernel2d.shape[0], kernel2d.shape[1]) padding = [kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2] img = torch.nn.functional.pad(img, padding, mode="reflect") img = torch.nn.functional.conv2d(img, kernel2d, groups=img.shape[-3]) return img def get_sobel_kernel2d(device=None, dtype=None): kernel_x = torch.tensor([[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]], device=device, dtype=dtype) kernel_y = kernel_x.transpose(0, 1) return torch.stack([kernel_x, kernel_y]) def spatial_gradient(input, normalized: bool = True): # KORNIA_CHECK_IS_TENSOR(input) # KORNIA_CHECK_SHAPE(input, ['B', 'C', 'H', 'W']) # allocate kernel kernel = get_sobel_kernel2d(device=input.device, dtype=input.dtype) if normalized: kernel = normalize_kernel2d(kernel) # prepare kernel b, c, h, w = input.shape tmp_kernel = kernel[:, None, ...] # Pad with "replicate for spatial dims, but with zeros for channel spatial_pad = [kernel.size(1) // 2, kernel.size(1) // 2, kernel.size(2) // 2, kernel.size(2) // 2] out_channels: int = 2 padded_inp = torch.nn.functional.pad(input.reshape(b * c, 1, h, w), spatial_pad, 'replicate') out = F.conv2d(padded_inp, tmp_kernel, groups=1, padding=0, stride=1) return out.reshape(b, c, out_channels, h, w) def rgb_to_grayscale(image, rgb_weights = None): if len(image.shape) < 3 or image.shape[-3] != 3: raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") if rgb_weights is None: # 8 bit images if image.dtype == torch.uint8: rgb_weights = torch.tensor([76, 150, 29], device=image.device, dtype=torch.uint8) # floating point images elif image.dtype in (torch.float16, torch.float32, torch.float64): rgb_weights = torch.tensor([0.299, 0.587, 0.114], device=image.device, dtype=image.dtype) else: raise TypeError(f"Unknown data type: {image.dtype}") else: # is tensor that we make sure is in the same device/dtype rgb_weights = rgb_weights.to(image) # unpack the color image channels with RGB order r: Tensor = image[..., 0:1, :, :] g: Tensor = image[..., 1:2, :, :] b: Tensor = image[..., 2:3, :, :] w_r, w_g, w_b = rgb_weights.unbind() return w_r * r + w_g * g + w_b * b def canny( input, low_threshold = 0.1, high_threshold = 0.2, kernel_size = 5, sigma = 1, hysteresis = True, eps = 1e-6, ): # KORNIA_CHECK_IS_TENSOR(input) # KORNIA_CHECK_SHAPE(input, ['B', 'C', 'H', 'W']) # KORNIA_CHECK( # low_threshold <= high_threshold, # "Invalid input thresholds. low_threshold should be smaller than the high_threshold. Got: " # f"{low_threshold}>{high_threshold}", # ) # KORNIA_CHECK(0 < low_threshold < 1, f'Invalid low threshold. Should be in range (0, 1). Got: {low_threshold}') # KORNIA_CHECK(0 < high_threshold < 1, f'Invalid high threshold. Should be in range (0, 1). Got: {high_threshold}') device = input.device dtype = input.dtype # To Grayscale if input.shape[1] == 3: input = rgb_to_grayscale(input) # Gaussian filter blurred: Tensor = gaussian_blur_2d(input, kernel_size, sigma) # Compute the gradients gradients: Tensor = spatial_gradient(blurred, normalized=False) # Unpack the edges gx: Tensor = gradients[:, :, 0] gy: Tensor = gradients[:, :, 1] # Compute gradient magnitude and angle magnitude: Tensor = torch.sqrt(gx * gx + gy * gy + eps) angle: Tensor = torch.atan2(gy, gx) # Radians to Degrees angle = 180.0 * angle / math.pi # Round angle to the nearest 45 degree angle = torch.round(angle / 45) * 45 # Non-maximal suppression nms_kernels: Tensor = get_canny_nms_kernel(device, dtype) nms_magnitude: Tensor = F.conv2d(magnitude, nms_kernels, padding=nms_kernels.shape[-1] // 2) # Get the indices for both directions positive_idx: Tensor = (angle / 45) % 8 positive_idx = positive_idx.long() negative_idx: Tensor = ((angle / 45) + 4) % 8 negative_idx = negative_idx.long() # Apply the non-maximum suppression to the different directions channel_select_filtered_positive: Tensor = torch.gather(nms_magnitude, 1, positive_idx) channel_select_filtered_negative: Tensor = torch.gather(nms_magnitude, 1, negative_idx) channel_select_filtered: Tensor = torch.stack( [channel_select_filtered_positive, channel_select_filtered_negative], 1 ) is_max: Tensor = channel_select_filtered.min(dim=1)[0] > 0.0 magnitude = magnitude * is_max # Threshold edges: Tensor = F.threshold(magnitude, low_threshold, 0.0) low: Tensor = magnitude > low_threshold high: Tensor = magnitude > high_threshold edges = low * 0.5 + high * 0.5 edges = edges.to(dtype) # Hysteresis if hysteresis: edges_old: Tensor = -torch.ones(edges.shape, device=edges.device, dtype=dtype) hysteresis_kernels: Tensor = get_hysteresis_kernel(device, dtype) while ((edges_old - edges).abs() != 0).any(): weak: Tensor = (edges == 0.5).float() strong: Tensor = (edges == 1).float() hysteresis_magnitude: Tensor = F.conv2d( edges, hysteresis_kernels, padding=hysteresis_kernels.shape[-1] // 2 ) hysteresis_magnitude = (hysteresis_magnitude == 1).any(1, keepdim=True).to(dtype) hysteresis_magnitude = hysteresis_magnitude * weak + strong edges_old = edges.clone() edges = hysteresis_magnitude + (hysteresis_magnitude == 0) * weak * 0.5 edges = hysteresis_magnitude return magnitude, edges class Canny: @classmethod def INPUT_TYPES(s): return {"required": {"image": ("IMAGE",), "low_threshold": ("FLOAT", {"default": 0.4, "min": 0.01, "max": 0.99, "step": 0.01}), "high_threshold": ("FLOAT", {"default": 0.8, "min": 0.01, "max": 0.99, "step": 0.01}) }} RETURN_TYPES = ("IMAGE",) FUNCTION = "detect_edge" CATEGORY = "image/preprocessors" def detect_edge(self, image, low_threshold, high_threshold): output = canny(image.to(ldm_patched.modules.model_management.get_torch_device()).movedim(-1, 1), low_threshold, high_threshold) img_out = output[1].to(ldm_patched.modules.model_management.intermediate_device()).repeat(1, 3, 1, 1).movedim(1, -1) return (img_out,) NODE_CLASS_MAPPINGS = { "Canny": Canny, }
--- +++ @@ -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]]], @@ -25,6 +26,7 @@ def get_hysteresis_kernel(device=None, dtype=None): + """Utility function that returns the 3x3 kernels for the Canny hysteresis.""" return torch.tensor( [ [[[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 0.0]]], @@ -66,6 +68,24 @@ return torch.stack([kernel_x, kernel_y]) def spatial_gradient(input, normalized: bool = True): + r"""Compute the first order image derivative in both x and y using a Sobel operator. + .. image:: _static/img/spatial_gradient.png + Args: + input: input image tensor with shape :math:`(B, C, H, W)`. + mode: derivatives modality, can be: `sobel` or `diff`. + order: the order of the derivatives. + normalized: whether the output is normalized. + Return: + the derivatives of the input feature map. with shape :math:`(B, C, 2, H, W)`. + .. note:: + See a working example `here <https://kornia.readthedocs.io/en/latest/ + filtering_edges.html>`__. + Examples: + >>> input = torch.rand(1, 3, 4, 4) + >>> output = spatial_gradient(input) # 1x3x2x4x4 + >>> output.shape + torch.Size([1, 3, 2, 4, 4]) + """ # KORNIA_CHECK_IS_TENSOR(input) # KORNIA_CHECK_SHAPE(input, ['B', 'C', 'H', 'W']) @@ -86,6 +106,27 @@ return out.reshape(b, c, out_channels, h, w) def rgb_to_grayscale(image, rgb_weights = None): + r"""Convert a RGB image to grayscale version of image. + + .. image:: _static/img/rgb_to_grayscale.png + + The image data is assumed to be in the range of (0, 1). + + Args: + image: RGB image to be converted to grayscale with shape :math:`(*,3,H,W)`. + rgb_weights: Weights that will be applied on each channel (RGB). + The sum of the weights should add up to one. + Returns: + grayscale version of the image with shape :math:`(*,1,H,W)`. + + .. note:: + See a working example `here <https://kornia.readthedocs.io/en/latest/ + color_conversions.html>`__. + + Example: + >>> input = torch.rand(2, 3, 4, 5) + >>> gray = rgb_to_grayscale(input) # 2x1x4x5 + """ if len(image.shape) < 3 or image.shape[-3] != 3: raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}") @@ -120,6 +161,31 @@ hysteresis = True, eps = 1e-6, ): + r"""Find edges of the input image and filters them using the Canny algorithm. + .. image:: _static/img/canny.png + Args: + input: input image tensor with shape :math:`(B,C,H,W)`. + low_threshold: lower threshold for the hysteresis procedure. + high_threshold: upper threshold for the hysteresis procedure. + kernel_size: the size of the kernel for the gaussian blur. + sigma: the standard deviation of the kernel for the gaussian blur. + hysteresis: if True, applies the hysteresis edge tracking. + Otherwise, the edges are divided between weak (0.5) and strong (1) edges. + eps: regularization number to avoid NaN during backprop. + Returns: + - the canny edge magnitudes map, shape of :math:`(B,1,H,W)`. + - the canny edge detection filtered by thresholds and hysteresis, shape of :math:`(B,1,H,W)`. + .. note:: + See a working example `here <https://kornia.readthedocs.io/en/latest/ + canny.html>`__. + Example: + >>> input = torch.rand(5, 3, 4, 4) + >>> magnitude, edges = canny(input) # 5x3x4x4 + >>> magnitude.shape + torch.Size([5, 1, 4, 4]) + >>> edges.shape + torch.Size([5, 1, 4, 4]) + """ # KORNIA_CHECK_IS_TENSOR(input) # KORNIA_CHECK_SHAPE(input, ['B', 'C', 'H', 'W']) # KORNIA_CHECK( @@ -232,4 +298,4 @@ NODE_CLASS_MAPPINGS = { "Canny": Canny, -}+}
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, device=device) min_inv_rho = sigma_min ** (1 / rho) max_inv_rho = sigma_max ** (1 / rho) sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return append_zero(sigmas).to(device) def get_sigmas_exponential(n, sigma_min, sigma_max, device='cpu'): sigmas = torch.linspace(math.log(sigma_max), math.log(sigma_min), n, device=device).exp() return append_zero(sigmas) def get_sigmas_polyexponential(n, sigma_min, sigma_max, rho=1., device='cpu'): ramp = torch.linspace(1, 0, n, device=device) ** rho sigmas = torch.exp(ramp * (math.log(sigma_max) - math.log(sigma_min)) + math.log(sigma_min)) return append_zero(sigmas) def get_sigmas_vp(n, beta_d=19.9, beta_min=0.1, eps_s=1e-3, device='cpu'): t = torch.linspace(1, eps_s, n, device=device) sigmas = torch.sqrt(torch.exp(beta_d * t ** 2 / 2 + beta_min * t) - 1) return append_zero(sigmas) def to_d(x, sigma, denoised): return (x - denoised) / utils.append_dims(sigma, x.ndim) def get_ancestral_step(sigma_from, sigma_to, eta=1.): if not eta: return sigma_to, 0. sigma_up = min(sigma_to, eta * (sigma_to ** 2 * (sigma_from ** 2 - sigma_to ** 2) / sigma_from ** 2) ** 0.5) sigma_down = (sigma_to ** 2 - sigma_up ** 2) ** 0.5 return sigma_down, sigma_up def default_noise_sampler(x): return lambda sigma, sigma_next: torch.randn_like(x) class BatchedBrownianTree: def __init__(self, x, t0, t1, seed=None, **kwargs): self.cpu_tree = True if "cpu" in kwargs: self.cpu_tree = kwargs.pop("cpu") t0, t1, self.sign = self.sort(t0, t1) w0 = kwargs.get('w0', torch.zeros_like(x)) if seed is None: seed = torch.randint(0, 2 ** 63 - 1, []).item() self.batched = True try: assert len(seed) == x.shape[0] w0 = w0[0] except TypeError: seed = [seed] self.batched = False if self.cpu_tree: self.trees = [torchsde.BrownianTree(t0.cpu(), w0.cpu(), t1.cpu(), entropy=s, **kwargs) for s in seed] else: self.trees = [torchsde.BrownianTree(t0, w0, t1, entropy=s, **kwargs) for s in seed] @staticmethod def sort(a, b): return (a, b, 1) if a < b else (b, a, -1) def __call__(self, t0, t1): t0, t1, sign = self.sort(t0, t1) if self.cpu_tree: w = torch.stack([tree(t0.cpu().float(), t1.cpu().float()).to(t0.dtype).to(t0.device) for tree in self.trees]) * (self.sign * sign) else: w = torch.stack([tree(t0, t1) for tree in self.trees]) * (self.sign * sign) return w if self.batched else w[0] class BrownianTreeNoiseSampler: def __init__(self, x, sigma_min, sigma_max, seed=None, transform=lambda x: x, cpu=False): self.transform = transform t0, t1 = self.transform(torch.as_tensor(sigma_min)), self.transform(torch.as_tensor(sigma_max)) self.tree = BatchedBrownianTree(x, t0, t1, seed, cpu=cpu) def __call__(self, sigma, sigma_next): t0, t1 = self.transform(torch.as_tensor(sigma)), self.transform(torch.as_tensor(sigma_next)) return self.tree(t0, t1) / (t1 - t0).abs().sqrt() @torch.no_grad() def sample_euler(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0., s_tmin=0., s_tmax=float('inf'), s_noise=1.): extra_args = {} if extra_args is None else extra_args s_in = x.new_ones([x.shape[0]]) for i in trange(len(sigmas) - 1, disable=disable): gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0. sigma_hat = sigmas[i] * (gamma + 1) if gamma > 0: eps = torch.randn_like(x) * s_noise x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5 denoised = model(x, sigma_hat * s_in, **extra_args) d = to_d(x, sigma_hat, denoised) if callback is not None: callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised}) dt = sigmas[i + 1] - sigma_hat # Euler method x = x + d * dt return x @torch.no_grad() def sample_euler_ancestral(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None): extra_args = {} if extra_args is None else extra_args noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler s_in = x.new_ones([x.shape[0]]) for i in trange(len(sigmas) - 1, disable=disable): denoised = model(x, sigmas[i] * s_in, **extra_args) sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta) if callback is not None: callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) d = to_d(x, sigmas[i], denoised) # Euler method dt = sigma_down - sigmas[i] x = x + d * dt if sigmas[i + 1] > 0: x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up return x @torch.no_grad() def sample_heun(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0., s_tmin=0., s_tmax=float('inf'), s_noise=1.): extra_args = {} if extra_args is None else extra_args s_in = x.new_ones([x.shape[0]]) for i in trange(len(sigmas) - 1, disable=disable): gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0. sigma_hat = sigmas[i] * (gamma + 1) if gamma > 0: eps = torch.randn_like(x) * s_noise x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5 denoised = model(x, sigma_hat * s_in, **extra_args) d = to_d(x, sigma_hat, denoised) if callback is not None: callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised}) dt = sigmas[i + 1] - sigma_hat if sigmas[i + 1] == 0: # Euler method x = x + d * dt else: # Heun's method x_2 = x + d * dt denoised_2 = model(x_2, sigmas[i + 1] * s_in, **extra_args) d_2 = to_d(x_2, sigmas[i + 1], denoised_2) d_prime = (d + d_2) / 2 x = x + d_prime * dt return x @torch.no_grad() def sample_dpm_2(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0., s_tmin=0., s_tmax=float('inf'), s_noise=1.): extra_args = {} if extra_args is None else extra_args s_in = x.new_ones([x.shape[0]]) for i in trange(len(sigmas) - 1, disable=disable): gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0. sigma_hat = sigmas[i] * (gamma + 1) if gamma > 0: eps = torch.randn_like(x) * s_noise x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5 denoised = model(x, sigma_hat * s_in, **extra_args) d = to_d(x, sigma_hat, denoised) if callback is not None: callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised}) if sigmas[i + 1] == 0: # Euler method dt = sigmas[i + 1] - sigma_hat x = x + d * dt else: # DPM-Solver-2 sigma_mid = sigma_hat.log().lerp(sigmas[i + 1].log(), 0.5).exp() dt_1 = sigma_mid - sigma_hat dt_2 = sigmas[i + 1] - sigma_hat x_2 = x + d * dt_1 denoised_2 = model(x_2, sigma_mid * s_in, **extra_args) d_2 = to_d(x_2, sigma_mid, denoised_2) x = x + d_2 * dt_2 return x @torch.no_grad() def sample_dpm_2_ancestral(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None): extra_args = {} if extra_args is None else extra_args noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler s_in = x.new_ones([x.shape[0]]) for i in trange(len(sigmas) - 1, disable=disable): denoised = model(x, sigmas[i] * s_in, **extra_args) sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta) if callback is not None: callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) d = to_d(x, sigmas[i], denoised) if sigma_down == 0: # Euler method dt = sigma_down - sigmas[i] x = x + d * dt else: # DPM-Solver-2 sigma_mid = sigmas[i].log().lerp(sigma_down.log(), 0.5).exp() dt_1 = sigma_mid - sigmas[i] dt_2 = sigma_down - sigmas[i] x_2 = x + d * dt_1 denoised_2 = model(x_2, sigma_mid * s_in, **extra_args) d_2 = to_d(x_2, sigma_mid, denoised_2) x = x + d_2 * dt_2 x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up return x def linear_multistep_coeff(order, t, i, j): if order - 1 > i: raise ValueError(f'Order {order} too high for step {i}') def fn(tau): prod = 1. for k in range(order): if j == k: continue prod *= (tau - t[i - k]) / (t[i - j] - t[i - k]) return prod return integrate.quad(fn, t[i], t[i + 1], epsrel=1e-4)[0] @torch.no_grad() def sample_lms(model, x, sigmas, extra_args=None, callback=None, disable=None, order=4): extra_args = {} if extra_args is None else extra_args s_in = x.new_ones([x.shape[0]]) sigmas_cpu = sigmas.detach().cpu().numpy() ds = [] for i in trange(len(sigmas) - 1, disable=disable): denoised = model(x, sigmas[i] * s_in, **extra_args) d = to_d(x, sigmas[i], denoised) ds.append(d) if len(ds) > order: ds.pop(0) if callback is not None: callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) cur_order = min(i + 1, order) coeffs = [linear_multistep_coeff(cur_order, sigmas_cpu, i, j) for j in range(cur_order)] x = x + sum(coeff * d for coeff, d in zip(coeffs, reversed(ds))) return x class PIDStepSizeController: def __init__(self, h, pcoeff, icoeff, dcoeff, order=1, accept_safety=0.81, eps=1e-8): self.h = h self.b1 = (pcoeff + icoeff + dcoeff) / order self.b2 = -(pcoeff + 2 * dcoeff) / order self.b3 = dcoeff / order self.accept_safety = accept_safety self.eps = eps self.errs = [] def limiter(self, x): return 1 + math.atan(x - 1) def propose_step(self, error): inv_error = 1 / (float(error) + self.eps) if not self.errs: self.errs = [inv_error, inv_error, inv_error] self.errs[0] = inv_error factor = self.errs[0] ** self.b1 * self.errs[1] ** self.b2 * self.errs[2] ** self.b3 factor = self.limiter(factor) accept = factor >= self.accept_safety if accept: self.errs[2] = self.errs[1] self.errs[1] = self.errs[0] self.h *= factor return accept class DPMSolver(nn.Module): def __init__(self, model, extra_args=None, eps_callback=None, info_callback=None): super().__init__() self.model = model self.extra_args = {} if extra_args is None else extra_args self.eps_callback = eps_callback self.info_callback = info_callback def t(self, sigma): return -sigma.log() def sigma(self, t): return t.neg().exp() def eps(self, eps_cache, key, x, t, *args, **kwargs): if key in eps_cache: return eps_cache[key], eps_cache sigma = self.sigma(t) * x.new_ones([x.shape[0]]) eps = (x - self.model(x, sigma, *args, **self.extra_args, **kwargs)) / self.sigma(t) if self.eps_callback is not None: self.eps_callback() return eps, {key: eps, **eps_cache} def dpm_solver_1_step(self, x, t, t_next, eps_cache=None): eps_cache = {} if eps_cache is None else eps_cache h = t_next - t eps, eps_cache = self.eps(eps_cache, 'eps', x, t) x_1 = x - self.sigma(t_next) * h.expm1() * eps return x_1, eps_cache def dpm_solver_2_step(self, x, t, t_next, r1=1 / 2, eps_cache=None): eps_cache = {} if eps_cache is None else eps_cache h = t_next - t eps, eps_cache = self.eps(eps_cache, 'eps', x, t) s1 = t + r1 * h u1 = x - self.sigma(s1) * (r1 * h).expm1() * eps eps_r1, eps_cache = self.eps(eps_cache, 'eps_r1', u1, s1) x_2 = x - self.sigma(t_next) * h.expm1() * eps - self.sigma(t_next) / (2 * r1) * h.expm1() * (eps_r1 - eps) return x_2, eps_cache def dpm_solver_3_step(self, x, t, t_next, r1=1 / 3, r2=2 / 3, eps_cache=None): eps_cache = {} if eps_cache is None else eps_cache h = t_next - t eps, eps_cache = self.eps(eps_cache, 'eps', x, t) s1 = t + r1 * h s2 = t + r2 * h u1 = x - self.sigma(s1) * (r1 * h).expm1() * eps eps_r1, eps_cache = self.eps(eps_cache, 'eps_r1', u1, s1) u2 = x - self.sigma(s2) * (r2 * h).expm1() * eps - self.sigma(s2) * (r2 / r1) * ((r2 * h).expm1() / (r2 * h) - 1) * (eps_r1 - eps) eps_r2, eps_cache = self.eps(eps_cache, 'eps_r2', u2, s2) x_3 = x - self.sigma(t_next) * h.expm1() * eps - self.sigma(t_next) / r2 * (h.expm1() / h - 1) * (eps_r2 - eps) return x_3, eps_cache def dpm_solver_fast(self, x, t_start, t_end, nfe, eta=0., s_noise=1., noise_sampler=None): noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler if not t_end > t_start and eta: raise ValueError('eta must be 0 for reverse sampling') m = math.floor(nfe / 3) + 1 ts = torch.linspace(t_start, t_end, m + 1, device=x.device) if nfe % 3 == 0: orders = [3] * (m - 2) + [2, 1] else: orders = [3] * (m - 1) + [nfe % 3] for i in range(len(orders)): eps_cache = {} t, t_next = ts[i], ts[i + 1] if eta: sd, su = get_ancestral_step(self.sigma(t), self.sigma(t_next), eta) t_next_ = torch.minimum(t_end, self.t(sd)) su = (self.sigma(t_next) ** 2 - self.sigma(t_next_) ** 2) ** 0.5 else: t_next_, su = t_next, 0. eps, eps_cache = self.eps(eps_cache, 'eps', x, t) denoised = x - self.sigma(t) * eps if self.info_callback is not None: self.info_callback({'x': x, 'i': i, 't': ts[i], 't_up': t, 'denoised': denoised}) if orders[i] == 1: x, eps_cache = self.dpm_solver_1_step(x, t, t_next_, eps_cache=eps_cache) elif orders[i] == 2: x, eps_cache = self.dpm_solver_2_step(x, t, t_next_, eps_cache=eps_cache) else: x, eps_cache = self.dpm_solver_3_step(x, t, t_next_, eps_cache=eps_cache) x = x + su * s_noise * noise_sampler(self.sigma(t), self.sigma(t_next)) return x def dpm_solver_adaptive(self, x, t_start, t_end, order=3, rtol=0.05, atol=0.0078, h_init=0.05, pcoeff=0., icoeff=1., dcoeff=0., accept_safety=0.81, eta=0., s_noise=1., noise_sampler=None): noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler if order not in {2, 3}: raise ValueError('order should be 2 or 3') forward = t_end > t_start if not forward and eta: raise ValueError('eta must be 0 for reverse sampling') h_init = abs(h_init) * (1 if forward else -1) atol = torch.tensor(atol) rtol = torch.tensor(rtol) s = t_start x_prev = x accept = True pid = PIDStepSizeController(h_init, pcoeff, icoeff, dcoeff, 1.5 if eta else order, accept_safety) info = {'steps': 0, 'nfe': 0, 'n_accept': 0, 'n_reject': 0} while s < t_end - 1e-5 if forward else s > t_end + 1e-5: eps_cache = {} t = torch.minimum(t_end, s + pid.h) if forward else torch.maximum(t_end, s + pid.h) if eta: sd, su = get_ancestral_step(self.sigma(s), self.sigma(t), eta) t_ = torch.minimum(t_end, self.t(sd)) su = (self.sigma(t) ** 2 - self.sigma(t_) ** 2) ** 0.5 else: t_, su = t, 0. eps, eps_cache = self.eps(eps_cache, 'eps', x, s) denoised = x - self.sigma(s) * eps if order == 2: x_low, eps_cache = self.dpm_solver_1_step(x, s, t_, eps_cache=eps_cache) x_high, eps_cache = self.dpm_solver_2_step(x, s, t_, eps_cache=eps_cache) else: x_low, eps_cache = self.dpm_solver_2_step(x, s, t_, r1=1 / 3, eps_cache=eps_cache) x_high, eps_cache = self.dpm_solver_3_step(x, s, t_, eps_cache=eps_cache) delta = torch.maximum(atol, rtol * torch.maximum(x_low.abs(), x_prev.abs())) error = torch.linalg.norm((x_low - x_high) / delta) / x.numel() ** 0.5 accept = pid.propose_step(error) if accept: x_prev = x_low x = x_high + su * s_noise * noise_sampler(self.sigma(s), self.sigma(t)) s = t info['n_accept'] += 1 else: info['n_reject'] += 1 info['nfe'] += order info['steps'] += 1 if self.info_callback is not None: self.info_callback({'x': x, 'i': info['steps'] - 1, 't': s, 't_up': s, 'denoised': denoised, 'error': error, 'h': pid.h, **info}) return x, info @torch.no_grad() def sample_dpm_fast(model, x, sigma_min, sigma_max, n, extra_args=None, callback=None, disable=None, eta=0., s_noise=1., noise_sampler=None): if sigma_min <= 0 or sigma_max <= 0: raise ValueError('sigma_min and sigma_max must not be 0') with tqdm(total=n, disable=disable) as pbar: dpm_solver = DPMSolver(model, extra_args, eps_callback=pbar.update) if callback is not None: dpm_solver.info_callback = lambda info: callback({'sigma': dpm_solver.sigma(info['t']), 'sigma_hat': dpm_solver.sigma(info['t_up']), **info}) return dpm_solver.dpm_solver_fast(x, dpm_solver.t(torch.tensor(sigma_max)), dpm_solver.t(torch.tensor(sigma_min)), n, eta, s_noise, noise_sampler) @torch.no_grad() def sample_dpm_adaptive(model, x, sigma_min, sigma_max, extra_args=None, callback=None, disable=None, order=3, rtol=0.05, atol=0.0078, h_init=0.05, pcoeff=0., icoeff=1., dcoeff=0., accept_safety=0.81, eta=0., s_noise=1., noise_sampler=None, return_info=False): if sigma_min <= 0 or sigma_max <= 0: raise ValueError('sigma_min and sigma_max must not be 0') with tqdm(disable=disable) as pbar: dpm_solver = DPMSolver(model, extra_args, eps_callback=pbar.update) if callback is not None: dpm_solver.info_callback = lambda info: callback({'sigma': dpm_solver.sigma(info['t']), 'sigma_hat': dpm_solver.sigma(info['t_up']), **info}) x, info = dpm_solver.dpm_solver_adaptive(x, dpm_solver.t(torch.tensor(sigma_max)), dpm_solver.t(torch.tensor(sigma_min)), order, rtol, atol, h_init, pcoeff, icoeff, dcoeff, accept_safety, eta, s_noise, noise_sampler) if return_info: return x, info return x @torch.no_grad() def sample_dpmpp_2s_ancestral(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None): extra_args = {} if extra_args is None else extra_args noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler s_in = x.new_ones([x.shape[0]]) sigma_fn = lambda t: t.neg().exp() t_fn = lambda sigma: sigma.log().neg() for i in trange(len(sigmas) - 1, disable=disable): denoised = model(x, sigmas[i] * s_in, **extra_args) sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta) if callback is not None: callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) if sigma_down == 0: # Euler method d = to_d(x, sigmas[i], denoised) dt = sigma_down - sigmas[i] x = x + d * dt else: # DPM-Solver++(2S) t, t_next = t_fn(sigmas[i]), t_fn(sigma_down) r = 1 / 2 h = t_next - t s = t + r * h x_2 = (sigma_fn(s) / sigma_fn(t)) * x - (-h * r).expm1() * denoised denoised_2 = model(x_2, sigma_fn(s) * s_in, **extra_args) x = (sigma_fn(t_next) / sigma_fn(t)) * x - (-h).expm1() * denoised_2 # Noise addition if sigmas[i + 1] > 0: x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up return x @torch.no_grad() def sample_dpmpp_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, r=1 / 2): sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max() seed = extra_args.get("seed", None) noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed, cpu=True) if noise_sampler is None else noise_sampler extra_args = {} if extra_args is None else extra_args s_in = x.new_ones([x.shape[0]]) sigma_fn = lambda t: t.neg().exp() t_fn = lambda sigma: sigma.log().neg() for i in trange(len(sigmas) - 1, disable=disable): denoised = model(x, sigmas[i] * s_in, **extra_args) if callback is not None: callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) if sigmas[i + 1] == 0: # Euler method d = to_d(x, sigmas[i], denoised) dt = sigmas[i + 1] - sigmas[i] x = x + d * dt else: # DPM-Solver++ t, t_next = t_fn(sigmas[i]), t_fn(sigmas[i + 1]) h = t_next - t s = t + h * r fac = 1 / (2 * r) # Step 1 sd, su = get_ancestral_step(sigma_fn(t), sigma_fn(s), eta) s_ = t_fn(sd) x_2 = (sigma_fn(s_) / sigma_fn(t)) * x - (t - s_).expm1() * denoised x_2 = x_2 + noise_sampler(sigma_fn(t), sigma_fn(s)) * s_noise * su denoised_2 = model(x_2, sigma_fn(s) * s_in, **extra_args) # Step 2 sd, su = get_ancestral_step(sigma_fn(t), sigma_fn(t_next), eta) t_next_ = t_fn(sd) denoised_d = (1 - fac) * denoised + fac * denoised_2 x = (sigma_fn(t_next_) / sigma_fn(t)) * x - (t - t_next_).expm1() * denoised_d x = x + noise_sampler(sigma_fn(t), sigma_fn(t_next)) * s_noise * su return x @torch.no_grad() def sample_dpmpp_2m(model, x, sigmas, extra_args=None, callback=None, disable=None): extra_args = {} if extra_args is None else extra_args s_in = x.new_ones([x.shape[0]]) sigma_fn = lambda t: t.neg().exp() t_fn = lambda sigma: sigma.log().neg() old_denoised = None for i in trange(len(sigmas) - 1, disable=disable): denoised = model(x, sigmas[i] * s_in, **extra_args) if callback is not None: callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) t, t_next = t_fn(sigmas[i]), t_fn(sigmas[i + 1]) h = t_next - t if old_denoised is None or sigmas[i + 1] == 0: x = (sigma_fn(t_next) / sigma_fn(t)) * x - (-h).expm1() * denoised else: h_last = t - t_fn(sigmas[i - 1]) r = h_last / h denoised_d = (1 + 1 / (2 * r)) * denoised - (1 / (2 * r)) * old_denoised x = (sigma_fn(t_next) / sigma_fn(t)) * x - (-h).expm1() * denoised_d old_denoised = denoised return x @torch.no_grad() def sample_dpmpp_2m_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, solver_type='midpoint'): if solver_type not in {'heun', 'midpoint'}: raise ValueError('solver_type must be \'heun\' or \'midpoint\'') seed = extra_args.get("seed", None) sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max() noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed, cpu=True) if noise_sampler is None else noise_sampler extra_args = {} if extra_args is None else extra_args s_in = x.new_ones([x.shape[0]]) old_denoised = None h_last = None h = None for i in trange(len(sigmas) - 1, disable=disable): denoised = model(x, sigmas[i] * s_in, **extra_args) if callback is not None: callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) if sigmas[i + 1] == 0: # Denoising step x = denoised else: # DPM-Solver++(2M) SDE t, s = -sigmas[i].log(), -sigmas[i + 1].log() h = s - t eta_h = eta * h x = sigmas[i + 1] / sigmas[i] * (-eta_h).exp() * x + (-h - eta_h).expm1().neg() * denoised if old_denoised is not None: r = h_last / h if solver_type == 'heun': x = x + ((-h - eta_h).expm1().neg() / (-h - eta_h) + 1) * (1 / r) * (denoised - old_denoised) elif solver_type == 'midpoint': x = x + 0.5 * (-h - eta_h).expm1().neg() * (1 / r) * (denoised - old_denoised) if eta: x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * sigmas[i + 1] * (-2 * eta_h).expm1().neg().sqrt() * s_noise old_denoised = denoised h_last = h return x @torch.no_grad() def sample_dpmpp_3m_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None): seed = extra_args.get("seed", None) sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max() noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed, cpu=True) if noise_sampler is None else noise_sampler extra_args = {} if extra_args is None else extra_args s_in = x.new_ones([x.shape[0]]) denoised_1, denoised_2 = None, None h, h_1, h_2 = None, None, None for i in trange(len(sigmas) - 1, disable=disable): denoised = model(x, sigmas[i] * s_in, **extra_args) if callback is not None: callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) if sigmas[i + 1] == 0: # Denoising step x = denoised else: t, s = -sigmas[i].log(), -sigmas[i + 1].log() h = s - t h_eta = h * (eta + 1) x = torch.exp(-h_eta) * x + (-h_eta).expm1().neg() * denoised if h_2 is not None: r0 = h_1 / h r1 = h_2 / h d1_0 = (denoised - denoised_1) / r0 d1_1 = (denoised_1 - denoised_2) / r1 d1 = d1_0 + (d1_0 - d1_1) * r0 / (r0 + r1) d2 = (d1_0 - d1_1) / (r0 + r1) phi_2 = h_eta.neg().expm1() / h_eta + 1 phi_3 = phi_2 / h_eta - 0.5 x = x + phi_2 * d1 - phi_3 * d2 elif h_1 is not None: r = h_1 / h d = (denoised - denoised_1) / r phi_2 = h_eta.neg().expm1() / h_eta + 1 x = x + phi_2 * d if eta: x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * sigmas[i + 1] * (-2 * h * eta).expm1().neg().sqrt() * s_noise denoised_1, denoised_2 = denoised, denoised_1 h_1, h_2 = h, h_1 return x @torch.no_grad() def sample_dpmpp_3m_sde_gpu(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None): sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max() noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=extra_args.get("seed", None), cpu=False) if noise_sampler is None else noise_sampler return sample_dpmpp_3m_sde(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, eta=eta, s_noise=s_noise, noise_sampler=noise_sampler) @torch.no_grad() def sample_dpmpp_2m_sde_gpu(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, solver_type='midpoint'): sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max() noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=extra_args.get("seed", None), cpu=False) if noise_sampler is None else noise_sampler return sample_dpmpp_2m_sde(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, eta=eta, s_noise=s_noise, noise_sampler=noise_sampler, solver_type=solver_type) @torch.no_grad() def sample_dpmpp_sde_gpu(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, r=1 / 2): sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max() noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=extra_args.get("seed", None), cpu=False) if noise_sampler is None else noise_sampler return sample_dpmpp_sde(model, x, sigmas, extra_args=extra_args, callback=callback, disable=disable, eta=eta, s_noise=s_noise, noise_sampler=noise_sampler, r=r) def DDPMSampler_step(x, sigma, sigma_prev, noise, noise_sampler): alpha_cumprod = 1 / ((sigma * sigma) + 1) alpha_cumprod_prev = 1 / ((sigma_prev * sigma_prev) + 1) alpha = (alpha_cumprod / alpha_cumprod_prev) mu = (1.0 / alpha).sqrt() * (x - (1 - alpha) * noise / (1 - alpha_cumprod).sqrt()) if sigma_prev > 0: mu += ((1 - alpha) * (1. - alpha_cumprod_prev) / (1. - alpha_cumprod)).sqrt() * noise_sampler(sigma, sigma_prev) return mu def generic_step_sampler(model, x, sigmas, extra_args=None, callback=None, disable=None, noise_sampler=None, step_function=None): extra_args = {} if extra_args is None else extra_args noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler s_in = x.new_ones([x.shape[0]]) for i in trange(len(sigmas) - 1, disable=disable): denoised = model(x, sigmas[i] * s_in, **extra_args) if callback is not None: callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) x = step_function(x / torch.sqrt(1.0 + sigmas[i] ** 2.0), sigmas[i], sigmas[i + 1], (x - denoised) / sigmas[i], noise_sampler) if sigmas[i + 1] != 0: x *= torch.sqrt(1.0 + sigmas[i + 1] ** 2.0) return x @torch.no_grad() def sample_ddpm(model, x, sigmas, extra_args=None, callback=None, disable=None, noise_sampler=None): return generic_step_sampler(model, x, sigmas, extra_args, callback, disable, noise_sampler, DDPMSampler_step) @torch.no_grad() def sample_lcm(model, x, sigmas, extra_args=None, callback=None, disable=None, noise_sampler=None): extra_args = {} if extra_args is None else extra_args noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler s_in = x.new_ones([x.shape[0]]) for i in trange(len(sigmas) - 1, disable=disable): denoised = model(x, sigmas[i] * s_in, **extra_args) if callback is not None: callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) x = denoised if sigmas[i + 1] > 0: x += sigmas[i + 1] * noise_sampler(sigmas[i], sigmas[i + 1]) return x @torch.no_grad() def sample_heunpp2(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0., s_tmin=0., s_tmax=float('inf'), s_noise=1.): # From MIT licensed: https://github.com/Carzit/sd-webui-samplers-scheduler/ extra_args = {} if extra_args is None else extra_args s_in = x.new_ones([x.shape[0]]) s_end = sigmas[-1] for i in trange(len(sigmas) - 1, disable=disable): gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0. eps = torch.randn_like(x) * s_noise sigma_hat = sigmas[i] * (gamma + 1) if gamma > 0: x = x + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5 denoised = model(x, sigma_hat * s_in, **extra_args) d = to_d(x, sigma_hat, denoised) if callback is not None: callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised}) dt = sigmas[i + 1] - sigma_hat if sigmas[i + 1] == s_end: # Euler method x = x + d * dt elif sigmas[i + 2] == s_end: # Heun's method x_2 = x + d * dt denoised_2 = model(x_2, sigmas[i + 1] * s_in, **extra_args) d_2 = to_d(x_2, sigmas[i + 1], denoised_2) w = 2 * sigmas[0] w2 = sigmas[i+1]/w w1 = 1 - w2 d_prime = d * w1 + d_2 * w2 x = x + d_prime * dt else: # Heun++ x_2 = x + d * dt denoised_2 = model(x_2, sigmas[i + 1] * s_in, **extra_args) d_2 = to_d(x_2, sigmas[i + 1], denoised_2) dt_2 = sigmas[i + 2] - sigmas[i + 1] x_3 = x_2 + d_2 * dt_2 denoised_3 = model(x_3, sigmas[i + 2] * s_in, **extra_args) d_3 = to_d(x_3, sigmas[i + 2], denoised_3) w = 3 * sigmas[0] w2 = sigmas[i + 1] / w w3 = sigmas[i + 2] / w w1 = 1 - w2 - w3 d_prime = w1 * d + w2 * d_2 + w3 * d_3 x = x + d_prime * dt return x @torch.no_grad() def sample_tcd(model, x, sigmas, extra_args=None, callback=None, disable=None, noise_sampler=None, eta=0.3): extra_args = {} if extra_args is None else extra_args noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler s_in = x.new_ones([x.shape[0]]) model_sampling = model.inner_model.inner_model.model_sampling timesteps_s = torch.floor((1 - eta) * model_sampling.timestep(sigmas)).to(dtype=torch.long).detach().cpu() timesteps_s[-1] = 0 alpha_prod_s = model_sampling.alphas_cumprod[timesteps_s] beta_prod_s = 1 - alpha_prod_s for i in trange(len(sigmas) - 1, disable=disable): denoised = model(x, sigmas[i] * s_in, **extra_args) # predicted_original_sample eps = (x - denoised) / sigmas[i] denoised = alpha_prod_s[i + 1].sqrt() * denoised + beta_prod_s[i + 1].sqrt() * eps if callback is not None: callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigmas[i], "denoised": denoised}) x = denoised if eta > 0 and sigmas[i + 1] > 0: noise = noise_sampler(sigmas[i], sigmas[i + 1]) x = x / alpha_prod_s[i+1].sqrt() + noise * (sigmas[i+1]**2 + 1 - 1/alpha_prod_s[i+1]).sqrt() else: x *= torch.sqrt(1.0 + sigmas[i + 1] ** 2) return x @torch.no_grad() def sample_restart(model, x, sigmas, extra_args=None, callback=None, disable=None, s_noise=1., restart_list=None): extra_args = {} if extra_args is None else extra_args s_in = x.new_ones([x.shape[0]]) step_id = 0 def heun_step(x, old_sigma, new_sigma, second_order=True): nonlocal step_id denoised = model(x, old_sigma * s_in, **extra_args) d = to_d(x, old_sigma, denoised) if callback is not None: callback({'x': x, 'i': step_id, 'sigma': new_sigma, 'sigma_hat': old_sigma, 'denoised': denoised}) dt = new_sigma - old_sigma if new_sigma == 0 or not second_order: # Euler method x = x + d * dt else: # Heun's method x_2 = x + d * dt denoised_2 = model(x_2, new_sigma * s_in, **extra_args) d_2 = to_d(x_2, new_sigma, denoised_2) d_prime = (d + d_2) / 2 x = x + d_prime * dt step_id += 1 return x steps = sigmas.shape[0] - 1 if restart_list is None: if steps >= 20: restart_steps = 9 restart_times = 1 if steps >= 36: restart_steps = steps // 4 restart_times = 2 sigmas = get_sigmas_karras(steps - restart_steps * restart_times, sigmas[-2].item(), sigmas[0].item(), device=sigmas.device) restart_list = {0.1: [restart_steps + 1, restart_times, 2]} else: restart_list = {} restart_list = {int(torch.argmin(abs(sigmas - key), dim=0)): value for key, value in restart_list.items()} step_list = [] for i in range(len(sigmas) - 1): step_list.append((sigmas[i], sigmas[i + 1])) if i + 1 in restart_list: restart_steps, restart_times, restart_max = restart_list[i + 1] min_idx = i + 1 max_idx = int(torch.argmin(abs(sigmas - restart_max), dim=0)) if max_idx < min_idx: sigma_restart = get_sigmas_karras(restart_steps, sigmas[min_idx].item(), sigmas[max_idx].item(), device=sigmas.device)[:-1] while restart_times > 0: restart_times -= 1 step_list.extend(zip(sigma_restart[:-1], sigma_restart[1:])) last_sigma = None for old_sigma, new_sigma in tqdm(step_list, disable=disable): if last_sigma is None: last_sigma = old_sigma elif last_sigma < old_sigma: x = x + torch.randn_like(x) * s_noise * (old_sigma ** 2 - last_sigma ** 2) ** 0.5 x = heun_step(x, old_sigma, new_sigma) last_sigma = new_sigma return x
--- +++ @@ -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 @@ def get_sigmas_exponential(n, sigma_min, sigma_max, device='cpu'): + """Constructs an exponential noise schedule.""" sigmas = torch.linspace(math.log(sigma_max), math.log(sigma_min), n, device=device).exp() return append_zero(sigmas) def get_sigmas_polyexponential(n, sigma_min, sigma_max, rho=1., device='cpu'): + """Constructs an polynomial in log sigma noise schedule.""" ramp = torch.linspace(1, 0, n, device=device) ** rho sigmas = torch.exp(ramp * (math.log(sigma_max) - math.log(sigma_min)) + math.log(sigma_min)) return append_zero(sigmas) def get_sigmas_vp(n, beta_d=19.9, beta_min=0.1, eps_s=1e-3, device='cpu'): + """Constructs a continuous VP noise schedule.""" t = torch.linspace(1, eps_s, n, device=device) sigmas = torch.sqrt(torch.exp(beta_d * t ** 2 / 2 + beta_min * t) - 1) return append_zero(sigmas) def to_d(x, sigma, denoised): + """Converts a denoiser output to a Karras ODE derivative.""" return (x - denoised) / utils.append_dims(sigma, x.ndim) def get_ancestral_step(sigma_from, sigma_to, eta=1.): + """Calculates the noise level (sigma_down) to step down to and the amount + of noise to add (sigma_up) when doing an ancestral sampling step.""" if not eta: return sigma_to, 0. sigma_up = min(sigma_to, eta * (sigma_to ** 2 * (sigma_from ** 2 - sigma_to ** 2) / sigma_from ** 2) ** 0.5) @@ -55,6 +62,7 @@ class BatchedBrownianTree: + """A wrapper around torchsde.BrownianTree that enables batches of entropy.""" def __init__(self, x, t0, t1, seed=None, **kwargs): self.cpu_tree = True @@ -91,6 +99,19 @@ class BrownianTreeNoiseSampler: + """A noise sampler backed by a torchsde.BrownianTree. + + Args: + x (Tensor): The tensor whose shape, device and dtype to use to generate + random samples. + sigma_min (float): The low end of the valid interval. + sigma_max (float): The high end of the valid interval. + seed (int or List[int]): The random seed. If a list of seeds is + supplied instead of a single integer, then the noise sampler will + use one BrownianTree per batch item, each with its own seed. + transform (callable): A function that maps sigma to the sampler's + internal timestep. + """ def __init__(self, x, sigma_min, sigma_max, seed=None, transform=lambda x: x, cpu=False): self.transform = transform @@ -104,6 +125,7 @@ @torch.no_grad() def sample_euler(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0., s_tmin=0., s_tmax=float('inf'), s_noise=1.): + """Implements Algorithm 2 (Euler steps) from Karras et al. (2022).""" extra_args = {} if extra_args is None else extra_args s_in = x.new_ones([x.shape[0]]) for i in trange(len(sigmas) - 1, disable=disable): @@ -124,6 +146,7 @@ @torch.no_grad() def sample_euler_ancestral(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None): + """Ancestral sampling with Euler method steps.""" extra_args = {} if extra_args is None else extra_args noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler s_in = x.new_ones([x.shape[0]]) @@ -143,6 +166,7 @@ @torch.no_grad() def sample_heun(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0., s_tmin=0., s_tmax=float('inf'), s_noise=1.): + """Implements Algorithm 2 (Heun steps) from Karras et al. (2022).""" extra_args = {} if extra_args is None else extra_args s_in = x.new_ones([x.shape[0]]) for i in trange(len(sigmas) - 1, disable=disable): @@ -171,6 +195,7 @@ @torch.no_grad() def sample_dpm_2(model, x, sigmas, extra_args=None, callback=None, disable=None, s_churn=0., s_tmin=0., s_tmax=float('inf'), s_noise=1.): + """A sampler inspired by DPM-Solver-2 and Algorithm 2 from Karras et al. (2022).""" extra_args = {} if extra_args is None else extra_args s_in = x.new_ones([x.shape[0]]) for i in trange(len(sigmas) - 1, disable=disable): @@ -201,6 +226,7 @@ @torch.no_grad() def sample_dpm_2_ancestral(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None): + """Ancestral sampling with DPM-Solver second-order steps.""" extra_args = {} if extra_args is None else extra_args noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler s_in = x.new_ones([x.shape[0]]) @@ -261,6 +287,7 @@ class PIDStepSizeController: + """A PID controller for ODE adaptive step size control.""" def __init__(self, h, pcoeff, icoeff, dcoeff, order=1, accept_safety=0.81, eps=1e-8): self.h = h self.b1 = (pcoeff + icoeff + dcoeff) / order @@ -289,6 +316,7 @@ class DPMSolver(nn.Module): + """DPM-Solver. See https://arxiv.org/abs/2206.00927.""" def __init__(self, model, extra_args=None, eps_callback=None, info_callback=None): super().__init__() @@ -437,6 +465,7 @@ @torch.no_grad() def sample_dpm_fast(model, x, sigma_min, sigma_max, n, extra_args=None, callback=None, disable=None, eta=0., s_noise=1., noise_sampler=None): + """DPM-Solver-Fast (fixed step size). See https://arxiv.org/abs/2206.00927.""" if sigma_min <= 0 or sigma_max <= 0: raise ValueError('sigma_min and sigma_max must not be 0') with tqdm(total=n, disable=disable) as pbar: @@ -448,6 +477,7 @@ @torch.no_grad() def sample_dpm_adaptive(model, x, sigma_min, sigma_max, extra_args=None, callback=None, disable=None, order=3, rtol=0.05, atol=0.0078, h_init=0.05, pcoeff=0., icoeff=1., dcoeff=0., accept_safety=0.81, eta=0., s_noise=1., noise_sampler=None, return_info=False): + """DPM-Solver-12 and 23 (adaptive step size). See https://arxiv.org/abs/2206.00927.""" if sigma_min <= 0 or sigma_max <= 0: raise ValueError('sigma_min and sigma_max must not be 0') with tqdm(disable=disable) as pbar: @@ -462,6 +492,7 @@ @torch.no_grad() def sample_dpmpp_2s_ancestral(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None): + """Ancestral sampling with DPM-Solver++(2S) second-order steps.""" extra_args = {} if extra_args is None else extra_args noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler s_in = x.new_ones([x.shape[0]]) @@ -495,6 +526,7 @@ @torch.no_grad() def sample_dpmpp_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, r=1 / 2): + """DPM-Solver++ (stochastic).""" sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max() seed = extra_args.get("seed", None) noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=seed, cpu=True) if noise_sampler is None else noise_sampler @@ -537,6 +569,7 @@ @torch.no_grad() def sample_dpmpp_2m(model, x, sigmas, extra_args=None, callback=None, disable=None): + """DPM-Solver++(2M).""" extra_args = {} if extra_args is None else extra_args s_in = x.new_ones([x.shape[0]]) sigma_fn = lambda t: t.neg().exp() @@ -561,6 +594,7 @@ @torch.no_grad() def sample_dpmpp_2m_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, solver_type='midpoint'): + """DPM-Solver++(2M) SDE.""" if solver_type not in {'heun', 'midpoint'}: raise ValueError('solver_type must be \'heun\' or \'midpoint\'') @@ -606,6 +640,7 @@ @torch.no_grad() def sample_dpmpp_3m_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None): + """DPM-Solver++(3M) SDE.""" seed = extra_args.get("seed", None) sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max() @@ -805,6 +840,10 @@ @torch.no_grad() def sample_restart(model, x, sigmas, extra_args=None, callback=None, disable=None, s_noise=1., restart_list=None): + """Implements restart sampling in Restart Sampling for Improving Generative Processes (2023) + Restart_list format: {min_sigma: [ restart_steps, restart_times, max_sigma]} + If restart_list is None: will choose restart_list automatically, otherwise will use the given restart_list + """ extra_args = {} if extra_args is None else extra_args s_in = x.new_ones([x.shape[0]]) step_id = 0
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 == 'bn': self.norm = nn.BatchNorm2d(channels, affine=True) elif norm_type == 'in': self.norm = nn.InstanceNorm2d(channels, affine=False) elif norm_type == 'gn': self.norm = nn.GroupNorm(32, channels, affine=True) elif norm_type == 'pixel': self.norm = lambda x: F.normalize(x, p=2, dim=1) elif norm_type == 'layer': self.norm = nn.LayerNorm(normalize_shape) elif norm_type == 'none': self.norm = lambda x: x * 1.0 else: assert 1 == 0, f'Norm type {norm_type} not support.' def forward(self, x, ref=None): if self.norm_type == 'spade': return self.norm(x, ref) else: return self.norm(x) class ReluLayer(nn.Module): def __init__(self, channels, relu_type='relu'): super(ReluLayer, self).__init__() relu_type = relu_type.lower() if relu_type == 'relu': self.func = nn.ReLU(True) elif relu_type == 'leakyrelu': self.func = nn.LeakyReLU(0.2, inplace=True) elif relu_type == 'prelu': self.func = nn.PReLU(channels) elif relu_type == 'selu': self.func = nn.SELU(True) elif relu_type == 'none': self.func = lambda x: x * 1.0 else: assert 1 == 0, f'Relu type {relu_type} not support.' def forward(self, x): return self.func(x) class ConvLayer(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, scale='none', norm_type='none', relu_type='none', use_pad=True, bias=True): super(ConvLayer, self).__init__() self.use_pad = use_pad self.norm_type = norm_type if norm_type in ['bn']: bias = False stride = 2 if scale == 'down' else 1 self.scale_func = lambda x: x if scale == 'up': self.scale_func = lambda x: nn.functional.interpolate(x, scale_factor=2, mode='nearest') self.reflection_pad = nn.ReflectionPad2d(int(np.ceil((kernel_size - 1.) / 2))) self.conv2d = nn.Conv2d(in_channels, out_channels, kernel_size, stride, bias=bias) self.relu = ReluLayer(out_channels, relu_type) self.norm = NormLayer(out_channels, norm_type=norm_type) def forward(self, x): out = self.scale_func(x) if self.use_pad: out = self.reflection_pad(out) out = self.conv2d(out) out = self.norm(out) out = self.relu(out) return out class ResidualBlock(nn.Module): def __init__(self, c_in, c_out, relu_type='prelu', norm_type='bn', scale='none'): super(ResidualBlock, self).__init__() if scale == 'none' and c_in == c_out: self.shortcut_func = lambda x: x else: self.shortcut_func = ConvLayer(c_in, c_out, 3, scale) scale_config_dict = {'down': ['none', 'down'], 'up': ['up', 'none'], 'none': ['none', 'none']} scale_conf = scale_config_dict[scale] self.conv1 = ConvLayer(c_in, c_out, 3, scale_conf[0], norm_type=norm_type, relu_type=relu_type) self.conv2 = ConvLayer(c_out, c_out, 3, scale_conf[1], norm_type=norm_type, relu_type='none') def forward(self, x): identity = self.shortcut_func(x) res = self.conv1(x) res = self.conv2(res) return identity + res class ParseNet(nn.Module): def __init__(self, in_size=128, out_size=128, min_feat_size=32, base_ch=64, parsing_ch=19, res_depth=10, relu_type='LeakyReLU', norm_type='bn', ch_range=[32, 256]): super().__init__() self.res_depth = res_depth act_args = {'norm_type': norm_type, 'relu_type': relu_type} min_ch, max_ch = ch_range ch_clip = lambda x: max(min_ch, min(x, max_ch)) # noqa: E731 min_feat_size = min(in_size, min_feat_size) down_steps = int(np.log2(in_size // min_feat_size)) up_steps = int(np.log2(out_size // min_feat_size)) # =============== define encoder-body-decoder ==================== self.encoder = [] self.encoder.append(ConvLayer(3, base_ch, 3, 1)) head_ch = base_ch for i in range(down_steps): cin, cout = ch_clip(head_ch), ch_clip(head_ch * 2) self.encoder.append(ResidualBlock(cin, cout, scale='down', **act_args)) head_ch = head_ch * 2 self.body = [] for i in range(res_depth): self.body.append(ResidualBlock(ch_clip(head_ch), ch_clip(head_ch), **act_args)) self.decoder = [] for i in range(up_steps): cin, cout = ch_clip(head_ch), ch_clip(head_ch // 2) self.decoder.append(ResidualBlock(cin, cout, scale='up', **act_args)) head_ch = head_ch // 2 self.encoder = nn.Sequential(*self.encoder) self.body = nn.Sequential(*self.body) self.decoder = nn.Sequential(*self.decoder) self.out_img_conv = ConvLayer(ch_clip(head_ch), 3) self.out_mask_conv = ConvLayer(ch_clip(head_ch), parsing_ch) def forward(self, x): feat = self.encoder(x) x = feat + self.body(feat) x = self.decoder(x) out_img = self.out_img_conv(x) out_mask = self.out_mask_conv(x) return out_mask, out_img
--- +++ @@ -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. + input_size: input shape without batch size, for layer norm. + """ def __init__(self, channels, normalize_shape=None, norm_type='bn'): super(NormLayer, self).__init__() @@ -32,6 +40,16 @@ class ReluLayer(nn.Module): + """Relu Layer. + + Args: + relu type: type of relu layer, candidates are + - ReLU + - LeakyReLU: default relu slope 0.2 + - PRelu + - SELU + - none: direct pass + """ def __init__(self, channels, relu_type='relu'): super(ReluLayer, self).__init__() @@ -93,6 +111,9 @@ class ResidualBlock(nn.Module): + """ + Residual block recommended in: http://torch.ch/blog/2016/02/04/resnets.html + """ def __init__(self, c_in, c_out, relu_type='prelu', norm_type='bn', scale='none'): super(ResidualBlock, self).__init__() @@ -170,4 +191,4 @@ x = self.decoder(x) out_img = self.out_img_conv(x) out_mask = self.out_mask_conv(x) - return out_mask, out_img+ return out_mask, out_img
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 = special_tokens.get("end", None) pad_token = special_tokens.get("pad") output = [] if start_token is not None: output.append(start_token) if end_token is not None: output.append(end_token) output += [pad_token] * (length - len(output)) return output class ClipTokenWeightEncoder: def encode_token_weights(self, token_weight_pairs): to_encode = list() max_token_len = 0 has_weights = False for x in token_weight_pairs: tokens = list(map(lambda a: a[0], x)) max_token_len = max(len(tokens), max_token_len) has_weights = has_weights or not all(map(lambda a: a[1] == 1.0, x)) to_encode.append(tokens) sections = len(to_encode) if has_weights or sections == 0: to_encode.append(gen_empty_tokens(self.special_tokens, max_token_len)) out, pooled = self.encode(to_encode) if pooled is not None: first_pooled = pooled[0:1].to(model_management.intermediate_device()) else: first_pooled = pooled output = [] for k in range(0, sections): z = out[k:k+1] if has_weights: z_empty = out[-1] for i in range(len(z)): for j in range(len(z[i])): weight = token_weight_pairs[k][j][1] if weight != 1.0: z[i][j] = (z[i][j] - z_empty[j]) * weight + z_empty[j] output.append(z) if (len(output) == 0): return out[-1:].to(model_management.intermediate_device()), first_pooled return torch.cat(output, dim=-2).to(model_management.intermediate_device()), first_pooled class SDClipModel(torch.nn.Module, ClipTokenWeightEncoder): LAYERS = [ "last", "pooled", "hidden" ] def __init__(self, version="openai/clip-vit-large-patch14", device="cpu", max_length=77, freeze=True, layer="last", layer_idx=None, textmodel_json_config=None, dtype=None, model_class=ldm_patched.modules.clip_model.CLIPTextModel, special_tokens={"start": 49406, "end": 49407, "pad": 49407}, layer_norm_hidden_state=True): # clip-vit-base-patch32 super().__init__() assert layer in self.LAYERS if textmodel_json_config is None: textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "sd1_clip_config.json") with open(textmodel_json_config) as f: config = json.load(f) self.transformer = model_class(config, dtype, device, ldm_patched.modules.ops.manual_cast) self.num_layers = self.transformer.num_layers self.max_length = max_length if freeze: self.freeze() self.layer = layer self.layer_idx = None self.special_tokens = special_tokens self.text_projection = torch.nn.Parameter(torch.eye(self.transformer.get_input_embeddings().weight.shape[1])) self.logit_scale = torch.nn.Parameter(torch.tensor(4.6055)) self.enable_attention_masks = False self.layer_norm_hidden_state = layer_norm_hidden_state if layer == "hidden": assert layer_idx is not None assert abs(layer_idx) < self.num_layers self.clip_layer(layer_idx) self.layer_default = (self.layer, self.layer_idx) def freeze(self): self.transformer = self.transformer.eval() #self.train = disabled_train for param in self.parameters(): param.requires_grad = False def clip_layer(self, layer_idx): if abs(layer_idx) > self.num_layers: self.layer = "last" else: self.layer = "hidden" self.layer_idx = layer_idx def reset_clip_layer(self): self.layer = self.layer_default[0] self.layer_idx = self.layer_default[1] def set_up_textual_embeddings(self, tokens, current_embeds): out_tokens = [] next_new_token = token_dict_size = current_embeds.weight.shape[0] - 1 embedding_weights = [] for x in tokens: tokens_temp = [] for y in x: if isinstance(y, int): if y == token_dict_size: #EOS token y = -1 tokens_temp += [y] else: if y.shape[0] == current_embeds.weight.shape[1]: embedding_weights += [y] tokens_temp += [next_new_token] next_new_token += 1 else: print("WARNING: shape mismatch when trying to apply embedding, embedding will be ignored", y.shape[0], current_embeds.weight.shape[1]) while len(tokens_temp) < len(x): tokens_temp += [self.special_tokens["pad"]] out_tokens += [tokens_temp] n = token_dict_size if len(embedding_weights) > 0: new_embedding = torch.nn.Embedding(next_new_token + 1, current_embeds.weight.shape[1], device=current_embeds.weight.device, dtype=current_embeds.weight.dtype) new_embedding.weight[:token_dict_size] = current_embeds.weight[:-1] for x in embedding_weights: new_embedding.weight[n] = x n += 1 new_embedding.weight[n] = current_embeds.weight[-1] #EOS embedding self.transformer.set_input_embeddings(new_embedding) processed_tokens = [] for x in out_tokens: processed_tokens += [list(map(lambda a: n if a == -1 else a, x))] #The EOS token should always be the largest one return processed_tokens def forward(self, tokens): backup_embeds = self.transformer.get_input_embeddings() device = backup_embeds.weight.device tokens = self.set_up_textual_embeddings(tokens, backup_embeds) tokens = torch.LongTensor(tokens).to(device) attention_mask = None if self.enable_attention_masks: attention_mask = torch.zeros_like(tokens) max_token = self.transformer.get_input_embeddings().weight.shape[0] - 1 for x in range(attention_mask.shape[0]): for y in range(attention_mask.shape[1]): attention_mask[x, y] = 1 if tokens[x, y] == max_token: break outputs = self.transformer(tokens, attention_mask, intermediate_output=self.layer_idx, final_layer_norm_intermediate=self.layer_norm_hidden_state) self.transformer.set_input_embeddings(backup_embeds) if self.layer == "last": z = outputs[0] else: z = outputs[1] if outputs[2] is not None: pooled_output = outputs[2].float() else: pooled_output = None if self.text_projection is not None and pooled_output is not None: pooled_output = pooled_output.float().to(self.text_projection.device) @ self.text_projection.float() return z.float(), pooled_output def encode(self, tokens): return self(tokens) def load_sd(self, sd): if "text_projection" in sd: self.text_projection[:] = sd.pop("text_projection") if "text_projection.weight" in sd: self.text_projection[:] = sd.pop("text_projection.weight").transpose(0, 1) return self.transformer.load_state_dict(sd, strict=False) def parse_parentheses(string): result = [] current_item = "" nesting_level = 0 for char in string: if char == "(": if nesting_level == 0: if current_item: result.append(current_item) current_item = "(" else: current_item = "(" else: current_item += char nesting_level += 1 elif char == ")": nesting_level -= 1 if nesting_level == 0: result.append(current_item + ")") current_item = "" else: current_item += char else: current_item += char if current_item: result.append(current_item) return result def token_weights(string, current_weight): a = parse_parentheses(string) out = [] for x in a: weight = current_weight if len(x) >= 2 and x[-1] == ')' and x[0] == '(': x = x[1:-1] xx = x.rfind(":") weight *= 1.1 if xx > 0: try: weight = float(x[xx+1:]) x = x[:xx] except: pass out += token_weights(x, weight) else: out += [(x, current_weight)] return out def escape_important(text): text = text.replace("\\)", "\0\1") text = text.replace("\\(", "\0\2") return text def unescape_important(text): text = text.replace("\0\1", ")") text = text.replace("\0\2", "(") return text def safe_load_embed_zip(embed_path): with zipfile.ZipFile(embed_path) as myzip: names = list(filter(lambda a: "data/" in a, myzip.namelist())) names.reverse() for n in names: with myzip.open(n) as myfile: data = myfile.read() number = len(data) // 4 length_embed = 1024 #sd2.x if number < 768: continue if number % 768 == 0: length_embed = 768 #sd1.x num_embeds = number // length_embed embed = torch.frombuffer(data, dtype=torch.float) out = embed.reshape((num_embeds, length_embed)).clone() del embed return out def expand_directory_list(directories): dirs = set() for x in directories: dirs.add(x) for root, subdir, file in os.walk(x, followlinks=True): dirs.add(root) return list(dirs) def load_embed(embedding_name, embedding_directory, embedding_size, embed_key=None): if isinstance(embedding_directory, str): embedding_directory = [embedding_directory] embedding_directory = expand_directory_list(embedding_directory) valid_file = None for embed_dir in embedding_directory: embed_path = os.path.abspath(os.path.join(embed_dir, embedding_name)) embed_dir = os.path.abspath(embed_dir) try: if os.path.commonpath((embed_dir, embed_path)) != embed_dir: continue except: continue if not os.path.isfile(embed_path): extensions = ['.safetensors', '.pt', '.bin'] for x in extensions: t = embed_path + x if os.path.isfile(t): valid_file = t break else: valid_file = embed_path if valid_file is not None: break if valid_file is None: return None embed_path = valid_file embed_out = None try: if embed_path.lower().endswith(".safetensors"): import safetensors.torch embed = safetensors.torch.load_file(embed_path, device="cpu") else: if 'weights_only' in torch.load.__code__.co_varnames: try: embed = torch.load(embed_path, weights_only=True, map_location="cpu") except: embed_out = safe_load_embed_zip(embed_path) else: embed = torch.load(embed_path, map_location="cpu", weights_only=True) except Exception as e: print(traceback.format_exc()) print() print("error loading embedding, skipping loading:", embedding_name) return None if embed_out is None: if 'string_to_param' in embed: values = embed['string_to_param'].values() embed_out = next(iter(values)) elif isinstance(embed, list): out_list = [] for x in range(len(embed)): for k in embed[x]: t = embed[x][k] if t.shape[-1] != embedding_size: continue out_list.append(t.reshape(-1, t.shape[-1])) embed_out = torch.cat(out_list, dim=0) elif embed_key is not None and embed_key in embed: embed_out = embed[embed_key] else: values = embed.values() embed_out = next(iter(values)) return embed_out class SDTokenizer: def __init__(self, tokenizer_path=None, max_length=77, pad_with_end=True, embedding_directory=None, embedding_size=768, embedding_key='clip_l', tokenizer_class=CLIPTokenizer, has_start_token=True, pad_to_max_length=True): if tokenizer_path is None: tokenizer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "sd1_tokenizer") self.tokenizer = tokenizer_class.from_pretrained(tokenizer_path) self.max_length = max_length empty = self.tokenizer('')["input_ids"] if has_start_token: self.tokens_start = 1 self.start_token = empty[0] self.end_token = empty[1] else: self.tokens_start = 0 self.start_token = None self.end_token = empty[0] self.pad_with_end = pad_with_end self.pad_to_max_length = pad_to_max_length vocab = self.tokenizer.get_vocab() self.inv_vocab = {v: k for k, v in vocab.items()} self.embedding_directory = embedding_directory self.max_word_length = 8 self.embedding_identifier = "embedding:" self.embedding_size = embedding_size self.embedding_key = embedding_key def _try_get_embedding(self, embedding_name:str): embed = load_embed(embedding_name, self.embedding_directory, self.embedding_size, self.embedding_key) if embed is None: stripped = embedding_name.strip(',') if len(stripped) < len(embedding_name): embed = load_embed(stripped, self.embedding_directory, self.embedding_size, self.embedding_key) return (embed, embedding_name[len(stripped):]) return (embed, "") def tokenize_with_weights(self, text:str, return_word_ids=False): if self.pad_with_end: pad_token = self.end_token else: pad_token = 0 text = escape_important(text) parsed_weights = token_weights(text, 1.0) #tokenize words tokens = [] for weighted_segment, weight in parsed_weights: to_tokenize = unescape_important(weighted_segment).replace("\n", " ").split(' ') to_tokenize = [x for x in to_tokenize if x != ""] for word in to_tokenize: #if we find an embedding, deal with the embedding if word.startswith(self.embedding_identifier) and self.embedding_directory is not None: embedding_name = word[len(self.embedding_identifier):].strip('\n') embed, leftover = self._try_get_embedding(embedding_name) if embed is None: print(f"warning, embedding:{embedding_name} does not exist, ignoring") else: if len(embed.shape) == 1: tokens.append([(embed, weight)]) else: tokens.append([(embed[x], weight) for x in range(embed.shape[0])]) #if we accidentally have leftover text, continue parsing using leftover, else move on to next word if leftover != "": word = leftover else: continue #parse word tokens.append([(t, weight) for t in self.tokenizer(word)["input_ids"][self.tokens_start:-1]]) #reshape token array to CLIP input size batched_tokens = [] batch = [] if self.start_token is not None: batch.append((self.start_token, 1.0, 0)) batched_tokens.append(batch) for i, t_group in enumerate(tokens): #determine if we're going to try and keep the tokens in a single batch is_large = len(t_group) >= self.max_word_length while len(t_group) > 0: if len(t_group) + len(batch) > self.max_length - 1: remaining_length = self.max_length - len(batch) - 1 #break word in two and add end token if is_large: batch.extend([(t,w,i+1) for t,w in t_group[:remaining_length]]) batch.append((self.end_token, 1.0, 0)) t_group = t_group[remaining_length:] #add end token and pad else: batch.append((self.end_token, 1.0, 0)) if self.pad_to_max_length: batch.extend([(pad_token, 1.0, 0)] * (remaining_length)) #start new batch batch = [] if self.start_token is not None: batch.append((self.start_token, 1.0, 0)) batched_tokens.append(batch) else: batch.extend([(t,w,i+1) for t,w in t_group]) t_group = [] #fill last batch batch.append((self.end_token, 1.0, 0)) if self.pad_to_max_length: batch.extend([(pad_token, 1.0, 0)] * (self.max_length - len(batch))) if not return_word_ids: batched_tokens = [[(t, w) for t, w,_ in x] for x in batched_tokens] return batched_tokens def untokenize(self, token_weight_pair): return list(map(lambda a: (a, self.inv_vocab[a[0]]), token_weight_pair)) class SD1Tokenizer: def __init__(self, embedding_directory=None, clip_name="l", tokenizer=SDTokenizer): self.clip_name = clip_name self.clip = "clip_{}".format(self.clip_name) setattr(self, self.clip, tokenizer(embedding_directory=embedding_directory)) def tokenize_with_weights(self, text:str, return_word_ids=False): out = {} out[self.clip_name] = getattr(self, self.clip).tokenize_with_weights(text, return_word_ids) return out def untokenize(self, token_weight_pair): return getattr(self, self.clip).untokenize(token_weight_pair) class SD1ClipModel(torch.nn.Module): def __init__(self, device="cpu", dtype=None, clip_name="l", clip_model=SDClipModel, **kwargs): super().__init__() self.clip_name = clip_name self.clip = "clip_{}".format(self.clip_name) setattr(self, self.clip, clip_model(device=device, dtype=dtype, **kwargs)) def clip_layer(self, layer_idx): getattr(self, self.clip).clip_layer(layer_idx) def reset_clip_layer(self): getattr(self, self.clip).reset_clip_layer() def encode_token_weights(self, token_weight_pairs): token_weight_pairs = token_weight_pairs[self.clip_name] out, pooled = getattr(self, self.clip).encode_token_weights(token_weight_pairs) return out, pooled def load_sd(self, sd): return getattr(self, self.clip).load_sd(sd)
--- +++ @@ -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,6 +381,10 @@ self.embedding_key = embedding_key def _try_get_embedding(self, embedding_name:str): + ''' + Takes a potential embedding name and tries to retrieve it. + Returns a Tuple consisting of the embedding and any leftover string, embedding can be None. + ''' embed = load_embed(embedding_name, self.embedding_directory, self.embedding_size, self.embedding_key) if embed is None: stripped = embedding_name.strip(',') @@ -390,6 +395,12 @@ def tokenize_with_weights(self, text:str, return_word_ids=False): + ''' + Takes a prompt and converts it to a list of (token, weight, word id) elements. + Tokens can both be integer tokens and pre computed CLIP tensors. + Word id values are unique per word and embedding, where the id 0 is reserved for non word tokens. + Returned list has the dimensions NxM where M is the input size of CLIP + ''' if self.pad_with_end: pad_token = self.end_token else: @@ -504,4 +515,4 @@ return out, pooled def load_sd(self, sd): - return getattr(self, self.clip).load_sd(sd)+ return getattr(self, self.clip).load_sd(sd)
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): txt = Image.new("RGB", wh, color="white") draw = ImageDraw.Draw(txt) font = ImageFont.truetype('data/DejaVuSans.ttf', size=size) nc = int(40 * (wh[0] / 256)) lines = "\n".join(xc[bi][start:start + nc] for start in range(0, len(xc[bi]), nc)) try: draw.text((0, 0), lines, fill="black", font=font) except UnicodeEncodeError: print("Cant encode string for logging. Skipping.") txt = np.array(txt).transpose(2, 0, 1) / 127.5 - 1.0 txts.append(txt) txts = np.stack(txts) txts = torch.tensor(txts) return txts def ismap(x): if not isinstance(x, torch.Tensor): return False return (len(x.shape) == 4) and (x.shape[1] > 3) def isimage(x): if not isinstance(x,torch.Tensor): return False return (len(x.shape) == 4) and (x.shape[1] == 3 or x.shape[1] == 1) def exists(x): return x is not None def default(val, d): if exists(val): return val return d() if isfunction(d) else d def mean_flat(tensor): return tensor.mean(dim=list(range(1, len(tensor.shape)))) def count_params(model, verbose=False): total_params = sum(p.numel() for p in model.parameters()) if verbose: print(f"{model.__class__.__name__} has {total_params*1.e-6:.2f} M params.") return total_params def instantiate_from_config(config): if not "target" in config: if config == '__is_first_stage__': return None elif config == "__is_unconditional__": return None raise KeyError("Expected key `target` to instantiate.") return get_obj_from_str(config["target"])(**config.get("params", dict())) def get_obj_from_str(string, reload=False): module, cls = string.rsplit(".", 1) if reload: module_imp = importlib.import_module(module) importlib.reload(module_imp) return getattr(importlib.import_module(module, package=None), cls) class AdamWwithEMAandWings(optim.Optimizer): # credit to https://gist.github.com/crowsonkb/65f7265353f403714fce3b2595e0b298 def __init__(self, params, lr=1.e-3, betas=(0.9, 0.999), eps=1.e-8, # TODO: check hyperparameters before using weight_decay=1.e-2, amsgrad=False, ema_decay=0.9999, # ema decay to match previous code ema_power=1., param_names=()): if not 0.0 <= lr: raise ValueError("Invalid learning rate: {}".format(lr)) if not 0.0 <= eps: raise ValueError("Invalid epsilon value: {}".format(eps)) if not 0.0 <= betas[0] < 1.0: raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0])) if not 0.0 <= betas[1] < 1.0: raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1])) if not 0.0 <= weight_decay: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) if not 0.0 <= ema_decay <= 1.0: raise ValueError("Invalid ema_decay value: {}".format(ema_decay)) defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, amsgrad=amsgrad, ema_decay=ema_decay, ema_power=ema_power, param_names=param_names) super().__init__(params, defaults) def __setstate__(self, state): super().__setstate__(state) for group in self.param_groups: group.setdefault('amsgrad', False) @torch.no_grad() def step(self, closure=None): loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: params_with_grad = [] grads = [] exp_avgs = [] exp_avg_sqs = [] ema_params_with_grad = [] state_sums = [] max_exp_avg_sqs = [] state_steps = [] amsgrad = group['amsgrad'] beta1, beta2 = group['betas'] ema_decay = group['ema_decay'] ema_power = group['ema_power'] for p in group['params']: if p.grad is None: continue params_with_grad.append(p) if p.grad.is_sparse: raise RuntimeError('AdamW does not support sparse gradients') grads.append(p.grad) state = self.state[p] # State initialization if len(state) == 0: state['step'] = 0 # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p, memory_format=torch.preserve_format) # Exponential moving average of squared gradient values state['exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format) if amsgrad: # Maintains max of all exp. moving avg. of sq. grad. values state['max_exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format) # Exponential moving average of parameter values state['param_exp_avg'] = p.detach().float().clone() exp_avgs.append(state['exp_avg']) exp_avg_sqs.append(state['exp_avg_sq']) ema_params_with_grad.append(state['param_exp_avg']) if amsgrad: max_exp_avg_sqs.append(state['max_exp_avg_sq']) # update the steps for each param group update state['step'] += 1 # record the step after step update state_steps.append(state['step']) optim._functional.adamw(params_with_grad, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, amsgrad=amsgrad, beta1=beta1, beta2=beta2, lr=group['lr'], weight_decay=group['weight_decay'], eps=group['eps'], maximize=False) cur_ema_decay = min(ema_decay, 1 - state['step'] ** -ema_power) for param, ema_param in zip(params_with_grad, ema_params_with_grad): ema_param.mul_(cur_ema_decay).add_(param.float(), alpha=1 - cur_ema_decay) return loss
--- +++ @@ -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 +92,7 @@ def __init__(self, params, lr=1.e-3, betas=(0.9, 0.999), eps=1.e-8, # TODO: check hyperparameters before using weight_decay=1.e-2, amsgrad=False, ema_decay=0.9999, # ema decay to match previous code ema_power=1., param_names=()): + """AdamW that saves EMA versions of the parameters.""" if not 0.0 <= lr: raise ValueError("Invalid learning rate: {}".format(lr)) if not 0.0 <= eps: @@ -112,6 +117,11 @@ @torch.no_grad() def step(self, closure=None): + """Performs a single optimization step. + Args: + closure (callable, optional): A closure that reevaluates the model + and returns the loss. + """ loss = None if closure is not None: with torch.enable_grad():
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_size=(1, 1), bias=False), nn.GELU(), nn.Conv2d(channel // reduction, channel, kernel_size=(1, 1), bias=False), # nn.Sigmoid() ) def forward(self, x): y = self.fc(self.gap(x)) return x * y.expand_as(x) class Simple_CA_layer(nn.Module): def __init__(self, channel): super(Simple_CA_layer, self).__init__() self.gap = nn.AdaptiveAvgPool2d(1) self.fc = nn.Conv2d( in_channels=channel, out_channels=channel, kernel_size=1, padding=0, stride=1, groups=1, bias=True, ) def forward(self, x): return x * self.fc(self.gap(x)) class ECA_layer(nn.Module): def __init__(self, channel): super(ECA_layer, self).__init__() b = 1 gamma = 2 k_size = int(abs(math.log(channel, 2) + b) / gamma) k_size = k_size if k_size % 2 else k_size + 1 self.avg_pool = nn.AdaptiveAvgPool2d(1) self.conv = nn.Conv1d( 1, 1, kernel_size=k_size, padding=(k_size - 1) // 2, bias=False ) # self.sigmoid = nn.Sigmoid() def forward(self, x): # x: input features with shape [b, c, h, w] # b, c, h, w = x.size() # feature descriptor on the global spatial information y = self.avg_pool(x) # Two different branches of ECA module y = self.conv(y.squeeze(-1).transpose(-1, -2)).transpose(-1, -2).unsqueeze(-1) # Multi-scale information fusion # y = self.sigmoid(y) return x * y.expand_as(x) class ECA_MaxPool_layer(nn.Module): def __init__(self, channel): super(ECA_MaxPool_layer, self).__init__() b = 1 gamma = 2 k_size = int(abs(math.log(channel, 2) + b) / gamma) k_size = k_size if k_size % 2 else k_size + 1 self.max_pool = nn.AdaptiveMaxPool2d(1) self.conv = nn.Conv1d( 1, 1, kernel_size=k_size, padding=(k_size - 1) // 2, bias=False ) # self.sigmoid = nn.Sigmoid() def forward(self, x): # x: input features with shape [b, c, h, w] # b, c, h, w = x.size() # feature descriptor on the global spatial information y = self.max_pool(x) # Two different branches of ECA module y = self.conv(y.squeeze(-1).transpose(-1, -2)).transpose(-1, -2).unsqueeze(-1) # Multi-scale information fusion # y = self.sigmoid(y) return x * y.expand_as(x)
--- +++ @@ -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 @@ class ECA_MaxPool_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_MaxPool_layer, self).__init__() @@ -97,4 +107,4 @@ # Multi-scale information fusion # y = self.sigmoid(y) - return x * y.expand_as(x)+ return x * y.expand_as(x)
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, Radu and Van Gool, Luc # ----------------------------------------------------------------------------------- import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from einops.layers.torch import Rearrange from .timm.drop import DropPath from .timm.weight_init import trunc_normal_ # Borrowed from https://github.com/cszn/SCUNet/blob/main/models/network_scunet.py class WMSA(nn.Module): def __init__(self, input_dim, output_dim, head_dim, window_size, type): super(WMSA, self).__init__() self.input_dim = input_dim self.output_dim = output_dim self.head_dim = head_dim self.scale = self.head_dim**-0.5 self.n_heads = input_dim // head_dim self.window_size = window_size self.type = type self.embedding_layer = nn.Linear(self.input_dim, 3 * self.input_dim, bias=True) self.relative_position_params = nn.Parameter( torch.zeros((2 * window_size - 1) * (2 * window_size - 1), self.n_heads) ) # TODO recover # self.relative_position_params = nn.Parameter(torch.zeros(self.n_heads, 2 * window_size - 1, 2 * window_size -1)) self.relative_position_params = nn.Parameter( torch.zeros((2 * window_size - 1) * (2 * window_size - 1), self.n_heads) ) self.linear = nn.Linear(self.input_dim, self.output_dim) trunc_normal_(self.relative_position_params, std=0.02) self.relative_position_params = torch.nn.Parameter( self.relative_position_params.view( 2 * window_size - 1, 2 * window_size - 1, self.n_heads ) .transpose(1, 2) .transpose(0, 1) ) def generate_mask(self, h, w, p, shift): # supporting square. attn_mask = torch.zeros( h, w, p, p, p, p, dtype=torch.bool, device=self.relative_position_params.device, ) if self.type == "W": return attn_mask s = p - shift attn_mask[-1, :, :s, :, s:, :] = True attn_mask[-1, :, s:, :, :s, :] = True attn_mask[:, -1, :, :s, :, s:] = True attn_mask[:, -1, :, s:, :, :s] = True attn_mask = rearrange( attn_mask, "w1 w2 p1 p2 p3 p4 -> 1 1 (w1 w2) (p1 p2) (p3 p4)" ) return attn_mask def forward(self, x): if self.type != "W": x = torch.roll( x, shifts=(-(self.window_size // 2), -(self.window_size // 2)), dims=(1, 2), ) x = rearrange( x, "b (w1 p1) (w2 p2) c -> b w1 w2 p1 p2 c", p1=self.window_size, p2=self.window_size, ) h_windows = x.size(1) w_windows = x.size(2) # square validation # assert h_windows == w_windows x = rearrange( x, "b w1 w2 p1 p2 c -> b (w1 w2) (p1 p2) c", p1=self.window_size, p2=self.window_size, ) qkv = self.embedding_layer(x) q, k, v = rearrange( qkv, "b nw np (threeh c) -> threeh b nw np c", c=self.head_dim ).chunk(3, dim=0) sim = torch.einsum("hbwpc,hbwqc->hbwpq", q, k) * self.scale # Adding learnable relative embedding sim = sim + rearrange(self.relative_embedding(), "h p q -> h 1 1 p q") # Using Attn Mask to distinguish different subwindows. if self.type != "W": attn_mask = self.generate_mask( h_windows, w_windows, self.window_size, shift=self.window_size // 2 ) sim = sim.masked_fill_(attn_mask, float("-inf")) probs = nn.functional.softmax(sim, dim=-1) output = torch.einsum("hbwij,hbwjc->hbwic", probs, v) output = rearrange(output, "h b w p c -> b w p (h c)") output = self.linear(output) output = rearrange( output, "b (w1 w2) (p1 p2) c -> b (w1 p1) (w2 p2) c", w1=h_windows, p1=self.window_size, ) if self.type != "W": output = torch.roll( output, shifts=(self.window_size // 2, self.window_size // 2), dims=(1, 2), ) return output def relative_embedding(self): cord = torch.tensor( np.array( [ [i, j] for i in range(self.window_size) for j in range(self.window_size) ] ) ) relation = cord[:, None, :] - cord[None, :, :] + self.window_size - 1 # negative is allowed return self.relative_position_params[ :, relation[:, :, 0].long(), relation[:, :, 1].long() ] class Block(nn.Module): def __init__( self, input_dim, output_dim, head_dim, window_size, drop_path, type="W", input_resolution=None, ): super(Block, self).__init__() self.input_dim = input_dim self.output_dim = output_dim assert type in ["W", "SW"] self.type = type if input_resolution <= window_size: self.type = "W" self.ln1 = nn.LayerNorm(input_dim) self.msa = WMSA(input_dim, input_dim, head_dim, window_size, self.type) self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() self.ln2 = nn.LayerNorm(input_dim) self.mlp = nn.Sequential( nn.Linear(input_dim, 4 * input_dim), nn.GELU(), nn.Linear(4 * input_dim, output_dim), ) def forward(self, x): x = x + self.drop_path(self.msa(self.ln1(x))) x = x + self.drop_path(self.mlp(self.ln2(x))) return x class ConvTransBlock(nn.Module): def __init__( self, conv_dim, trans_dim, head_dim, window_size, drop_path, type="W", input_resolution=None, ): super(ConvTransBlock, self).__init__() self.conv_dim = conv_dim self.trans_dim = trans_dim self.head_dim = head_dim self.window_size = window_size self.drop_path = drop_path self.type = type self.input_resolution = input_resolution assert self.type in ["W", "SW"] if self.input_resolution <= self.window_size: self.type = "W" self.trans_block = Block( self.trans_dim, self.trans_dim, self.head_dim, self.window_size, self.drop_path, self.type, self.input_resolution, ) self.conv1_1 = nn.Conv2d( self.conv_dim + self.trans_dim, self.conv_dim + self.trans_dim, 1, 1, 0, bias=True, ) self.conv1_2 = nn.Conv2d( self.conv_dim + self.trans_dim, self.conv_dim + self.trans_dim, 1, 1, 0, bias=True, ) self.conv_block = nn.Sequential( nn.Conv2d(self.conv_dim, self.conv_dim, 3, 1, 1, bias=False), nn.ReLU(True), nn.Conv2d(self.conv_dim, self.conv_dim, 3, 1, 1, bias=False), ) def forward(self, x): conv_x, trans_x = torch.split( self.conv1_1(x), (self.conv_dim, self.trans_dim), dim=1 ) conv_x = self.conv_block(conv_x) + conv_x trans_x = Rearrange("b c h w -> b h w c")(trans_x) trans_x = self.trans_block(trans_x) trans_x = Rearrange("b h w c -> b c h w")(trans_x) res = self.conv1_2(torch.cat((conv_x, trans_x), dim=1)) x = x + res return x class SCUNet(nn.Module): def __init__( self, state_dict, in_nc=3, config=[4, 4, 4, 4, 4, 4, 4], dim=64, drop_path_rate=0.0, input_resolution=256, ): super(SCUNet, self).__init__() self.model_arch = "SCUNet" self.sub_type = "SR" self.num_filters: int = 0 self.state = state_dict self.config = config self.dim = dim self.head_dim = 32 self.window_size = 8 self.in_nc = in_nc self.out_nc = self.in_nc self.scale = 1 self.supports_fp16 = True # drop path rate for each layer dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(config))] self.m_head = [nn.Conv2d(in_nc, dim, 3, 1, 1, bias=False)] begin = 0 self.m_down1 = [ ConvTransBlock( dim // 2, dim // 2, self.head_dim, self.window_size, dpr[i + begin], "W" if not i % 2 else "SW", input_resolution, ) for i in range(config[0]) ] + [nn.Conv2d(dim, 2 * dim, 2, 2, 0, bias=False)] begin += config[0] self.m_down2 = [ ConvTransBlock( dim, dim, self.head_dim, self.window_size, dpr[i + begin], "W" if not i % 2 else "SW", input_resolution // 2, ) for i in range(config[1]) ] + [nn.Conv2d(2 * dim, 4 * dim, 2, 2, 0, bias=False)] begin += config[1] self.m_down3 = [ ConvTransBlock( 2 * dim, 2 * dim, self.head_dim, self.window_size, dpr[i + begin], "W" if not i % 2 else "SW", input_resolution // 4, ) for i in range(config[2]) ] + [nn.Conv2d(4 * dim, 8 * dim, 2, 2, 0, bias=False)] begin += config[2] self.m_body = [ ConvTransBlock( 4 * dim, 4 * dim, self.head_dim, self.window_size, dpr[i + begin], "W" if not i % 2 else "SW", input_resolution // 8, ) for i in range(config[3]) ] begin += config[3] self.m_up3 = [ nn.ConvTranspose2d(8 * dim, 4 * dim, 2, 2, 0, bias=False), ] + [ ConvTransBlock( 2 * dim, 2 * dim, self.head_dim, self.window_size, dpr[i + begin], "W" if not i % 2 else "SW", input_resolution // 4, ) for i in range(config[4]) ] begin += config[4] self.m_up2 = [ nn.ConvTranspose2d(4 * dim, 2 * dim, 2, 2, 0, bias=False), ] + [ ConvTransBlock( dim, dim, self.head_dim, self.window_size, dpr[i + begin], "W" if not i % 2 else "SW", input_resolution // 2, ) for i in range(config[5]) ] begin += config[5] self.m_up1 = [ nn.ConvTranspose2d(2 * dim, dim, 2, 2, 0, bias=False), ] + [ ConvTransBlock( dim // 2, dim // 2, self.head_dim, self.window_size, dpr[i + begin], "W" if not i % 2 else "SW", input_resolution, ) for i in range(config[6]) ] self.m_tail = [nn.Conv2d(dim, in_nc, 3, 1, 1, bias=False)] self.m_head = nn.Sequential(*self.m_head) self.m_down1 = nn.Sequential(*self.m_down1) self.m_down2 = nn.Sequential(*self.m_down2) self.m_down3 = nn.Sequential(*self.m_down3) self.m_body = nn.Sequential(*self.m_body) self.m_up3 = nn.Sequential(*self.m_up3) self.m_up2 = nn.Sequential(*self.m_up2) self.m_up1 = nn.Sequential(*self.m_up1) self.m_tail = nn.Sequential(*self.m_tail) # self.apply(self._init_weights) self.load_state_dict(state_dict, strict=True) def check_image_size(self, x): _, _, h, w = x.size() mod_pad_h = (64 - h % 64) % 64 mod_pad_w = (64 - w % 64) % 64 x = F.pad(x, (0, mod_pad_w, 0, mod_pad_h), "reflect") return x def forward(self, x0): h, w = x0.size()[-2:] x0 = self.check_image_size(x0) x1 = self.m_head(x0) x2 = self.m_down1(x1) x3 = self.m_down2(x2) x4 = self.m_down3(x3) x = self.m_body(x4) x = self.m_up3(x + x4) x = self.m_up2(x + x3) x = self.m_up1(x + x2) x = self.m_tail(x + x1) x = x[:, :, :h, :w] return x def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=0.02) if m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0)
--- +++ @@ -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 @@ ) def generate_mask(self, h, w, p, shift): + """generating the mask of SW-MSA + Args: + shift: shift parameters in CyclicShift. + Returns: + attn_mask: should be (1 1 w p p), + """ # supporting square. attn_mask = torch.zeros( h, @@ -75,6 +82,13 @@ return attn_mask def forward(self, x): + """Forward pass of Window Multi-head Self-attention module. + Args: + x: input tensor with shape of [b h w c]; + attn_mask: attention mask, fill -inf where the value is True; + Returns: + output: tensor shape [b h w c] + """ if self.type != "W": x = torch.roll( x, @@ -161,6 +175,7 @@ type="W", input_resolution=None, ): + """SwinTransformer Block""" super(Block, self).__init__() self.input_dim = input_dim self.output_dim = output_dim @@ -196,6 +211,7 @@ type="W", input_resolution=None, ): + """SwinTransformer and Conv Block""" super(ConvTransBlock, self).__init__() self.conv_dim = conv_dim self.trans_dim = trans_dim @@ -436,4 +452,4 @@ nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) - nn.init.constant_(m.weight, 1.0)+ nn.init.constant_(m.weight, 1.0)
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, drop_prob: float = 0.0, training: bool = False): if drop_prob == 0.0 or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0],) + (1,) * ( x.ndim - 1 ) # work with diff dim tensors, not just 2D ConvNets random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device) random_tensor.floor_() # binarize output = x.div(keep_prob) * random_tensor return output class DropPath(nn.Module): def __init__(self, drop_prob=None): super(DropPath, self).__init__() self.drop_prob = drop_prob def forward(self, x): return drop_path(x, self.drop_prob, self.training) # type: ignore class ChannelAttention(nn.Module): def __init__(self, num_feat, squeeze_factor=16): super(ChannelAttention, self).__init__() self.attention = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Conv2d(num_feat, num_feat // squeeze_factor, 1, padding=0), nn.ReLU(inplace=True), nn.Conv2d(num_feat // squeeze_factor, num_feat, 1, padding=0), nn.Sigmoid(), ) def forward(self, x): y = self.attention(x) return x * y class CAB(nn.Module): def __init__(self, num_feat, compress_ratio=3, squeeze_factor=30): super(CAB, self).__init__() self.cab = nn.Sequential( nn.Conv2d(num_feat, num_feat // compress_ratio, 3, 1, 1), nn.GELU(), nn.Conv2d(num_feat // compress_ratio, num_feat, 3, 1, 1), ChannelAttention(num_feat, squeeze_factor), ) def forward(self, x): return self.cab(x) class Mlp(nn.Module): def __init__( self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0, ): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop) def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x def window_partition(x, window_size): b, h, w, c = x.shape x = x.view(b, h // window_size, window_size, w // window_size, window_size, c) windows = ( x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, c) ) return windows def window_reverse(windows, window_size, h, w): b = int(windows.shape[0] / (h * w / window_size / window_size)) x = windows.view( b, h // window_size, w // window_size, window_size, window_size, -1 ) x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(b, h, w, -1) return x class WindowAttention(nn.Module): def __init__( self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0.0, proj_drop=0.0, ): super().__init__() self.dim = dim self.window_size = window_size # Wh, Ww self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim**-0.5 # define a parameter table of relative position bias self.relative_position_bias_table = nn.Parameter( # type: ignore torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads) ) # 2*Wh-1 * 2*Ww-1, nH self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) trunc_normal_(self.relative_position_bias_table, std=0.02) self.softmax = nn.Softmax(dim=-1) def forward(self, x, rpi, mask=None): b_, n, c = x.shape qkv = ( self.qkv(x) .reshape(b_, n, 3, self.num_heads, c // self.num_heads) .permute(2, 0, 3, 1, 4) ) q, k, v = ( qkv[0], qkv[1], qkv[2], ) # make torchscript happy (cannot use tensor as tuple) q = q * self.scale attn = q @ k.transpose(-2, -1) relative_position_bias = self.relative_position_bias_table[rpi.view(-1)].view( self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1, ) # Wh*Ww,Wh*Ww,nH relative_position_bias = relative_position_bias.permute( 2, 0, 1 ).contiguous() # nH, Wh*Ww, Wh*Ww attn = attn + relative_position_bias.unsqueeze(0) if mask is not None: nw = mask.shape[0] attn = attn.view(b_ // nw, nw, self.num_heads, n, n) + mask.unsqueeze( 1 ).unsqueeze(0) attn = attn.view(-1, self.num_heads, n, n) attn = self.softmax(attn) else: attn = self.softmax(attn) attn = self.attn_drop(attn) x = (attn @ v).transpose(1, 2).reshape(b_, n, c) x = self.proj(x) x = self.proj_drop(x) return x class HAB(nn.Module): def __init__( self, dim, input_resolution, num_heads, window_size=7, shift_size=0, compress_ratio=3, squeeze_factor=30, conv_scale=0.01, mlp_ratio=4.0, qkv_bias=True, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm, ): super().__init__() self.dim = dim self.input_resolution = input_resolution self.num_heads = num_heads self.window_size = window_size self.shift_size = shift_size self.mlp_ratio = mlp_ratio if min(self.input_resolution) <= self.window_size: # if window size is larger than input resolution, we don't partition windows self.shift_size = 0 self.window_size = min(self.input_resolution) assert ( 0 <= self.shift_size < self.window_size ), "shift_size must in 0-window_size" self.norm1 = norm_layer(dim) self.attn = WindowAttention( dim, window_size=to_2tuple(self.window_size), num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, ) self.conv_scale = conv_scale self.conv_block = CAB( num_feat=dim, compress_ratio=compress_ratio, squeeze_factor=squeeze_factor ) self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp( in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop, ) def forward(self, x, x_size, rpi_sa, attn_mask): h, w = x_size b, _, c = x.shape # assert seq_len == h * w, "input feature has wrong size" shortcut = x x = self.norm1(x) x = x.view(b, h, w, c) # Conv_X conv_x = self.conv_block(x.permute(0, 3, 1, 2)) conv_x = conv_x.permute(0, 2, 3, 1).contiguous().view(b, h * w, c) # cyclic shift if self.shift_size > 0: shifted_x = torch.roll( x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2) ) attn_mask = attn_mask else: shifted_x = x attn_mask = None # partition windows x_windows = window_partition( shifted_x, self.window_size ) # nw*b, window_size, window_size, c x_windows = x_windows.view( -1, self.window_size * self.window_size, c ) # nw*b, window_size*window_size, c # W-MSA/SW-MSA (to be compatible for testing on images whose shapes are the multiple of window size attn_windows = self.attn(x_windows, rpi=rpi_sa, mask=attn_mask) # merge windows attn_windows = attn_windows.view(-1, self.window_size, self.window_size, c) shifted_x = window_reverse(attn_windows, self.window_size, h, w) # b h' w' c # reverse cyclic shift if self.shift_size > 0: attn_x = torch.roll( shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2) ) else: attn_x = shifted_x attn_x = attn_x.view(b, h * w, c) # FFN x = shortcut + self.drop_path(attn_x) + conv_x * self.conv_scale x = x + self.drop_path(self.mlp(self.norm2(x))) return x class PatchMerging(nn.Module): def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm): super().__init__() self.input_resolution = input_resolution self.dim = dim self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) self.norm = norm_layer(4 * dim) def forward(self, x): h, w = self.input_resolution b, seq_len, c = x.shape assert seq_len == h * w, "input feature has wrong size" assert h % 2 == 0 and w % 2 == 0, f"x size ({h}*{w}) are not even." x = x.view(b, h, w, c) x0 = x[:, 0::2, 0::2, :] # b h/2 w/2 c x1 = x[:, 1::2, 0::2, :] # b h/2 w/2 c x2 = x[:, 0::2, 1::2, :] # b h/2 w/2 c x3 = x[:, 1::2, 1::2, :] # b h/2 w/2 c x = torch.cat([x0, x1, x2, x3], -1) # b h/2 w/2 4*c x = x.view(b, -1, 4 * c) # b h/2*w/2 4*c x = self.norm(x) x = self.reduction(x) return x class OCAB(nn.Module): # overlapping cross-attention block def __init__( self, dim, input_resolution, window_size, overlap_ratio, num_heads, qkv_bias=True, qk_scale=None, mlp_ratio=2, norm_layer=nn.LayerNorm, ): super().__init__() self.dim = dim self.input_resolution = input_resolution self.window_size = window_size self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim**-0.5 self.overlap_win_size = int(window_size * overlap_ratio) + window_size self.norm1 = norm_layer(dim) self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.unfold = nn.Unfold( kernel_size=(self.overlap_win_size, self.overlap_win_size), stride=window_size, padding=(self.overlap_win_size - window_size) // 2, ) # define a parameter table of relative position bias self.relative_position_bias_table = nn.Parameter( # type: ignore torch.zeros( (window_size + self.overlap_win_size - 1) * (window_size + self.overlap_win_size - 1), num_heads, ) ) # 2*Wh-1 * 2*Ww-1, nH trunc_normal_(self.relative_position_bias_table, std=0.02) self.softmax = nn.Softmax(dim=-1) self.proj = nn.Linear(dim, dim) self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp( in_features=dim, hidden_features=mlp_hidden_dim, act_layer=nn.GELU ) def forward(self, x, x_size, rpi): h, w = x_size b, _, c = x.shape shortcut = x x = self.norm1(x) x = x.view(b, h, w, c) qkv = self.qkv(x).reshape(b, h, w, 3, c).permute(3, 0, 4, 1, 2) # 3, b, c, h, w q = qkv[0].permute(0, 2, 3, 1) # b, h, w, c kv = torch.cat((qkv[1], qkv[2]), dim=1) # b, 2*c, h, w # partition windows q_windows = window_partition( q, self.window_size ) # nw*b, window_size, window_size, c q_windows = q_windows.view( -1, self.window_size * self.window_size, c ) # nw*b, window_size*window_size, c kv_windows = self.unfold(kv) # b, c*w*w, nw kv_windows = rearrange( kv_windows, "b (nc ch owh oww) nw -> nc (b nw) (owh oww) ch", nc=2, ch=c, owh=self.overlap_win_size, oww=self.overlap_win_size, ).contiguous() # 2, nw*b, ow*ow, c # Do the above rearrangement without the rearrange function # kv_windows = kv_windows.view( # 2, b, self.overlap_win_size, self.overlap_win_size, c, -1 # ) # kv_windows = kv_windows.permute(0, 5, 1, 2, 3, 4).contiguous() # kv_windows = kv_windows.view( # 2, -1, self.overlap_win_size * self.overlap_win_size, c # ) k_windows, v_windows = kv_windows[0], kv_windows[1] # nw*b, ow*ow, c b_, nq, _ = q_windows.shape _, n, _ = k_windows.shape d = self.dim // self.num_heads q = q_windows.reshape(b_, nq, self.num_heads, d).permute( 0, 2, 1, 3 ) # nw*b, nH, nq, d k = k_windows.reshape(b_, n, self.num_heads, d).permute( 0, 2, 1, 3 ) # nw*b, nH, n, d v = v_windows.reshape(b_, n, self.num_heads, d).permute( 0, 2, 1, 3 ) # nw*b, nH, n, d q = q * self.scale attn = q @ k.transpose(-2, -1) relative_position_bias = self.relative_position_bias_table[rpi.view(-1)].view( self.window_size * self.window_size, self.overlap_win_size * self.overlap_win_size, -1, ) # ws*ws, wse*wse, nH relative_position_bias = relative_position_bias.permute( 2, 0, 1 ).contiguous() # nH, ws*ws, wse*wse attn = attn + relative_position_bias.unsqueeze(0) attn = self.softmax(attn) attn_windows = (attn @ v).transpose(1, 2).reshape(b_, nq, self.dim) # merge windows attn_windows = attn_windows.view( -1, self.window_size, self.window_size, self.dim ) x = window_reverse(attn_windows, self.window_size, h, w) # b h w c x = x.view(b, h * w, self.dim) x = self.proj(x) + shortcut x = x + self.mlp(self.norm2(x)) return x class AttenBlocks(nn.Module): def __init__( self, dim, input_resolution, depth, num_heads, window_size, compress_ratio, squeeze_factor, conv_scale, overlap_ratio, mlp_ratio=4.0, qkv_bias=True, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False, ): super().__init__() self.dim = dim self.input_resolution = input_resolution self.depth = depth self.use_checkpoint = use_checkpoint # build blocks self.blocks = nn.ModuleList( [ HAB( dim=dim, input_resolution=input_resolution, num_heads=num_heads, window_size=window_size, shift_size=0 if (i % 2 == 0) else window_size // 2, compress_ratio=compress_ratio, squeeze_factor=squeeze_factor, conv_scale=conv_scale, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop, attn_drop=attn_drop, drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, norm_layer=norm_layer, ) for i in range(depth) ] ) # OCAB self.overlap_attn = OCAB( dim=dim, input_resolution=input_resolution, window_size=window_size, overlap_ratio=overlap_ratio, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, mlp_ratio=mlp_ratio, # type: ignore norm_layer=norm_layer, ) # patch merging layer if downsample is not None: self.downsample = downsample( input_resolution, dim=dim, norm_layer=norm_layer ) else: self.downsample = None def forward(self, x, x_size, params): for blk in self.blocks: x = blk(x, x_size, params["rpi_sa"], params["attn_mask"]) x = self.overlap_attn(x, x_size, params["rpi_oca"]) if self.downsample is not None: x = self.downsample(x) return x class RHAG(nn.Module): def __init__( self, dim, input_resolution, depth, num_heads, window_size, compress_ratio, squeeze_factor, conv_scale, overlap_ratio, mlp_ratio=4.0, qkv_bias=True, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False, img_size=224, patch_size=4, resi_connection="1conv", ): super(RHAG, self).__init__() self.dim = dim self.input_resolution = input_resolution self.residual_group = AttenBlocks( dim=dim, input_resolution=input_resolution, depth=depth, num_heads=num_heads, window_size=window_size, compress_ratio=compress_ratio, squeeze_factor=squeeze_factor, conv_scale=conv_scale, overlap_ratio=overlap_ratio, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop, attn_drop=attn_drop, drop_path=drop_path, norm_layer=norm_layer, downsample=downsample, use_checkpoint=use_checkpoint, ) if resi_connection == "1conv": self.conv = nn.Conv2d(dim, dim, 3, 1, 1) elif resi_connection == "identity": self.conv = nn.Identity() self.patch_embed = PatchEmbed( img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim, norm_layer=None, ) self.patch_unembed = PatchUnEmbed( img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim, norm_layer=None, ) def forward(self, x, x_size, params): return ( self.patch_embed( self.conv( self.patch_unembed(self.residual_group(x, x_size, params), x_size) ) ) + x ) class PatchEmbed(nn.Module): def __init__( self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None ): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) patches_resolution = [ img_size[0] // patch_size[0], # type: ignore img_size[1] // patch_size[1], # type: ignore ] self.img_size = img_size self.patch_size = patch_size self.patches_resolution = patches_resolution self.num_patches = patches_resolution[0] * patches_resolution[1] self.in_chans = in_chans self.embed_dim = embed_dim if norm_layer is not None: self.norm = norm_layer(embed_dim) else: self.norm = None def forward(self, x): x = x.flatten(2).transpose(1, 2) # b Ph*Pw c if self.norm is not None: x = self.norm(x) return x class PatchUnEmbed(nn.Module): def __init__( self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None ): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) patches_resolution = [ img_size[0] // patch_size[0], # type: ignore img_size[1] // patch_size[1], # type: ignore ] self.img_size = img_size self.patch_size = patch_size self.patches_resolution = patches_resolution self.num_patches = patches_resolution[0] * patches_resolution[1] self.in_chans = in_chans self.embed_dim = embed_dim def forward(self, x, x_size): x = ( x.transpose(1, 2) .contiguous() .view(x.shape[0], self.embed_dim, x_size[0], x_size[1]) ) # b Ph*Pw c return x class Upsample(nn.Sequential): def __init__(self, scale, num_feat): m = [] if (scale & (scale - 1)) == 0: # scale = 2^n for _ in range(int(math.log(scale, 2))): m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1)) m.append(nn.PixelShuffle(2)) elif scale == 3: m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1)) m.append(nn.PixelShuffle(3)) else: raise ValueError( f"scale {scale} is not supported. " "Supported scales: 2^n and 3." ) super(Upsample, self).__init__(*m) class HAT(nn.Module): def __init__( self, state_dict, **kwargs, ): super(HAT, self).__init__() # Defaults img_size = 64 patch_size = 1 in_chans = 3 embed_dim = 96 depths = (6, 6, 6, 6) num_heads = (6, 6, 6, 6) window_size = 7 compress_ratio = 3 squeeze_factor = 30 conv_scale = 0.01 overlap_ratio = 0.5 mlp_ratio = 4.0 qkv_bias = True qk_scale = None drop_rate = 0.0 attn_drop_rate = 0.0 drop_path_rate = 0.1 norm_layer = nn.LayerNorm ape = False patch_norm = True use_checkpoint = False upscale = 2 img_range = 1.0 upsampler = "" resi_connection = "1conv" self.state = state_dict self.model_arch = "HAT" self.sub_type = "SR" self.supports_fp16 = False self.support_bf16 = True self.min_size_restriction = 16 state_keys = list(state_dict.keys()) num_feat = state_dict["conv_last.weight"].shape[1] in_chans = state_dict["conv_first.weight"].shape[1] num_out_ch = state_dict["conv_last.weight"].shape[0] embed_dim = state_dict["conv_first.weight"].shape[0] if "conv_before_upsample.0.weight" in state_keys: if "conv_up1.weight" in state_keys: upsampler = "nearest+conv" else: upsampler = "pixelshuffle" supports_fp16 = False elif "upsample.0.weight" in state_keys: upsampler = "pixelshuffledirect" else: upsampler = "" upscale = 1 if upsampler == "nearest+conv": upsample_keys = [ x for x in state_keys if "conv_up" in x and "bias" not in x ] for upsample_key in upsample_keys: upscale *= 2 elif upsampler == "pixelshuffle": upsample_keys = [ x for x in state_keys if "upsample" in x and "conv" not in x and "bias" not in x ] for upsample_key in upsample_keys: shape = self.state[upsample_key].shape[0] upscale *= math.sqrt(shape // num_feat) upscale = int(upscale) elif upsampler == "pixelshuffledirect": upscale = int( math.sqrt(self.state["upsample.0.bias"].shape[0] // num_out_ch) ) max_layer_num = 0 max_block_num = 0 for key in state_keys: result = re.match( r"layers.(\d*).residual_group.blocks.(\d*).conv_block.cab.0.weight", key ) if result: layer_num, block_num = result.groups() max_layer_num = max(max_layer_num, int(layer_num)) max_block_num = max(max_block_num, int(block_num)) depths = [max_block_num + 1 for _ in range(max_layer_num + 1)] if ( "layers.0.residual_group.blocks.0.attn.relative_position_bias_table" in state_keys ): num_heads_num = self.state[ "layers.0.residual_group.blocks.0.attn.relative_position_bias_table" ].shape[-1] num_heads = [num_heads_num for _ in range(max_layer_num + 1)] else: num_heads = depths mlp_ratio = float( self.state["layers.0.residual_group.blocks.0.mlp.fc1.bias"].shape[0] / embed_dim ) # TODO: could actually count the layers, but this should do if "layers.0.conv.4.weight" in state_keys: resi_connection = "3conv" else: resi_connection = "1conv" window_size = int(math.sqrt(self.state["relative_position_index_SA"].shape[0])) # Not sure if this is needed or used at all anywhere in HAT's config if "layers.0.residual_group.blocks.1.attn_mask" in state_keys: img_size = int( math.sqrt( self.state["layers.0.residual_group.blocks.1.attn_mask"].shape[0] ) * window_size ) self.window_size = window_size self.shift_size = window_size // 2 self.overlap_ratio = overlap_ratio self.in_nc = in_chans self.out_nc = num_out_ch self.num_feat = num_feat self.embed_dim = embed_dim self.num_heads = num_heads self.depths = depths self.window_size = window_size self.mlp_ratio = mlp_ratio self.scale = upscale self.upsampler = upsampler self.img_size = img_size self.img_range = img_range self.resi_connection = resi_connection num_in_ch = in_chans # num_out_ch = in_chans # num_feat = 64 self.img_range = img_range if in_chans == 3: rgb_mean = (0.4488, 0.4371, 0.4040) self.mean = torch.Tensor(rgb_mean).view(1, 3, 1, 1) else: self.mean = torch.zeros(1, 1, 1, 1) self.upscale = upscale self.upsampler = upsampler # relative position index relative_position_index_SA = self.calculate_rpi_sa() relative_position_index_OCA = self.calculate_rpi_oca() self.register_buffer("relative_position_index_SA", relative_position_index_SA) self.register_buffer("relative_position_index_OCA", relative_position_index_OCA) # ------------------------- 1, shallow feature extraction ------------------------- # self.conv_first = nn.Conv2d(num_in_ch, embed_dim, 3, 1, 1) # ------------------------- 2, deep feature extraction ------------------------- # self.num_layers = len(depths) self.embed_dim = embed_dim self.ape = ape self.patch_norm = patch_norm self.num_features = embed_dim self.mlp_ratio = mlp_ratio # split image into non-overlapping patches self.patch_embed = PatchEmbed( img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim, norm_layer=norm_layer if self.patch_norm else None, ) num_patches = self.patch_embed.num_patches patches_resolution = self.patch_embed.patches_resolution self.patches_resolution = patches_resolution # merge non-overlapping patches into image self.patch_unembed = PatchUnEmbed( img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim, norm_layer=norm_layer if self.patch_norm else None, ) # absolute position embedding if self.ape: self.absolute_pos_embed = nn.Parameter( # type: ignore[arg-type] torch.zeros(1, num_patches, embed_dim) ) trunc_normal_(self.absolute_pos_embed, std=0.02) self.pos_drop = nn.Dropout(p=drop_rate) # stochastic depth dpr = [ x.item() for x in torch.linspace(0, drop_path_rate, sum(depths)) ] # stochastic depth decay rule # build Residual Hybrid Attention Groups (RHAG) self.layers = nn.ModuleList() for i_layer in range(self.num_layers): layer = RHAG( dim=embed_dim, input_resolution=(patches_resolution[0], patches_resolution[1]), depth=depths[i_layer], num_heads=num_heads[i_layer], window_size=window_size, compress_ratio=compress_ratio, squeeze_factor=squeeze_factor, conv_scale=conv_scale, overlap_ratio=overlap_ratio, mlp_ratio=self.mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[ sum(depths[:i_layer]) : sum(depths[: i_layer + 1]) # type: ignore ], # no impact on SR results norm_layer=norm_layer, downsample=None, use_checkpoint=use_checkpoint, img_size=img_size, patch_size=patch_size, resi_connection=resi_connection, ) self.layers.append(layer) self.norm = norm_layer(self.num_features) # build the last conv layer in deep feature extraction if resi_connection == "1conv": self.conv_after_body = nn.Conv2d(embed_dim, embed_dim, 3, 1, 1) elif resi_connection == "identity": self.conv_after_body = nn.Identity() # ------------------------- 3, high quality image reconstruction ------------------------- # if self.upsampler == "pixelshuffle": # for classical SR self.conv_before_upsample = nn.Sequential( nn.Conv2d(embed_dim, num_feat, 3, 1, 1), nn.LeakyReLU(inplace=True) ) self.upsample = Upsample(upscale, num_feat) self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1) self.apply(self._init_weights) self.load_state_dict(self.state, strict=False) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=0.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) def calculate_rpi_sa(self): # calculate relative position index for SA coords_h = torch.arange(self.window_size) coords_w = torch.arange(self.window_size) coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww relative_coords = ( coords_flatten[:, :, None] - coords_flatten[:, None, :] ) # 2, Wh*Ww, Wh*Ww relative_coords = relative_coords.permute( 1, 2, 0 ).contiguous() # Wh*Ww, Wh*Ww, 2 relative_coords[:, :, 0] += self.window_size - 1 # shift to start from 0 relative_coords[:, :, 1] += self.window_size - 1 relative_coords[:, :, 0] *= 2 * self.window_size - 1 relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww return relative_position_index def calculate_rpi_oca(self): # calculate relative position index for OCA window_size_ori = self.window_size window_size_ext = self.window_size + int(self.overlap_ratio * self.window_size) coords_h = torch.arange(window_size_ori) coords_w = torch.arange(window_size_ori) coords_ori = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, ws, ws coords_ori_flatten = torch.flatten(coords_ori, 1) # 2, ws*ws coords_h = torch.arange(window_size_ext) coords_w = torch.arange(window_size_ext) coords_ext = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, wse, wse coords_ext_flatten = torch.flatten(coords_ext, 1) # 2, wse*wse relative_coords = ( coords_ext_flatten[:, None, :] - coords_ori_flatten[:, :, None] ) # 2, ws*ws, wse*wse relative_coords = relative_coords.permute( 1, 2, 0 ).contiguous() # ws*ws, wse*wse, 2 relative_coords[:, :, 0] += ( window_size_ori - window_size_ext + 1 ) # shift to start from 0 relative_coords[:, :, 1] += window_size_ori - window_size_ext + 1 relative_coords[:, :, 0] *= window_size_ori + window_size_ext - 1 relative_position_index = relative_coords.sum(-1) return relative_position_index def calculate_mask(self, x_size): # calculate attention mask for SW-MSA h, w = x_size img_mask = torch.zeros((1, h, w, 1)) # 1 h w 1 h_slices = ( slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None), ) w_slices = ( slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None), ) cnt = 0 for h in h_slices: for w in w_slices: img_mask[:, h, w, :] = cnt cnt += 1 mask_windows = window_partition( img_mask, self.window_size ) # nw, window_size, window_size, 1 mask_windows = mask_windows.view(-1, self.window_size * self.window_size) attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill( attn_mask == 0, float(0.0) ) return attn_mask @torch.jit.ignore # type: ignore def no_weight_decay(self): return {"absolute_pos_embed"} @torch.jit.ignore # type: ignore def no_weight_decay_keywords(self): return {"relative_position_bias_table"} def check_image_size(self, x): _, _, h, w = x.size() mod_pad_h = (self.window_size - h % self.window_size) % self.window_size mod_pad_w = (self.window_size - w % self.window_size) % self.window_size x = F.pad(x, (0, mod_pad_w, 0, mod_pad_h), "reflect") return x def forward_features(self, x): x_size = (x.shape[2], x.shape[3]) # Calculate attention mask and relative position index in advance to speed up inference. # The original code is very time-cosuming for large window size. attn_mask = self.calculate_mask(x_size).to(x.device) params = { "attn_mask": attn_mask, "rpi_sa": self.relative_position_index_SA, "rpi_oca": self.relative_position_index_OCA, } x = self.patch_embed(x) if self.ape: x = x + self.absolute_pos_embed x = self.pos_drop(x) for layer in self.layers: x = layer(x, x_size, params) x = self.norm(x) # b seq_len c x = self.patch_unembed(x, x_size) return x def forward(self, x): H, W = x.shape[2:] self.mean = self.mean.type_as(x) x = (x - self.mean) * self.img_range x = self.check_image_size(x) if self.upsampler == "pixelshuffle": # for classical SR x = self.conv_first(x) x = self.conv_after_body(self.forward_features(x)) + x x = self.conv_before_upsample(x) x = self.conv_last(self.upsample(x)) x = x / self.img_range + self.mean return x[:, :, : H * self.upscale, : W * self.upscale]
--- +++ @@ -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 or not training: return x keep_prob = 1 - drop_prob @@ -26,6 +29,9 @@ class DropPath(nn.Module): + """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 + """ def __init__(self, drop_prob=None): super(DropPath, self).__init__() @@ -36,6 +42,11 @@ class ChannelAttention(nn.Module): + """Channel attention used in RCAN. + Args: + num_feat (int): Channel number of intermediate features. + squeeze_factor (int): Channel squeeze factor. Default: 16. + """ def __init__(self, num_feat, squeeze_factor=16): super(ChannelAttention, self).__init__() @@ -94,6 +105,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 // window_size, window_size, c) windows = ( @@ -103,6 +121,15 @@ def window_reverse(windows, window_size, h, w): + """ + Args: + windows: (num_windows*b, window_size, window_size, c) + window_size (int): Window size + h (int): Height of image + w (int): Width of image + Returns: + x: (b, h, w, c) + """ b = int(windows.shape[0] / (h * w / window_size / window_size)) x = windows.view( b, h // window_size, w // window_size, window_size, window_size, -1 @@ -112,6 +139,17 @@ class WindowAttention(nn.Module): + r"""Window based multi-head self attention (W-MSA) module with relative position bias. + It supports both of shifted and non-shifted window. + Args: + dim (int): Number of input channels. + window_size (tuple[int]): The height and width of the window. + num_heads (int): Number of attention heads. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set + attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 + proj_drop (float, optional): Dropout ratio of output. Default: 0.0 + """ def __init__( self, @@ -145,6 +183,11 @@ self.softmax = nn.Softmax(dim=-1) def forward(self, x, rpi, mask=None): + """ + Args: + x: input features with shape of (num_windows*b, n, c) + mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None + """ b_, n, c = x.shape qkv = ( self.qkv(x) @@ -189,6 +232,22 @@ class HAB(nn.Module): + r"""Hybrid Attention Block. + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resolution. + num_heads (int): Number of attention heads. + window_size (int): Window size. + shift_size (int): Shift size for SW-MSA. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float, optional): Stochastic depth rate. Default: 0.0 + act_layer (nn.Module, optional): Activation layer. Default: nn.GELU + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + """ def __init__( self, @@ -305,6 +364,12 @@ class PatchMerging(nn.Module): + r"""Patch Merging Layer. + Args: + input_resolution (tuple[int]): Resolution of input feature. + dim (int): Number of input channels. + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + """ def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm): super().__init__() @@ -314,6 +379,9 @@ self.norm = norm_layer(4 * dim) def forward(self, x): + """ + x: b, h*w, c + """ h, w = self.input_resolution b, seq_len, c = x.shape assert seq_len == h * w, "input feature has wrong size" @@ -469,6 +537,23 @@ class AttenBlocks(nn.Module): + """A series of attention blocks for one RHAG. + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resolution. + depth (int): Number of blocks. + num_heads (int): Number of attention heads. + window_size (int): Local window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. + """ def __init__( self, @@ -556,6 +641,26 @@ class RHAG(nn.Module): + """Residual Hybrid Attention Group (RHAG). + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resolution. + depth (int): Number of blocks. + num_heads (int): Number of attention heads. + window_size (int): Local window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. + img_size: Input image size. + patch_size: Patch size. + resi_connection: The convolutional block before residual connection. + """ def __init__( self, @@ -640,6 +745,14 @@ class PatchEmbed(nn.Module): + r"""Image to Patch Embedding + Args: + img_size (int): Image size. Default: 224. + patch_size (int): Patch token size. Default: 4. + in_chans (int): Number of input image channels. Default: 3. + embed_dim (int): Number of linear projection output channels. Default: 96. + norm_layer (nn.Module, optional): Normalization layer. Default: None + """ def __init__( self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None @@ -672,6 +785,14 @@ class PatchUnEmbed(nn.Module): + r"""Image to Patch Unembedding + Args: + img_size (int): Image size. Default: 224. + patch_size (int): Patch token size. Default: 4. + in_chans (int): Number of input image channels. Default: 3. + embed_dim (int): Number of linear projection output channels. Default: 96. + norm_layer (nn.Module, optional): Normalization layer. Default: None + """ def __init__( self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None @@ -701,6 +822,11 @@ class Upsample(nn.Sequential): + """Upsample module. + Args: + scale (int): Scale factor. Supported scales: 2^n and 3. + num_feat (int): Channel number of intermediate features. + """ def __init__(self, scale, num_feat): m = [] @@ -719,6 +845,32 @@ class HAT(nn.Module): + r"""Hybrid Attention Transformer + A PyTorch implementation of : `Activating More Pixels in Image Super-Resolution Transformer`. + Some codes are based on SwinIR. + Args: + img_size (int | tuple(int)): Input image size. Default 64 + patch_size (int | tuple(int)): Patch size. Default: 1 + in_chans (int): Number of input image channels. Default: 3 + embed_dim (int): Patch embedding dimension. Default: 96 + depths (tuple(int)): Depth of each Swin Transformer layer. + num_heads (tuple(int)): Number of attention heads in different layers. + window_size (int): Window size. Default: 7 + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4 + qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. Default: None + drop_rate (float): Dropout rate. Default: 0 + attn_drop_rate (float): Attention dropout rate. Default: 0 + drop_path_rate (float): Stochastic depth rate. Default: 0.1 + norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. + ape (bool): If True, add absolute position embedding to the patch embedding. Default: False + patch_norm (bool): If True, add normalization after patch embedding. Default: True + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False + upscale: Upscale factor. 2/3/4/8 for image SR, 1 for denoising and compress artifact reduction + img_range: Image range. 1. or 255. + upsampler: The reconstruction reconstruction module. 'pixelshuffle'/'pixelshuffledirect'/'nearest+conv'/None + resi_connection: The convolutional block before residual connection. '1conv'/'3conv' + """ def __init__( self, @@ -1122,4 +1274,4 @@ x = x / self.img_range + self.mean - return x[:, :, : H * self.upscale, : W * self.upscale]+ return x[:, :, : H * self.upscale, : W * self.upscale]
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.weight_init import trunc_normal_ def img2windows(img, H_sp, W_sp): B, C, H, W = img.shape img_reshape = img.view(B, C, H // H_sp, H_sp, W // W_sp, W_sp) img_perm = ( img_reshape.permute(0, 2, 4, 3, 5, 1).contiguous().reshape(-1, H_sp * W_sp, C) ) return img_perm def windows2img(img_splits_hw, H_sp, W_sp, H, W): B = int(img_splits_hw.shape[0] / (H * W / H_sp / W_sp)) img = img_splits_hw.view(B, H // H_sp, W // W_sp, H_sp, W_sp, -1) img = img.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) return img class SpatialGate(nn.Module): def __init__(self, dim): super().__init__() self.norm = nn.LayerNorm(dim) self.conv = nn.Conv2d( dim, dim, kernel_size=3, stride=1, padding=1, groups=dim ) # DW Conv def forward(self, x, H, W): # Split x1, x2 = x.chunk(2, dim=-1) B, N, C = x.shape x2 = ( self.conv(self.norm(x2).transpose(1, 2).contiguous().view(B, C // 2, H, W)) .flatten(2) .transpose(-1, -2) .contiguous() ) return x1 * x2 class SGFN(nn.Module): def __init__( self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0, ): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.sg = SpatialGate(hidden_features // 2) self.fc2 = nn.Linear(hidden_features // 2, out_features) self.drop = nn.Dropout(drop) def forward(self, x, H, W): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.sg(x, H, W) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x class DynamicPosBias(nn.Module): # The implementation builds on Crossformer code https://github.com/cheerss/CrossFormer/blob/main/models/crossformer.py def __init__(self, dim, num_heads, residual): super().__init__() self.residual = residual self.num_heads = num_heads self.pos_dim = dim // 4 self.pos_proj = nn.Linear(2, self.pos_dim) self.pos1 = nn.Sequential( nn.LayerNorm(self.pos_dim), nn.ReLU(inplace=True), nn.Linear(self.pos_dim, self.pos_dim), ) self.pos2 = nn.Sequential( nn.LayerNorm(self.pos_dim), nn.ReLU(inplace=True), nn.Linear(self.pos_dim, self.pos_dim), ) self.pos3 = nn.Sequential( nn.LayerNorm(self.pos_dim), nn.ReLU(inplace=True), nn.Linear(self.pos_dim, self.num_heads), ) def forward(self, biases): if self.residual: pos = self.pos_proj(biases) # 2Gh-1 * 2Gw-1, heads pos = pos + self.pos1(pos) pos = pos + self.pos2(pos) pos = self.pos3(pos) else: pos = self.pos3(self.pos2(self.pos1(self.pos_proj(biases)))) return pos class Spatial_Attention(nn.Module): def __init__( self, dim, idx, split_size=[8, 8], dim_out=None, num_heads=6, attn_drop=0.0, proj_drop=0.0, qk_scale=None, position_bias=True, ): super().__init__() self.dim = dim self.dim_out = dim_out or dim self.split_size = split_size self.num_heads = num_heads self.idx = idx self.position_bias = position_bias head_dim = dim // num_heads self.scale = qk_scale or head_dim**-0.5 if idx == 0: H_sp, W_sp = self.split_size[0], self.split_size[1] elif idx == 1: W_sp, H_sp = self.split_size[0], self.split_size[1] else: print("ERROR MODE", idx) exit(0) self.H_sp = H_sp self.W_sp = W_sp if self.position_bias: self.pos = DynamicPosBias(self.dim // 4, self.num_heads, residual=False) # generate mother-set position_bias_h = torch.arange(1 - self.H_sp, self.H_sp) position_bias_w = torch.arange(1 - self.W_sp, self.W_sp) biases = torch.stack(torch.meshgrid([position_bias_h, position_bias_w])) biases = biases.flatten(1).transpose(0, 1).contiguous().float() self.register_buffer("rpe_biases", biases) # get pair-wise relative position index for each token inside the window coords_h = torch.arange(self.H_sp) coords_w = torch.arange(self.W_sp) coords = torch.stack(torch.meshgrid([coords_h, coords_w])) coords_flatten = torch.flatten(coords, 1) relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] relative_coords = relative_coords.permute(1, 2, 0).contiguous() relative_coords[:, :, 0] += self.H_sp - 1 relative_coords[:, :, 1] += self.W_sp - 1 relative_coords[:, :, 0] *= 2 * self.W_sp - 1 relative_position_index = relative_coords.sum(-1) self.register_buffer("relative_position_index", relative_position_index) self.attn_drop = nn.Dropout(attn_drop) def im2win(self, x, H, W): B, N, C = x.shape x = x.transpose(-2, -1).contiguous().view(B, C, H, W) x = img2windows(x, self.H_sp, self.W_sp) x = ( x.reshape(-1, self.H_sp * self.W_sp, self.num_heads, C // self.num_heads) .permute(0, 2, 1, 3) .contiguous() ) return x def forward(self, qkv, H, W, mask=None): q, k, v = qkv[0], qkv[1], qkv[2] B, L, C = q.shape assert L == H * W, "flatten img_tokens has wrong size" # partition the q,k,v, image to window q = self.im2win(q, H, W) k = self.im2win(k, H, W) v = self.im2win(v, H, W) q = q * self.scale attn = q @ k.transpose(-2, -1) # B head N C @ B head C N --> B head N N # calculate drpe if self.position_bias: pos = self.pos(self.rpe_biases) # select position bias relative_position_bias = pos[self.relative_position_index.view(-1)].view( self.H_sp * self.W_sp, self.H_sp * self.W_sp, -1 ) relative_position_bias = relative_position_bias.permute( 2, 0, 1 ).contiguous() attn = attn + relative_position_bias.unsqueeze(0) N = attn.shape[3] # use mask for shift window if mask is not None: nW = mask.shape[0] attn = attn.view(B, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze( 0 ) attn = attn.view(-1, self.num_heads, N, N) attn = nn.functional.softmax(attn, dim=-1, dtype=attn.dtype) attn = self.attn_drop(attn) x = attn @ v x = x.transpose(1, 2).reshape( -1, self.H_sp * self.W_sp, C ) # B head N N @ B head N C # merge the window, window to image x = windows2img(x, self.H_sp, self.W_sp, H, W) # B H' W' C return x class Adaptive_Spatial_Attention(nn.Module): # The implementation builds on CAT code https://github.com/Zhengchen1999/CAT def __init__( self, dim, num_heads, reso=64, split_size=[8, 8], shift_size=[1, 2], qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, rg_idx=0, b_idx=0, ): super().__init__() self.dim = dim self.num_heads = num_heads self.split_size = split_size self.shift_size = shift_size self.b_idx = b_idx self.rg_idx = rg_idx self.patches_resolution = reso self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) assert ( 0 <= self.shift_size[0] < self.split_size[0] ), "shift_size must in 0-split_size0" assert ( 0 <= self.shift_size[1] < self.split_size[1] ), "shift_size must in 0-split_size1" self.branch_num = 2 self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(drop) self.attns = nn.ModuleList( [ Spatial_Attention( dim // 2, idx=i, split_size=split_size, num_heads=num_heads // 2, dim_out=dim // 2, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, position_bias=True, ) for i in range(self.branch_num) ] ) if (self.rg_idx % 2 == 0 and self.b_idx > 0 and (self.b_idx - 2) % 4 == 0) or ( self.rg_idx % 2 != 0 and self.b_idx % 4 == 0 ): attn_mask = self.calculate_mask( self.patches_resolution, self.patches_resolution ) self.register_buffer("attn_mask_0", attn_mask[0]) self.register_buffer("attn_mask_1", attn_mask[1]) else: attn_mask = None self.register_buffer("attn_mask_0", None) self.register_buffer("attn_mask_1", None) self.dwconv = nn.Sequential( nn.Conv2d(dim, dim, kernel_size=3, stride=1, padding=1, groups=dim), nn.BatchNorm2d(dim), nn.GELU(), ) self.channel_interaction = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Conv2d(dim, dim // 8, kernel_size=1), nn.BatchNorm2d(dim // 8), nn.GELU(), nn.Conv2d(dim // 8, dim, kernel_size=1), ) self.spatial_interaction = nn.Sequential( nn.Conv2d(dim, dim // 16, kernel_size=1), nn.BatchNorm2d(dim // 16), nn.GELU(), nn.Conv2d(dim // 16, 1, kernel_size=1), ) def calculate_mask(self, H, W): # The implementation builds on Swin Transformer code https://github.com/microsoft/Swin-Transformer/blob/main/models/swin_transformer.py # calculate attention mask for shift window img_mask_0 = torch.zeros((1, H, W, 1)) # 1 H W 1 idx=0 img_mask_1 = torch.zeros((1, H, W, 1)) # 1 H W 1 idx=1 h_slices_0 = ( slice(0, -self.split_size[0]), slice(-self.split_size[0], -self.shift_size[0]), slice(-self.shift_size[0], None), ) w_slices_0 = ( slice(0, -self.split_size[1]), slice(-self.split_size[1], -self.shift_size[1]), slice(-self.shift_size[1], None), ) h_slices_1 = ( slice(0, -self.split_size[1]), slice(-self.split_size[1], -self.shift_size[1]), slice(-self.shift_size[1], None), ) w_slices_1 = ( slice(0, -self.split_size[0]), slice(-self.split_size[0], -self.shift_size[0]), slice(-self.shift_size[0], None), ) cnt = 0 for h in h_slices_0: for w in w_slices_0: img_mask_0[:, h, w, :] = cnt cnt += 1 cnt = 0 for h in h_slices_1: for w in w_slices_1: img_mask_1[:, h, w, :] = cnt cnt += 1 # calculate mask for window-0 img_mask_0 = img_mask_0.view( 1, H // self.split_size[0], self.split_size[0], W // self.split_size[1], self.split_size[1], 1, ) img_mask_0 = ( img_mask_0.permute(0, 1, 3, 2, 4, 5) .contiguous() .view(-1, self.split_size[0], self.split_size[1], 1) ) # nW, sw[0], sw[1], 1 mask_windows_0 = img_mask_0.view(-1, self.split_size[0] * self.split_size[1]) attn_mask_0 = mask_windows_0.unsqueeze(1) - mask_windows_0.unsqueeze(2) attn_mask_0 = attn_mask_0.masked_fill( attn_mask_0 != 0, float(-100.0) ).masked_fill(attn_mask_0 == 0, float(0.0)) # calculate mask for window-1 img_mask_1 = img_mask_1.view( 1, H // self.split_size[1], self.split_size[1], W // self.split_size[0], self.split_size[0], 1, ) img_mask_1 = ( img_mask_1.permute(0, 1, 3, 2, 4, 5) .contiguous() .view(-1, self.split_size[1], self.split_size[0], 1) ) # nW, sw[1], sw[0], 1 mask_windows_1 = img_mask_1.view(-1, self.split_size[1] * self.split_size[0]) attn_mask_1 = mask_windows_1.unsqueeze(1) - mask_windows_1.unsqueeze(2) attn_mask_1 = attn_mask_1.masked_fill( attn_mask_1 != 0, float(-100.0) ).masked_fill(attn_mask_1 == 0, float(0.0)) return attn_mask_0, attn_mask_1 def forward(self, x, H, W): B, L, C = x.shape assert L == H * W, "flatten img_tokens has wrong size" qkv = self.qkv(x).reshape(B, -1, 3, C).permute(2, 0, 1, 3) # 3, B, HW, C # V without partition v = qkv[2].transpose(-2, -1).contiguous().view(B, C, H, W) # image padding max_split_size = max(self.split_size[0], self.split_size[1]) pad_l = pad_t = 0 pad_r = (max_split_size - W % max_split_size) % max_split_size pad_b = (max_split_size - H % max_split_size) % max_split_size qkv = qkv.reshape(3 * B, H, W, C).permute(0, 3, 1, 2) # 3B C H W qkv = ( F.pad(qkv, (pad_l, pad_r, pad_t, pad_b)) .reshape(3, B, C, -1) .transpose(-2, -1) ) # l r t b _H = pad_b + H _W = pad_r + W _L = _H * _W # window-0 and window-1 on split channels [C/2, C/2]; for square windows (e.g., 8x8), window-0 and window-1 can be merged # shift in block: (0, 4, 8, ...), (2, 6, 10, ...), (0, 4, 8, ...), (2, 6, 10, ...), ... if (self.rg_idx % 2 == 0 and self.b_idx > 0 and (self.b_idx - 2) % 4 == 0) or ( self.rg_idx % 2 != 0 and self.b_idx % 4 == 0 ): qkv = qkv.view(3, B, _H, _W, C) qkv_0 = torch.roll( qkv[:, :, :, :, : C // 2], shifts=(-self.shift_size[0], -self.shift_size[1]), dims=(2, 3), ) qkv_0 = qkv_0.view(3, B, _L, C // 2) qkv_1 = torch.roll( qkv[:, :, :, :, C // 2 :], shifts=(-self.shift_size[1], -self.shift_size[0]), dims=(2, 3), ) qkv_1 = qkv_1.view(3, B, _L, C // 2) if self.patches_resolution != _H or self.patches_resolution != _W: mask_tmp = self.calculate_mask(_H, _W) x1_shift = self.attns[0](qkv_0, _H, _W, mask=mask_tmp[0].to(x.device)) x2_shift = self.attns[1](qkv_1, _H, _W, mask=mask_tmp[1].to(x.device)) else: x1_shift = self.attns[0](qkv_0, _H, _W, mask=self.attn_mask_0) x2_shift = self.attns[1](qkv_1, _H, _W, mask=self.attn_mask_1) x1 = torch.roll( x1_shift, shifts=(self.shift_size[0], self.shift_size[1]), dims=(1, 2) ) x2 = torch.roll( x2_shift, shifts=(self.shift_size[1], self.shift_size[0]), dims=(1, 2) ) x1 = x1[:, :H, :W, :].reshape(B, L, C // 2) x2 = x2[:, :H, :W, :].reshape(B, L, C // 2) # attention output attened_x = torch.cat([x1, x2], dim=2) else: x1 = self.attns[0](qkv[:, :, :, : C // 2], _H, _W)[:, :H, :W, :].reshape( B, L, C // 2 ) x2 = self.attns[1](qkv[:, :, :, C // 2 :], _H, _W)[:, :H, :W, :].reshape( B, L, C // 2 ) # attention output attened_x = torch.cat([x1, x2], dim=2) # convolution output conv_x = self.dwconv(v) # Adaptive Interaction Module (AIM) # C-Map (before sigmoid) channel_map = ( self.channel_interaction(conv_x) .permute(0, 2, 3, 1) .contiguous() .view(B, 1, C) ) # S-Map (before sigmoid) attention_reshape = attened_x.transpose(-2, -1).contiguous().view(B, C, H, W) spatial_map = self.spatial_interaction(attention_reshape) # C-I attened_x = attened_x * torch.sigmoid(channel_map) # S-I conv_x = torch.sigmoid(spatial_map) * conv_x conv_x = conv_x.permute(0, 2, 3, 1).contiguous().view(B, L, C) x = attened_x + conv_x x = self.proj(x) x = self.proj_drop(x) return x class Adaptive_Channel_Attention(nn.Module): # The implementation builds on XCiT code https://github.com/facebookresearch/xcit def __init__( self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0, ): super().__init__() self.num_heads = num_heads self.temperature = nn.Parameter(torch.ones(num_heads, 1, 1)) self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) self.dwconv = nn.Sequential( nn.Conv2d(dim, dim, kernel_size=3, stride=1, padding=1, groups=dim), nn.BatchNorm2d(dim), nn.GELU(), ) self.channel_interaction = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Conv2d(dim, dim // 8, kernel_size=1), nn.BatchNorm2d(dim // 8), nn.GELU(), nn.Conv2d(dim // 8, dim, kernel_size=1), ) self.spatial_interaction = nn.Sequential( nn.Conv2d(dim, dim // 16, kernel_size=1), nn.BatchNorm2d(dim // 16), nn.GELU(), nn.Conv2d(dim // 16, 1, kernel_size=1), ) def forward(self, x, H, W): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads) qkv = qkv.permute(2, 0, 3, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] q = q.transpose(-2, -1) k = k.transpose(-2, -1) v = v.transpose(-2, -1) v_ = v.reshape(B, C, N).contiguous().view(B, C, H, W) q = torch.nn.functional.normalize(q, dim=-1) k = torch.nn.functional.normalize(k, dim=-1) attn = (q @ k.transpose(-2, -1)) * self.temperature attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) # attention output attened_x = (attn @ v).permute(0, 3, 1, 2).reshape(B, N, C) # convolution output conv_x = self.dwconv(v_) # Adaptive Interaction Module (AIM) # C-Map (before sigmoid) attention_reshape = attened_x.transpose(-2, -1).contiguous().view(B, C, H, W) channel_map = self.channel_interaction(attention_reshape) # S-Map (before sigmoid) spatial_map = ( self.spatial_interaction(conv_x) .permute(0, 2, 3, 1) .contiguous() .view(B, N, 1) ) # S-I attened_x = attened_x * torch.sigmoid(spatial_map) # C-I conv_x = conv_x * torch.sigmoid(channel_map) conv_x = conv_x.permute(0, 2, 3, 1).contiguous().view(B, N, C) x = attened_x + conv_x x = self.proj(x) x = self.proj_drop(x) return x class DATB(nn.Module): def __init__( self, dim, num_heads, reso=64, split_size=[2, 4], shift_size=[1, 2], expansion_factor=4.0, qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm, rg_idx=0, b_idx=0, ): super().__init__() self.norm1 = norm_layer(dim) if b_idx % 2 == 0: # DSTB self.attn = Adaptive_Spatial_Attention( dim, num_heads=num_heads, reso=reso, split_size=split_size, shift_size=shift_size, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop, attn_drop=attn_drop, rg_idx=rg_idx, b_idx=b_idx, ) else: # DCTB self.attn = Adaptive_Channel_Attention( dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, ) self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() ffn_hidden_dim = int(dim * expansion_factor) self.ffn = SGFN( in_features=dim, hidden_features=ffn_hidden_dim, out_features=dim, act_layer=act_layer, ) self.norm2 = norm_layer(dim) def forward(self, x, x_size): H, W = x_size x = x + self.drop_path(self.attn(self.norm1(x), H, W)) x = x + self.drop_path(self.ffn(self.norm2(x), H, W)) return x class ResidualGroup(nn.Module): def __init__( self, dim, reso, num_heads, split_size=[2, 4], expansion_factor=4.0, qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, drop_paths=None, act_layer=nn.GELU, norm_layer=nn.LayerNorm, depth=2, use_chk=False, resi_connection="1conv", rg_idx=0, ): super().__init__() self.use_chk = use_chk self.reso = reso self.blocks = nn.ModuleList( [ DATB( dim=dim, num_heads=num_heads, reso=reso, split_size=split_size, shift_size=[split_size[0] // 2, split_size[1] // 2], expansion_factor=expansion_factor, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop, attn_drop=attn_drop, drop_path=drop_paths[i], act_layer=act_layer, norm_layer=norm_layer, rg_idx=rg_idx, b_idx=i, ) for i in range(depth) ] ) if resi_connection == "1conv": self.conv = nn.Conv2d(dim, dim, 3, 1, 1) elif resi_connection == "3conv": self.conv = nn.Sequential( nn.Conv2d(dim, dim // 4, 3, 1, 1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(dim // 4, dim // 4, 1, 1, 0), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(dim // 4, dim, 3, 1, 1), ) def forward(self, x, x_size): H, W = x_size res = x for blk in self.blocks: if self.use_chk: x = checkpoint.checkpoint(blk, x, x_size) else: x = blk(x, x_size) x = rearrange(x, "b (h w) c -> b c h w", h=H, w=W) x = self.conv(x) x = rearrange(x, "b c h w -> b (h w) c") x = res + x return x class Upsample(nn.Sequential): def __init__(self, scale, num_feat): m = [] if (scale & (scale - 1)) == 0: # scale = 2^n for _ in range(int(math.log(scale, 2))): m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1)) m.append(nn.PixelShuffle(2)) elif scale == 3: m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1)) m.append(nn.PixelShuffle(3)) else: raise ValueError( f"scale {scale} is not supported. " "Supported scales: 2^n and 3." ) super(Upsample, self).__init__(*m) class UpsampleOneStep(nn.Sequential): def __init__(self, scale, num_feat, num_out_ch, input_resolution=None): self.num_feat = num_feat self.input_resolution = input_resolution m = [] m.append(nn.Conv2d(num_feat, (scale**2) * num_out_ch, 3, 1, 1)) m.append(nn.PixelShuffle(scale)) super(UpsampleOneStep, self).__init__(*m) def flops(self): h, w = self.input_resolution flops = h * w * self.num_feat * 3 * 9 return flops class DAT(nn.Module): def __init__(self, state_dict): super().__init__() # defaults img_size = 64 in_chans = 3 embed_dim = 180 split_size = [2, 4] depth = [2, 2, 2, 2] num_heads = [2, 2, 2, 2] expansion_factor = 4.0 qkv_bias = True qk_scale = None drop_rate = 0.0 attn_drop_rate = 0.0 drop_path_rate = 0.1 act_layer = nn.GELU norm_layer = nn.LayerNorm use_chk = False upscale = 2 img_range = 1.0 resi_connection = "1conv" upsampler = "pixelshuffle" self.model_arch = "DAT" self.sub_type = "SR" self.state = state_dict state_keys = state_dict.keys() if "conv_before_upsample.0.weight" in state_keys: if "conv_up1.weight" in state_keys: upsampler = "nearest+conv" else: upsampler = "pixelshuffle" supports_fp16 = False elif "upsample.0.weight" in state_keys: upsampler = "pixelshuffledirect" else: upsampler = "" num_feat = ( state_dict.get("conv_before_upsample.0.weight", None).shape[1] if state_dict.get("conv_before_upsample.weight", None) else 64 ) num_in_ch = state_dict["conv_first.weight"].shape[1] in_chans = num_in_ch if "conv_last.weight" in state_keys: num_out_ch = state_dict["conv_last.weight"].shape[0] else: num_out_ch = num_in_ch upscale = 1 if upsampler == "nearest+conv": upsample_keys = [ x for x in state_keys if "conv_up" in x and "bias" not in x ] for upsample_key in upsample_keys: upscale *= 2 elif upsampler == "pixelshuffle": upsample_keys = [ x for x in state_keys if "upsample" in x and "conv" not in x and "bias" not in x ] for upsample_key in upsample_keys: shape = state_dict[upsample_key].shape[0] upscale *= math.sqrt(shape // num_feat) upscale = int(upscale) elif upsampler == "pixelshuffledirect": upscale = int( math.sqrt(state_dict["upsample.0.bias"].shape[0] // num_out_ch) ) max_layer_num = 0 max_block_num = 0 for key in state_keys: result = re.match(r"layers.(\d*).blocks.(\d*).norm1.weight", key) if result: layer_num, block_num = result.groups() max_layer_num = max(max_layer_num, int(layer_num)) max_block_num = max(max_block_num, int(block_num)) depth = [max_block_num + 1 for _ in range(max_layer_num + 1)] if "layers.0.blocks.1.attn.temperature" in state_keys: num_heads_num = state_dict["layers.0.blocks.1.attn.temperature"].shape[0] num_heads = [num_heads_num for _ in range(max_layer_num + 1)] else: num_heads = depth embed_dim = state_dict["conv_first.weight"].shape[0] expansion_factor = float( state_dict["layers.0.blocks.0.ffn.fc1.weight"].shape[0] / embed_dim ) # TODO: could actually count the layers, but this should do if "layers.0.conv.4.weight" in state_keys: resi_connection = "3conv" else: resi_connection = "1conv" if "layers.0.blocks.2.attn.attn_mask_0" in state_keys: attn_mask_0_x, attn_mask_0_y, attn_mask_0_z = state_dict[ "layers.0.blocks.2.attn.attn_mask_0" ].shape img_size = int(math.sqrt(attn_mask_0_x * attn_mask_0_y)) if "layers.0.blocks.0.attn.attns.0.rpe_biases" in state_keys: split_sizes = ( state_dict["layers.0.blocks.0.attn.attns.0.rpe_biases"][-1] + 1 ) split_size = [int(x) for x in split_sizes] self.in_nc = num_in_ch self.out_nc = num_out_ch self.num_feat = num_feat self.embed_dim = embed_dim self.num_heads = num_heads self.depth = depth self.scale = upscale self.upsampler = upsampler self.img_size = img_size self.img_range = img_range self.expansion_factor = expansion_factor self.resi_connection = resi_connection self.split_size = split_size self.supports_fp16 = False # Too much weirdness to support this at the moment self.supports_bfp16 = True self.min_size_restriction = 16 num_in_ch = in_chans num_out_ch = in_chans num_feat = 64 self.img_range = img_range if in_chans == 3: rgb_mean = (0.4488, 0.4371, 0.4040) self.mean = torch.Tensor(rgb_mean).view(1, 3, 1, 1) else: self.mean = torch.zeros(1, 1, 1, 1) self.upscale = upscale self.upsampler = upsampler # ------------------------- 1, Shallow Feature Extraction ------------------------- # self.conv_first = nn.Conv2d(num_in_ch, embed_dim, 3, 1, 1) # ------------------------- 2, Deep Feature Extraction ------------------------- # self.num_layers = len(depth) self.use_chk = use_chk self.num_features = ( self.embed_dim ) = embed_dim # num_features for consistency with other models heads = num_heads self.before_RG = nn.Sequential( Rearrange("b c h w -> b (h w) c"), nn.LayerNorm(embed_dim) ) curr_dim = embed_dim dpr = [ x.item() for x in torch.linspace(0, drop_path_rate, np.sum(depth)) ] # stochastic depth decay rule self.layers = nn.ModuleList() for i in range(self.num_layers): layer = ResidualGroup( dim=embed_dim, num_heads=heads[i], reso=img_size, split_size=split_size, expansion_factor=expansion_factor, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_paths=dpr[sum(depth[:i]) : sum(depth[: i + 1])], act_layer=act_layer, norm_layer=norm_layer, depth=depth[i], use_chk=use_chk, resi_connection=resi_connection, rg_idx=i, ) self.layers.append(layer) self.norm = norm_layer(curr_dim) # build the last conv layer in deep feature extraction if resi_connection == "1conv": self.conv_after_body = nn.Conv2d(embed_dim, embed_dim, 3, 1, 1) elif resi_connection == "3conv": # to save parameters and memory self.conv_after_body = nn.Sequential( nn.Conv2d(embed_dim, embed_dim // 4, 3, 1, 1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(embed_dim // 4, embed_dim // 4, 1, 1, 0), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(embed_dim // 4, embed_dim, 3, 1, 1), ) # ------------------------- 3, Reconstruction ------------------------- # if self.upsampler == "pixelshuffle": # for classical SR self.conv_before_upsample = nn.Sequential( nn.Conv2d(embed_dim, num_feat, 3, 1, 1), nn.LeakyReLU(inplace=True) ) self.upsample = Upsample(upscale, num_feat) self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1) elif self.upsampler == "pixelshuffledirect": # for lightweight SR (to save parameters) self.upsample = UpsampleOneStep( upscale, embed_dim, num_out_ch, (img_size, img_size) ) self.apply(self._init_weights) self.load_state_dict(state_dict, strict=True) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=0.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance( m, (nn.LayerNorm, nn.BatchNorm2d, nn.GroupNorm, nn.InstanceNorm2d) ): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) def forward_features(self, x): _, _, H, W = x.shape x_size = [H, W] x = self.before_RG(x) for layer in self.layers: x = layer(x, x_size) x = self.norm(x) x = rearrange(x, "b (h w) c -> b c h w", h=H, w=W) return x def forward(self, x): self.mean = self.mean.type_as(x) x = (x - self.mean) * self.img_range if self.upsampler == "pixelshuffle": # for image SR x = self.conv_first(x) x = self.conv_after_body(self.forward_features(x)) + x x = self.conv_before_upsample(x) x = self.conv_last(self.upsample(x)) elif self.upsampler == "pixelshuffledirect": # for lightweight SR x = self.conv_first(x) x = self.conv_after_body(self.forward_features(x)) + x x = self.upsample(x) x = x / self.img_range + self.mean return x
--- +++ @@ -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_hw, H_sp, W_sp, H, W): + """ + Input: Window Partition (B', N, C) + Output: Image (B, H, W, C) + """ B = int(img_splits_hw.shape[0] / (H * W / H_sp / W_sp)) img = img_splits_hw.view(B, H // H_sp, W // W_sp, H_sp, W_sp, -1) @@ -33,6 +41,10 @@ class SpatialGate(nn.Module): + """Spatial-Gate. + Args: + dim (int): Half of input channels. + """ def __init__(self, dim): super().__init__() @@ -56,6 +68,14 @@ class SGFN(nn.Module): + """Spatial-Gate Feed-Forward Network. + Args: + in_features (int): Number of input channels. + hidden_features (int | None): Number of hidden channels. Default: None + out_features (int | None): Number of output channels. Default: None + act_layer (nn.Module): Activation layer. Default: nn.GELU + drop (float): Dropout rate. Default: 0.0 + """ def __init__( self, @@ -75,6 +95,10 @@ self.drop = nn.Dropout(drop) def forward(self, x, H, W): + """ + Input: x: (B, H*W, C), H, W + Output: x: (B, H*W, C) + """ x = self.fc1(x) x = self.act(x) x = self.drop(x) @@ -89,6 +113,12 @@ class DynamicPosBias(nn.Module): # The implementation builds on Crossformer code https://github.com/cheerss/CrossFormer/blob/main/models/crossformer.py + """Dynamic Relative Position Bias. + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. + residual (bool): If True, use residual strage to connect conv. + """ def __init__(self, dim, num_heads, residual): super().__init__() @@ -124,6 +154,19 @@ class Spatial_Attention(nn.Module): + """Spatial Window Self-Attention. + It supports rectangle window (containing square window). + Args: + dim (int): Number of input channels. + idx (int): The indentix of window. (0/1) + split_size (tuple(int)): Height and Width of spatial window. + dim_out (int | None): The dimension of the attention output. Default: None + num_heads (int): Number of attention heads. Default: 6 + attn_drop (float): Dropout ratio of attention weight. Default: 0.0 + proj_drop (float): Dropout ratio of output. Default: 0.0 + qk_scale (float | None): Override default qk scale of head_dim ** -0.5 if set + position_bias (bool): The dynamic relative position bias. Default: True + """ def __init__( self, @@ -194,6 +237,10 @@ return x def forward(self, qkv, H, W, mask=None): + """ + Input: qkv: (B, 3*L, C), H, W, mask: (B, N, N), N is the window size + Output: x (B, H, W, C) + """ q, k, v = qkv[0], qkv[1], qkv[2] B, L, C = q.shape @@ -245,6 +292,19 @@ class Adaptive_Spatial_Attention(nn.Module): # The implementation builds on CAT code https://github.com/Zhengchen1999/CAT + """Adaptive Spatial Self-Attention + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. Default: 6 + split_size (tuple(int)): Height and Width of spatial window. + shift_size (tuple(int)): Shift size for spatial window. + qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None): Override default qk scale of head_dim ** -0.5 if set. + drop (float): Dropout rate. Default: 0.0 + attn_drop (float): Attention dropout rate. Default: 0.0 + rg_idx (int): The indentix of Residual Group (RG) + b_idx (int): The indentix of Block in each RG + """ def __init__( self, @@ -411,6 +471,10 @@ return attn_mask_0, attn_mask_1 def forward(self, x, H, W): + """ + Input: x: (B, H*W, C), H, W + Output: x: (B, H*W, C) + """ B, L, C = x.shape assert L == H * W, "flatten img_tokens has wrong size" @@ -513,6 +577,15 @@ class Adaptive_Channel_Attention(nn.Module): # The implementation builds on XCiT code https://github.com/facebookresearch/xcit + """Adaptive Channel Self-Attention + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. Default: 6 + qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None): Override default qk scale of head_dim ** -0.5 if set. + attn_drop (float): Attention dropout rate. Default: 0.0 + drop_path (float): Stochastic depth rate. Default: 0.0 + """ def __init__( self, @@ -552,6 +625,10 @@ ) def forward(self, x, H, W): + """ + Input: x: (B, H*W, C), H, W + Output: x: (B, H*W, C) + """ B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads) qkv = qkv.permute(2, 0, 3, 1, 4) @@ -662,6 +739,10 @@ self.norm2 = norm_layer(dim) def forward(self, x, x_size): + """ + Input: x: (B, H*W, C), x_size: (H, W) + Output: x: (B, H*W, C) + """ H, W = x_size x = x + self.drop_path(self.attn(self.norm1(x), H, W)) x = x + self.drop_path(self.ffn(self.norm2(x), H, W)) @@ -670,6 +751,24 @@ class ResidualGroup(nn.Module): + """ResidualGroup + Args: + dim (int): Number of input channels. + reso (int): Input resolution. + num_heads (int): Number of attention heads. + split_size (tuple(int)): Height and Width of spatial window. + expansion_factor (float): Ratio of ffn hidden dim to embedding dim. + qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None): Override default qk scale of head_dim ** -0.5 if set. Default: None + drop (float): Dropout rate. Default: 0 + attn_drop(float): Attention dropout rate. Default: 0 + drop_paths (float | None): Stochastic depth rate. + act_layer (nn.Module): Activation layer. Default: nn.GELU + norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm + depth (int): Number of dual aggregation Transformer blocks in residual group. + use_chk (bool): Whether to use checkpointing to save memory. + resi_connection: The convolutional block before residual connection. '1conv'/'3conv' + """ def __init__( self, @@ -729,6 +828,10 @@ ) def forward(self, x, x_size): + """ + Input: x: (B, H*W, C), x_size: (H, W) + Output: x: (B, H*W, C) + """ H, W = x_size res = x for blk in self.blocks: @@ -745,6 +848,11 @@ class Upsample(nn.Sequential): + """Upsample module. + Args: + scale (int): Scale factor. Supported scales: 2^n and 3. + num_feat (int): Channel number of intermediate features. + """ def __init__(self, scale, num_feat): m = [] @@ -763,6 +871,14 @@ class UpsampleOneStep(nn.Sequential): + """UpsampleOneStep module (the difference with Upsample is that it always only has 1conv + 1pixelshuffle) + Used in lightweight SR to save parameters. + + Args: + scale (int): Scale factor. Supported scales: 2^n and 3. + num_feat (int): Channel number of intermediate features. + + """ def __init__(self, scale, num_feat, num_out_ch, input_resolution=None): self.num_feat = num_feat @@ -779,6 +895,27 @@ class DAT(nn.Module): + """Dual Aggregation Transformer + Args: + img_size (int): Input image size. Default: 64 + in_chans (int): Number of input image channels. Default: 3 + embed_dim (int): Patch embedding dimension. Default: 180 + depths (tuple(int)): Depth of each residual group (number of DATB in each RG). + split_size (tuple(int)): Height and Width of spatial window. + num_heads (tuple(int)): Number of attention heads in different residual groups. + expansion_factor (float): Ratio of ffn hidden dim to embedding dim. Default: 4 + qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None): Override default qk scale of head_dim ** -0.5 if set. Default: None + drop_rate (float): Dropout rate. Default: 0 + attn_drop_rate (float): Attention dropout rate. Default: 0 + drop_path_rate (float): Stochastic depth rate. Default: 0.1 + act_layer (nn.Module): Activation layer. Default: nn.GELU + norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm + use_chk (bool): Whether to use checkpointing to save memory. + upscale: Upscale factor. 2/3/4 for image SR + img_range: Image range. 1. or 255. + resi_connection: The convolutional block before residual connection. '1conv'/'3conv' + """ def __init__(self, state_dict): super().__init__() @@ -1023,6 +1160,9 @@ return x def forward(self, x): + """ + Input: x: (B, C, H, W) + """ self.mean = self.mean.type_as(x) x = (x - self.mean) * self.img_range @@ -1039,4 +1179,4 @@ x = self.upsample(x) x = x / self.img_range + self.mean - return x+ return x
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 enhanced stuff that was already here class RRDBNet(nn.Module): def __init__( self, state_dict, norm=None, act: str = "leakyrelu", upsampler: str = "upconv", mode: B.ConvMode = "CNA", ) -> None: super(RRDBNet, self).__init__() self.model_arch = "ESRGAN" self.sub_type = "SR" self.state = state_dict self.norm = norm self.act = act self.upsampler = upsampler self.mode = mode self.state_map = { # currently supports old, new, and newer RRDBNet arch models # ESRGAN, BSRGAN/RealSR, Real-ESRGAN "model.0.weight": ("conv_first.weight",), "model.0.bias": ("conv_first.bias",), "model.1.sub./NB/.weight": ("trunk_conv.weight", "conv_body.weight"), "model.1.sub./NB/.bias": ("trunk_conv.bias", "conv_body.bias"), r"model.1.sub.\1.RDB\2.conv\3.0.\4": ( r"RRDB_trunk\.(\d+)\.RDB(\d)\.conv(\d+)\.(weight|bias)", r"body\.(\d+)\.rdb(\d)\.conv(\d+)\.(weight|bias)", ), } if "params_ema" in self.state: self.state = self.state["params_ema"] # self.model_arch = "RealESRGAN" self.num_blocks = self.get_num_blocks() self.plus = any("conv1x1" in k for k in self.state.keys()) if self.plus: self.model_arch = "ESRGAN+" self.state = self.new_to_old_arch(self.state) self.key_arr = list(self.state.keys()) self.in_nc: int = self.state[self.key_arr[0]].shape[1] self.out_nc: int = self.state[self.key_arr[-1]].shape[0] self.scale: int = self.get_scale() self.num_filters: int = self.state[self.key_arr[0]].shape[0] c2x2 = False if self.state["model.0.weight"].shape[-2] == 2: c2x2 = True self.scale = round(math.sqrt(self.scale / 4)) self.model_arch = "ESRGAN-2c2" self.supports_fp16 = True self.supports_bfp16 = True self.min_size_restriction = None # Detect if pixelunshuffle was used (Real-ESRGAN) if self.in_nc in (self.out_nc * 4, self.out_nc * 16) and self.out_nc in ( self.in_nc / 4, self.in_nc / 16, ): self.shuffle_factor = int(math.sqrt(self.in_nc / self.out_nc)) else: self.shuffle_factor = None upsample_block = { "upconv": B.upconv_block, "pixel_shuffle": B.pixelshuffle_block, }.get(self.upsampler) if upsample_block is None: raise NotImplementedError(f"Upsample mode [{self.upsampler}] is not found") if self.scale == 3: upsample_blocks = upsample_block( in_nc=self.num_filters, out_nc=self.num_filters, upscale_factor=3, act_type=self.act, c2x2=c2x2, ) else: upsample_blocks = [ upsample_block( in_nc=self.num_filters, out_nc=self.num_filters, act_type=self.act, c2x2=c2x2, ) for _ in range(int(math.log(self.scale, 2))) ] self.model = B.sequential( # fea conv B.conv_block( in_nc=self.in_nc, out_nc=self.num_filters, kernel_size=3, norm_type=None, act_type=None, c2x2=c2x2, ), B.ShortcutBlock( B.sequential( # rrdb blocks *[ B.RRDB( nf=self.num_filters, kernel_size=3, gc=32, stride=1, bias=True, pad_type="zero", norm_type=self.norm, act_type=self.act, mode="CNA", plus=self.plus, c2x2=c2x2, ) for _ in range(self.num_blocks) ], # lr conv B.conv_block( in_nc=self.num_filters, out_nc=self.num_filters, kernel_size=3, norm_type=self.norm, act_type=None, mode=self.mode, c2x2=c2x2, ), ) ), *upsample_blocks, # hr_conv0 B.conv_block( in_nc=self.num_filters, out_nc=self.num_filters, kernel_size=3, norm_type=None, act_type=self.act, c2x2=c2x2, ), # hr_conv1 B.conv_block( in_nc=self.num_filters, out_nc=self.out_nc, kernel_size=3, norm_type=None, act_type=None, c2x2=c2x2, ), ) # Adjust these properties for calculations outside of the model if self.shuffle_factor: self.in_nc //= self.shuffle_factor**2 self.scale //= self.shuffle_factor self.load_state_dict(self.state, strict=False) def new_to_old_arch(self, state): if "params_ema" in state: state = state["params_ema"] if "conv_first.weight" not in state: # model is already old arch, this is a loose check, but should be sufficient return state # add nb to state keys for kind in ("weight", "bias"): self.state_map[f"model.1.sub.{self.num_blocks}.{kind}"] = self.state_map[ f"model.1.sub./NB/.{kind}" ] del self.state_map[f"model.1.sub./NB/.{kind}"] old_state = OrderedDict() for old_key, new_keys in self.state_map.items(): for new_key in new_keys: if r"\1" in old_key: for k, v in state.items(): sub = re.sub(new_key, old_key, k) if sub != k: old_state[sub] = v else: if new_key in state: old_state[old_key] = state[new_key] # upconv layers max_upconv = 0 for key in state.keys(): match = re.match(r"(upconv|conv_up)(\d)\.(weight|bias)", key) if match is not None: _, key_num, key_type = match.groups() old_state[f"model.{int(key_num) * 3}.{key_type}"] = state[key] max_upconv = max(max_upconv, int(key_num) * 3) # final layers for key in state.keys(): if key in ("HRconv.weight", "conv_hr.weight"): old_state[f"model.{max_upconv + 2}.weight"] = state[key] elif key in ("HRconv.bias", "conv_hr.bias"): old_state[f"model.{max_upconv + 2}.bias"] = state[key] elif key in ("conv_last.weight",): old_state[f"model.{max_upconv + 4}.weight"] = state[key] elif key in ("conv_last.bias",): old_state[f"model.{max_upconv + 4}.bias"] = state[key] # Sort by first numeric value of each layer def compare(item1, item2): parts1 = item1.split(".") parts2 = item2.split(".") int1 = int(parts1[1]) int2 = int(parts2[1]) return int1 - int2 sorted_keys = sorted(old_state.keys(), key=functools.cmp_to_key(compare)) # Rebuild the output dict in the right order out_dict = OrderedDict((k, old_state[k]) for k in sorted_keys) return out_dict def get_scale(self, min_part: int = 6) -> int: n = 0 for part in list(self.state): parts = part.split(".")[1:] if len(parts) == 2: part_num = int(parts[0]) if part_num > min_part and parts[1] == "weight": n += 1 return 2**n def get_num_blocks(self) -> int: nbs = [] state_keys = self.state_map[r"model.1.sub.\1.RDB\2.conv\3.0.\4"] + ( r"model\.\d+\.sub\.(\d+)\.RDB(\d+)\.conv(\d+)\.0\.(weight|bias)", ) for state_key in state_keys: for k in self.state: m = re.search(state_key, k) if m: nbs.append(int(m.group(1))) if nbs: break return max(*nbs) + 1 def forward(self, x): if self.shuffle_factor: _, _, h, w = x.size() mod_pad_h = ( self.shuffle_factor - h % self.shuffle_factor ) % self.shuffle_factor mod_pad_w = ( self.shuffle_factor - w % self.shuffle_factor ) % self.shuffle_factor x = F.pad(x, (0, mod_pad_w, 0, mod_pad_h), "reflect") x = torch.pixel_unshuffle(x, downscale_factor=self.shuffle_factor) x = self.model(x) return x[:, :, : h * self.scale, : w * self.scale] return self.model(x)
--- +++ @@ -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. + This is old-arch Residual in Residual Dense Block Network and is not + the newest revision that's available at github.com/xinntao/ESRGAN. + This is on purpose, the newest Network has severely limited the + potential use of the Network with no benefits. + This network supports model files from both new and old-arch. + Args: + norm: Normalization layer + act: Activation layer + upsampler: Upsample layer. upconv, pixel_shuffle + mode: Convolution mode + """ super(RRDBNet, self).__init__() self.model_arch = "ESRGAN" self.sub_type = "SR" @@ -179,6 +194,7 @@ self.load_state_dict(self.state, strict=False) def new_to_old_arch(self, state): + """Convert a new-arch model state dictionary to an old-arch dictionary.""" if "params_ema" in state: state = state["params_ema"] @@ -277,4 +293,4 @@ x = torch.pixel_unshuffle(x, downscale_factor=self.shuffle_factor) x = self.model(x) return x[:, :, : h * self.scale, : w * self.scale] - return self.model(x)+ return self.model(x)
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 clipped_block_size = min(block_size, min(W, H)) # seed_drop_rate, the gamma parameter gamma = ( gamma_scale * drop_prob * total_size / clipped_block_size**2 / ((W - block_size + 1) * (H - block_size + 1)) ) # Forces the block to be inside the feature map. w_i, h_i = torch.meshgrid( torch.arange(W).to(x.device), torch.arange(H).to(x.device) ) valid_block = ( (w_i >= clipped_block_size // 2) & (w_i < W - (clipped_block_size - 1) // 2) ) & ((h_i >= clipped_block_size // 2) & (h_i < H - (clipped_block_size - 1) // 2)) valid_block = torch.reshape(valid_block, (1, 1, H, W)).to(dtype=x.dtype) if batchwise: # one mask for whole batch, quite a bit faster uniform_noise = torch.rand((1, C, H, W), dtype=x.dtype, device=x.device) else: uniform_noise = torch.rand_like(x) block_mask = ((2 - gamma - valid_block + uniform_noise) >= 1).to(dtype=x.dtype) block_mask = -F.max_pool2d( -block_mask, kernel_size=clipped_block_size, # block_size, stride=1, padding=clipped_block_size // 2, ) if with_noise: normal_noise = ( torch.randn((1, C, H, W), dtype=x.dtype, device=x.device) if batchwise else torch.randn_like(x) ) if inplace: x.mul_(block_mask).add_(normal_noise * (1 - block_mask)) else: x = x * block_mask + normal_noise * (1 - block_mask) else: normalize_scale = ( block_mask.numel() / block_mask.to(dtype=torch.float32).sum().add(1e-7) ).to(x.dtype) if inplace: x.mul_(block_mask * normalize_scale) else: x = x * block_mask * normalize_scale return x def drop_block_fast_2d( x: torch.Tensor, drop_prob: float = 0.1, block_size: int = 7, gamma_scale: float = 1.0, with_noise: bool = False, inplace: bool = False, ): _, _, H, W = x.shape total_size = W * H clipped_block_size = min(block_size, min(W, H)) gamma = ( gamma_scale * drop_prob * total_size / clipped_block_size**2 / ((W - block_size + 1) * (H - block_size + 1)) ) block_mask = torch.empty_like(x).bernoulli_(gamma) block_mask = F.max_pool2d( block_mask.to(x.dtype), kernel_size=clipped_block_size, stride=1, padding=clipped_block_size // 2, ) if with_noise: normal_noise = torch.empty_like(x).normal_() if inplace: x.mul_(1.0 - block_mask).add_(normal_noise * block_mask) else: x = x * (1.0 - block_mask) + normal_noise * block_mask else: block_mask = 1 - block_mask normalize_scale = ( block_mask.numel() / block_mask.to(dtype=torch.float32).sum().add(1e-6) ).to(dtype=x.dtype) if inplace: x.mul_(block_mask * normalize_scale) else: x = x * block_mask * normalize_scale return x class DropBlock2d(nn.Module): def __init__( self, drop_prob: float = 0.1, block_size: int = 7, gamma_scale: float = 1.0, with_noise: bool = False, inplace: bool = False, batchwise: bool = False, fast: bool = True, ): super(DropBlock2d, self).__init__() self.drop_prob = drop_prob self.gamma_scale = gamma_scale self.block_size = block_size self.with_noise = with_noise self.inplace = inplace self.batchwise = batchwise self.fast = fast # FIXME finish comparisons of fast vs not def forward(self, x): if not self.training or not self.drop_prob: return x if self.fast: return drop_block_fast_2d( x, self.drop_prob, self.block_size, self.gamma_scale, self.with_noise, self.inplace, ) else: return drop_block_2d( x, self.drop_prob, self.block_size, self.gamma_scale, self.with_noise, self.inplace, self.batchwise, ) def drop_path( x, drop_prob: float = 0.0, training: bool = False, scale_by_keep: bool = True ): if drop_prob == 0.0 or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0],) + (1,) * ( x.ndim - 1 ) # work with diff dim tensors, not just 2D ConvNets random_tensor = x.new_empty(shape).bernoulli_(keep_prob) if keep_prob > 0.0 and scale_by_keep: random_tensor.div_(keep_prob) return x * random_tensor class DropPath(nn.Module): def __init__(self, drop_prob: float = 0.0, scale_by_keep: bool = True): super(DropPath, self).__init__() self.drop_prob = drop_prob self.scale_by_keep = scale_by_keep def forward(self, x): return drop_path(x, self.drop_prob, self.training, self.scale_by_keep) def extra_repr(self): return f"drop_prob={round(self.drop_prob,3):0.3f}"
--- +++ @@ -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.09382) + +Code: +DropBlock impl inspired by two Tensorflow impl that I liked: + - https://github.com/tensorflow/tpu/blob/master/models/official/resnet/resnet_model.py#L74 + - https://github.com/clovaai/assembled-cnn/blob/master/nets/blocks.py + +Hacked together by / Copyright 2020 Ross Wightman +""" import torch import torch.nn as nn import torch.nn.functional as F @@ -12,6 +28,11 @@ inplace: bool = False, batchwise: bool = False, ): + """DropBlock. See https://arxiv.org/pdf/1810.12890.pdf + + DropBlock with an experimental gaussian noise option. This layer has been tested on a few training + runs with success, but needs further validation and possibly optimization for lower runtime impact. + """ _, C, H, W = x.shape total_size = W * H clipped_block_size = min(block_size, min(W, H)) @@ -75,6 +96,11 @@ with_noise: bool = False, inplace: bool = False, ): + """DropBlock. See https://arxiv.org/pdf/1810.12890.pdf + + DropBlock with an experimental gaussian noise option. Simplied from above without concern for valid + block mask at edges. + """ _, _, H, W = x.shape total_size = W * H clipped_block_size = min(block_size, min(W, H)) @@ -113,6 +139,7 @@ class DropBlock2d(nn.Module): + """DropBlock. See https://arxiv.org/pdf/1810.12890.pdf""" def __init__( self, @@ -160,6 +187,15 @@ def drop_path( x, drop_prob: float = 0.0, training: bool = False, scale_by_keep: bool = True ): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). + + This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, + the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... + See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for + changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use + 'survival rate' as the argument. + + """ if drop_prob == 0.0 or not training: return x keep_prob = 1 - drop_prob @@ -173,6 +209,7 @@ class DropPath(nn.Module): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).""" def __init__(self, drop_prob: float = 0.0, scale_by_keep: bool = True): super(DropPath, self).__init__() @@ -183,4 +220,4 @@ return drop_path(x, self.drop_prob, self.training, self.scale_by_keep) def extra_repr(self): - return f"drop_prob={round(self.drop_prob,3):0.3f}"+ return f"drop_prob={round(self.drop_prob,3):0.3f}"
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/truncated_normal.pdf def norm_cdf(x): # Computes standard normal cumulative distribution function return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0 if (mean < a - 2 * std) or (mean > b + 2 * std): warnings.warn( "mean is more than 2 std from [a, b] in nn.init.trunc_normal_. " "The distribution of values may be incorrect.", stacklevel=2, ) with torch.no_grad(): # Values are generated by using a truncated uniform distribution and # then using the inverse CDF for the normal distribution. # Get upper and lower cdf values l = norm_cdf((a - mean) / std) u = norm_cdf((b - mean) / std) # Uniformly fill tensor with values from [l, u], then translate to # [2l-1, 2u-1]. tensor.uniform_(2 * l - 1, 2 * u - 1) # Use inverse cdf transform for normal distribution to get truncated # standard normal tensor.erfinv_() # Transform to proper mean, std tensor.mul_(std * math.sqrt(2.0)) tensor.add_(mean) # Clamp to ensure it's in the proper range tensor.clamp_(min=a, max=b) return tensor def trunc_normal_( tensor: torch.Tensor, mean=0.0, std=1.0, a=-2.0, b=2.0 ) -> torch.Tensor: return _no_grad_trunc_normal_(tensor, mean, std, a, b) def trunc_normal_tf_( tensor: torch.Tensor, mean=0.0, std=1.0, a=-2.0, b=2.0 ) -> torch.Tensor: _no_grad_trunc_normal_(tensor, 0, 1.0, a, b) with torch.no_grad(): tensor.mul_(std).add_(mean) return tensor def variance_scaling_(tensor, scale=1.0, mode="fan_in", distribution="normal"): fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor) if mode == "fan_in": denom = fan_in elif mode == "fan_out": denom = fan_out elif mode == "fan_avg": denom = (fan_in + fan_out) / 2 variance = scale / denom # type: ignore if distribution == "truncated_normal": # constant is stddev of standard normal truncated to (-2, 2) trunc_normal_tf_(tensor, std=math.sqrt(variance) / 0.87962566103423978) elif distribution == "normal": tensor.normal_(std=math.sqrt(variance)) elif distribution == "uniform": bound = math.sqrt(3 * variance) # pylint: disable=invalid-unary-operand-type tensor.uniform_(-bound, bound) else: raise ValueError(f"invalid distribution {distribution}") def lecun_normal_(tensor): variance_scaling_(tensor, mode="fan_in", distribution="truncated_normal")
--- +++ @@ -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}, \text{std}^2)` + with values outside :math:`[a, b]` redrawn until they are within + the bounds. The method used for generating the random values works + best when :math:`a \leq \text{mean} \leq b`. + + NOTE: this impl is similar to the PyTorch trunc_normal_, the bounds [a, b] are + applied while sampling the normal with mean/std applied, therefore a, b args + should be adjusted to match the range of mean, std args. + + Args: + tensor: an n-dimensional `torch.Tensor` + mean: the mean of the normal distribution + std: the standard deviation of the normal distribution + a: the minimum cutoff value + b: the maximum cutoff value + Examples: + >>> w = torch.empty(3, 5) + >>> nn.init.trunc_normal_(w) + """ return _no_grad_trunc_normal_(tensor, mean, std, a, b) def trunc_normal_tf_( 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}, \text{std}^2)` + with values outside :math:`[a, b]` redrawn until they are within + the bounds. The method used for generating the random values works + best when :math:`a \leq \text{mean} \leq b`. + + NOTE: this 'tf' variant behaves closer to Tensorflow / JAX impl where the + bounds [a, b] are applied when sampling the normal distribution with mean=0, std=1.0 + and the result is subsquently scaled and shifted by the mean and std args. + + Args: + tensor: an n-dimensional `torch.Tensor` + mean: the mean of the normal distribution + std: the standard deviation of the normal distribution + a: the minimum cutoff value + b: the maximum cutoff value + Examples: + >>> w = torch.empty(3, 5) + >>> nn.init.trunc_normal_(w) + """ _no_grad_trunc_normal_(tensor, 0, 1.0, a, b) with torch.no_grad(): tensor.mul_(std).add_(mean) @@ -83,4 +125,4 @@ def lecun_normal_(tensor): - variance_scaling_(tensor, mode="fan_in", distribution="truncated_normal")+ variance_scaling_(tensor, mode="fan_in", distribution="truncated_normal")
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 StyleGAN2GeneratorBilinearSFT(StyleGAN2GeneratorBilinear): def __init__( self, out_size, num_style_feat=512, num_mlp=8, channel_multiplier=2, lr_mlp=0.01, narrow=1, sft_half=False, ): super(StyleGAN2GeneratorBilinearSFT, self).__init__( out_size, num_style_feat=num_style_feat, num_mlp=num_mlp, channel_multiplier=channel_multiplier, lr_mlp=lr_mlp, narrow=narrow, ) self.sft_half = sft_half def forward( self, styles, conditions, input_is_latent=False, noise=None, randomize_noise=True, truncation=1, truncation_latent=None, inject_index=None, return_latents=False, ): # style codes -> latents with Style MLP layer if not input_is_latent: styles = [self.style_mlp(s) for s in styles] # noises if noise is None: if randomize_noise: noise = [None] * self.num_layers # for each style conv layer else: # use the stored noise noise = [ getattr(self.noises, f"noise{i}") for i in range(self.num_layers) ] # style truncation if truncation < 1: style_truncation = [] for style in styles: style_truncation.append( truncation_latent + truncation * (style - truncation_latent) ) styles = style_truncation # get style latents with injection if len(styles) == 1: inject_index = self.num_latent if styles[0].ndim < 3: # repeat latent code for all the layers latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1) else: # used for encoder with different latent code for each layer latent = styles[0] elif len(styles) == 2: # mixing noises if inject_index is None: inject_index = random.randint(1, self.num_latent - 1) latent1 = styles[0].unsqueeze(1).repeat(1, inject_index, 1) latent2 = ( styles[1].unsqueeze(1).repeat(1, self.num_latent - inject_index, 1) ) latent = torch.cat([latent1, latent2], 1) # main generation out = self.constant_input(latent.shape[0]) out = self.style_conv1(out, latent[:, 0], noise=noise[0]) skip = self.to_rgb1(out, latent[:, 1]) i = 1 for conv1, conv2, noise1, noise2, to_rgb in zip( self.style_convs[::2], self.style_convs[1::2], noise[1::2], noise[2::2], self.to_rgbs, ): out = conv1(out, latent[:, i], noise=noise1) # the conditions may have fewer levels if i < len(conditions): # SFT part to combine the conditions if self.sft_half: # only apply SFT to half of the channels out_same, out_sft = torch.split(out, int(out.size(1) // 2), dim=1) out_sft = out_sft * conditions[i - 1] + conditions[i] out = torch.cat([out_same, out_sft], dim=1) else: # apply SFT to all the channels out = out * conditions[i - 1] + conditions[i] out = conv2(out, latent[:, i + 1], noise=noise2) skip = to_rgb(out, latent[:, i + 2], skip) # feature back to the rgb space i += 2 image = skip if return_latents: return image, latent else: return image, None class GFPGANBilinear(nn.Module): def __init__( self, out_size, num_style_feat=512, channel_multiplier=1, decoder_load_path=None, fix_decoder=True, # for stylegan decoder num_mlp=8, lr_mlp=0.01, input_is_latent=False, different_w=False, narrow=1, sft_half=False, ): super(GFPGANBilinear, self).__init__() self.input_is_latent = input_is_latent self.different_w = different_w self.num_style_feat = num_style_feat self.min_size_restriction = 512 unet_narrow = narrow * 0.5 # by default, use a half of input channels channels = { "4": int(512 * unet_narrow), "8": int(512 * unet_narrow), "16": int(512 * unet_narrow), "32": int(512 * unet_narrow), "64": int(256 * channel_multiplier * unet_narrow), "128": int(128 * channel_multiplier * unet_narrow), "256": int(64 * channel_multiplier * unet_narrow), "512": int(32 * channel_multiplier * unet_narrow), "1024": int(16 * channel_multiplier * unet_narrow), } self.log_size = int(math.log(out_size, 2)) first_out_size = 2 ** (int(math.log(out_size, 2))) self.conv_body_first = ConvLayer( 3, channels[f"{first_out_size}"], 1, bias=True, activate=True ) # downsample in_channels = channels[f"{first_out_size}"] self.conv_body_down = nn.ModuleList() for i in range(self.log_size, 2, -1): out_channels = channels[f"{2**(i - 1)}"] self.conv_body_down.append(ResBlock(in_channels, out_channels)) in_channels = out_channels self.final_conv = ConvLayer( in_channels, channels["4"], 3, bias=True, activate=True ) # upsample in_channels = channels["4"] self.conv_body_up = nn.ModuleList() for i in range(3, self.log_size + 1): out_channels = channels[f"{2**i}"] self.conv_body_up.append(ResUpBlock(in_channels, out_channels)) in_channels = out_channels # to RGB self.toRGB = nn.ModuleList() for i in range(3, self.log_size + 1): self.toRGB.append( EqualConv2d( channels[f"{2**i}"], 3, 1, stride=1, padding=0, bias=True, bias_init_val=0, ) ) if different_w: linear_out_channel = (int(math.log(out_size, 2)) * 2 - 2) * num_style_feat else: linear_out_channel = num_style_feat self.final_linear = EqualLinear( channels["4"] * 4 * 4, linear_out_channel, bias=True, bias_init_val=0, lr_mul=1, activation=None, ) # the decoder: stylegan2 generator with SFT modulations self.stylegan_decoder = StyleGAN2GeneratorBilinearSFT( out_size=out_size, num_style_feat=num_style_feat, num_mlp=num_mlp, channel_multiplier=channel_multiplier, lr_mlp=lr_mlp, narrow=narrow, sft_half=sft_half, ) # load pre-trained stylegan2 model if necessary if decoder_load_path: self.stylegan_decoder.load_state_dict( torch.load( decoder_load_path, map_location=lambda storage, loc: storage, weights_only=True)["params_ema"] ) # fix decoder without updating params if fix_decoder: for _, param in self.stylegan_decoder.named_parameters(): param.requires_grad = False # for SFT modulations (scale and shift) self.condition_scale = nn.ModuleList() self.condition_shift = nn.ModuleList() for i in range(3, self.log_size + 1): out_channels = channels[f"{2**i}"] if sft_half: sft_out_channels = out_channels else: sft_out_channels = out_channels * 2 self.condition_scale.append( nn.Sequential( EqualConv2d( out_channels, out_channels, 3, stride=1, padding=1, bias=True, bias_init_val=0, ), ScaledLeakyReLU(0.2), EqualConv2d( out_channels, sft_out_channels, 3, stride=1, padding=1, bias=True, bias_init_val=1, ), ) ) self.condition_shift.append( nn.Sequential( EqualConv2d( out_channels, out_channels, 3, stride=1, padding=1, bias=True, bias_init_val=0, ), ScaledLeakyReLU(0.2), EqualConv2d( out_channels, sft_out_channels, 3, stride=1, padding=1, bias=True, bias_init_val=0, ), ) ) def forward(self, x, return_latents=False, return_rgb=True, randomize_noise=True): conditions = [] unet_skips = [] out_rgbs = [] # encoder feat = self.conv_body_first(x) for i in range(self.log_size - 2): feat = self.conv_body_down[i](feat) unet_skips.insert(0, feat) feat = self.final_conv(feat) # style code style_code = self.final_linear(feat.view(feat.size(0), -1)) if self.different_w: style_code = style_code.view(style_code.size(0), -1, self.num_style_feat) # decode for i in range(self.log_size - 2): # add unet skip feat = feat + unet_skips[i] # ResUpLayer feat = self.conv_body_up[i](feat) # generate scale and shift for SFT layers scale = self.condition_scale[i](feat) conditions.append(scale.clone()) shift = self.condition_shift[i](feat) conditions.append(shift.clone()) # generate rgb images if return_rgb: out_rgbs.append(self.toRGB[i](feat)) # decoder image, _ = self.stylegan_decoder( [style_code], conditions, return_latents=return_latents, input_is_latent=self.input_is_latent, randomize_noise=randomize_noise, ) return image, out_rgbs
--- +++ @@ -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 converted to the clean version: StyleGAN2GeneratorCSFT. + Args: + out_size (int): The spatial size of outputs. + num_style_feat (int): Channel number of style features. Default: 512. + num_mlp (int): Layer number of MLP style layers. Default: 8. + channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2. + lr_mlp (float): Learning rate multiplier for mlp layers. Default: 0.01. + narrow (float): The narrow ratio for channels. Default: 1. + sft_half (bool): Whether to apply SFT on half of the input channels. Default: False. + """ def __init__( self, @@ -51,6 +63,18 @@ inject_index=None, return_latents=False, ): + """Forward function for StyleGAN2GeneratorBilinearSFT. + Args: + styles (list[Tensor]): Sample codes of styles. + conditions (list[Tensor]): SFT conditions to generators. + input_is_latent (bool): Whether input is latent style. Default: False. + noise (Tensor | None): Input noise or None. Default: None. + randomize_noise (bool): Randomize noise, used when 'noise' is False. Default: True. + truncation (float): The truncation ratio. Default: 1. + truncation_latent (Tensor | None): The truncation latent tensor. Default: None. + inject_index (int | None): The injection index for mixing noise. Default: None. + return_latents (bool): Whether to return style latents. Default: False. + """ # style codes -> latents with Style MLP layer if not input_is_latent: styles = [self.style_mlp(s) for s in styles] @@ -126,6 +150,23 @@ class GFPGANBilinear(nn.Module): + """The GFPGAN architecture: Unet + StyleGAN2 decoder with SFT. + It is the bilinear version and it does not use the complicated UpFirDnSmooth function that is not friendly for + deployment. It can be easily converted to the clean version: GFPGANv1Clean. + Ref: GFP-GAN: Towards Real-World Blind Face Restoration with Generative Facial Prior. + Args: + out_size (int): The spatial size of outputs. + num_style_feat (int): Channel number of style features. Default: 512. + channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2. + decoder_load_path (str): The path to the pre-trained decoder model (usually, the StyleGAN2). Default: None. + fix_decoder (bool): Whether to fix the decoder. Default: True. + num_mlp (int): Layer number of MLP style layers. Default: 8. + lr_mlp (float): Learning rate multiplier for mlp layers. Default: 0.01. + input_is_latent (bool): Whether input is latent style. Default: False. + different_w (bool): Whether to use different latent w for different layers. Default: False. + narrow (float): The narrow ratio for channels. Default: 1. + sft_half (bool): Whether to apply SFT on half of the input channels. Default: False. + """ def __init__( self, @@ -297,6 +338,13 @@ ) def forward(self, x, return_latents=False, return_rgb=True, randomize_noise=True): + """Forward function for GFPGANBilinear. + Args: + x (Tensor): Input images. + return_latents (bool): Whether to return style latents. Default: False. + return_rgb (bool): Whether return intermediate rgb images. Default: True. + randomize_noise (bool): Randomize noise, used when 'noise' is False. Default: True. + """ conditions = [] unet_skips = [] out_rgbs = [] @@ -338,4 +386,4 @@ randomize_noise=randomize_noise, ) - return image, out_rgbs+ return image, out_rgbs
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 nn.Conv3d(*args, **kwargs) raise ValueError(f"unsupported dimensions: {dims}") def avg_pool_nd(dims, *args, **kwargs): if dims == 1: return nn.AvgPool1d(*args, **kwargs) elif dims == 2: return nn.AvgPool2d(*args, **kwargs) elif dims == 3: return nn.AvgPool3d(*args, **kwargs) raise ValueError(f"unsupported dimensions: {dims}") class Downsample(nn.Module): def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.use_conv = use_conv self.dims = dims stride = 2 if dims != 3 else (1, 2, 2) if use_conv: self.op = conv_nd( dims, self.channels, self.out_channels, 3, stride=stride, padding=padding ) else: assert self.channels == self.out_channels self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride) def forward(self, x): assert x.shape[1] == self.channels if not self.use_conv: padding = [x.shape[2] % 2, x.shape[3] % 2] self.op.padding = padding x = self.op(x) return x class ResnetBlock(nn.Module): def __init__(self, in_c, out_c, down, ksize=3, sk=False, use_conv=True): super().__init__() ps = ksize // 2 if in_c != out_c or sk == False: self.in_conv = nn.Conv2d(in_c, out_c, ksize, 1, ps) else: # print('n_in') self.in_conv = None self.block1 = nn.Conv2d(out_c, out_c, 3, 1, 1) self.act = nn.ReLU() self.block2 = nn.Conv2d(out_c, out_c, ksize, 1, ps) if sk == False: self.skep = nn.Conv2d(in_c, out_c, ksize, 1, ps) else: self.skep = None self.down = down if self.down == True: self.down_opt = Downsample(in_c, use_conv=use_conv) def forward(self, x): if self.down == True: x = self.down_opt(x) if self.in_conv is not None: # edit x = self.in_conv(x) h = self.block1(x) h = self.act(h) h = self.block2(h) if self.skep is not None: return h + self.skep(x) else: return h + x class Adapter(nn.Module): def __init__(self, channels=[320, 640, 1280, 1280], nums_rb=3, cin=64, ksize=3, sk=False, use_conv=True, xl=True): super(Adapter, self).__init__() self.unshuffle_amount = 8 resblock_no_downsample = [] resblock_downsample = [3, 2, 1] self.xl = xl if self.xl: self.unshuffle_amount = 16 resblock_no_downsample = [1] resblock_downsample = [2] self.input_channels = cin // (self.unshuffle_amount * self.unshuffle_amount) self.unshuffle = nn.PixelUnshuffle(self.unshuffle_amount) self.channels = channels self.nums_rb = nums_rb self.body = [] for i in range(len(channels)): for j in range(nums_rb): if (i in resblock_downsample) and (j == 0): self.body.append( ResnetBlock(channels[i - 1], channels[i], down=True, ksize=ksize, sk=sk, use_conv=use_conv)) elif (i in resblock_no_downsample) and (j == 0): self.body.append( ResnetBlock(channels[i - 1], channels[i], down=False, ksize=ksize, sk=sk, use_conv=use_conv)) else: self.body.append( ResnetBlock(channels[i], channels[i], down=False, ksize=ksize, sk=sk, use_conv=use_conv)) self.body = nn.ModuleList(self.body) self.conv_in = nn.Conv2d(cin, channels[0], 3, 1, 1) def forward(self, x): # unshuffle x = self.unshuffle(x) # extract features features = [] x = self.conv_in(x) for i in range(len(self.channels)): for j in range(self.nums_rb): idx = i * self.nums_rb + j x = self.body[idx](x) if self.xl: features.append(None) if i == 0: features.append(None) features.append(None) if i == 2: features.append(None) else: features.append(None) features.append(None) features.append(x) return features class LayerNorm(nn.LayerNorm): def forward(self, x: torch.Tensor): orig_type = x.dtype ret = super().forward(x.type(torch.float32)) return ret.type(orig_type) class QuickGELU(nn.Module): def forward(self, x: torch.Tensor): return x * torch.sigmoid(1.702 * x) class ResidualAttentionBlock(nn.Module): def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None): super().__init__() self.attn = nn.MultiheadAttention(d_model, n_head) self.ln_1 = LayerNorm(d_model) self.mlp = nn.Sequential( OrderedDict([("c_fc", nn.Linear(d_model, d_model * 4)), ("gelu", QuickGELU()), ("c_proj", nn.Linear(d_model * 4, d_model))])) self.ln_2 = LayerNorm(d_model) self.attn_mask = attn_mask def attention(self, x: torch.Tensor): self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0] def forward(self, x: torch.Tensor): x = x + self.attention(self.ln_1(x)) x = x + self.mlp(self.ln_2(x)) return x class StyleAdapter(nn.Module): def __init__(self, width=1024, context_dim=768, num_head=8, n_layes=3, num_token=4): super().__init__() scale = width ** -0.5 self.transformer_layes = nn.Sequential(*[ResidualAttentionBlock(width, num_head) for _ in range(n_layes)]) self.num_token = num_token self.style_embedding = nn.Parameter(torch.randn(1, num_token, width) * scale) self.ln_post = LayerNorm(width) self.ln_pre = LayerNorm(width) self.proj = nn.Parameter(scale * torch.randn(width, context_dim)) def forward(self, x): # x shape [N, HW+1, C] style_embedding = self.style_embedding + torch.zeros( (x.shape[0], self.num_token, self.style_embedding.shape[-1]), device=x.device) x = torch.cat([x, style_embedding], dim=1) x = self.ln_pre(x) x = x.permute(1, 0, 2) # NLD -> LND x = self.transformer_layes(x) x = x.permute(1, 0, 2) # LND -> NLD x = self.ln_post(x[:, -self.num_token:, :]) x = x @ self.proj return x class ResnetBlock_light(nn.Module): def __init__(self, in_c): super().__init__() self.block1 = nn.Conv2d(in_c, in_c, 3, 1, 1) self.act = nn.ReLU() self.block2 = nn.Conv2d(in_c, in_c, 3, 1, 1) def forward(self, x): h = self.block1(x) h = self.act(h) h = self.block2(h) return h + x class extractor(nn.Module): def __init__(self, in_c, inter_c, out_c, nums_rb, down=False): super().__init__() self.in_conv = nn.Conv2d(in_c, inter_c, 1, 1, 0) self.body = [] for _ in range(nums_rb): self.body.append(ResnetBlock_light(inter_c)) self.body = nn.Sequential(*self.body) self.out_conv = nn.Conv2d(inter_c, out_c, 1, 1, 0) self.down = down if self.down == True: self.down_opt = Downsample(in_c, use_conv=False) def forward(self, x): if self.down == True: x = self.down_opt(x) x = self.in_conv(x) x = self.body(x) x = self.out_conv(x) return x class Adapter_light(nn.Module): def __init__(self, channels=[320, 640, 1280, 1280], nums_rb=3, cin=64): super(Adapter_light, self).__init__() self.unshuffle_amount = 8 self.unshuffle = nn.PixelUnshuffle(self.unshuffle_amount) self.input_channels = cin // (self.unshuffle_amount * self.unshuffle_amount) self.channels = channels self.nums_rb = nums_rb self.body = [] self.xl = False for i in range(len(channels)): if i == 0: self.body.append(extractor(in_c=cin, inter_c=channels[i]//4, out_c=channels[i], nums_rb=nums_rb, down=False)) else: self.body.append(extractor(in_c=channels[i-1], inter_c=channels[i]//4, out_c=channels[i], nums_rb=nums_rb, down=True)) self.body = nn.ModuleList(self.body) def forward(self, x): # unshuffle x = self.unshuffle(x) # extract features features = [] for i in range(len(self.channels)): x = self.body[i](x) features.append(None) features.append(None) features.append(x) return features
--- +++ @@ -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 pooling module. + """ if dims == 1: return nn.AvgPool1d(*args, **kwargs) elif dims == 2: @@ -25,6 +31,13 @@ class Downsample(nn.Module): + """ + A downsampling layer with an optional convolution. + :param channels: channels in the inputs and outputs. + :param use_conv: a bool determining if a convolution is applied. + :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then + downsampling occurs in the inner-two dimensions. + """ def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1): super().__init__() @@ -144,6 +157,7 @@ class LayerNorm(nn.LayerNorm): + """Subclass torch's LayerNorm to handle fp16.""" def forward(self, x: torch.Tensor): orig_type = x.dtype @@ -276,4 +290,4 @@ features.append(None) features.append(x) - return features+ return features
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/swin2sr/main/models/network_swin2sr.py # ----------------------------------------------------------------------------------- import math import re import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint # Originally from the timm package from .timm.drop import DropPath from .timm.helpers import to_2tuple from .timm.weight_init import trunc_normal_ class Mlp(nn.Module): def __init__( self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0, ): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop) def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x def window_partition(x, window_size): B, H, W, C = x.shape x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) windows = ( x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) ) return windows def window_reverse(windows, window_size, H, W): B = int(windows.shape[0] / (H * W / window_size / window_size)) x = windows.view( B, H // window_size, W // window_size, window_size, window_size, -1 ) x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) return x class WindowAttention(nn.Module): def __init__( self, dim, window_size, num_heads, qkv_bias=True, attn_drop=0.0, proj_drop=0.0, pretrained_window_size=[0, 0], ): super().__init__() self.dim = dim self.window_size = window_size # Wh, Ww self.pretrained_window_size = pretrained_window_size self.num_heads = num_heads self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1))), requires_grad=True) # type: ignore # mlp to generate continuous relative position bias self.cpb_mlp = nn.Sequential( nn.Linear(2, 512, bias=True), nn.ReLU(inplace=True), nn.Linear(512, num_heads, bias=False), ) # get relative_coords_table relative_coords_h = torch.arange( -(self.window_size[0] - 1), self.window_size[0], dtype=torch.float32 ) relative_coords_w = torch.arange( -(self.window_size[1] - 1), self.window_size[1], dtype=torch.float32 ) relative_coords_table = ( torch.stack(torch.meshgrid([relative_coords_h, relative_coords_w])) .permute(1, 2, 0) .contiguous() .unsqueeze(0) ) # 1, 2*Wh-1, 2*Ww-1, 2 if pretrained_window_size[0] > 0: relative_coords_table[:, :, :, 0] /= pretrained_window_size[0] - 1 relative_coords_table[:, :, :, 1] /= pretrained_window_size[1] - 1 else: relative_coords_table[:, :, :, 0] /= self.window_size[0] - 1 relative_coords_table[:, :, :, 1] /= self.window_size[1] - 1 relative_coords_table *= 8 # normalize to -8, 8 relative_coords_table = ( torch.sign(relative_coords_table) * torch.log2(torch.abs(relative_coords_table) + 1.0) / np.log2(8) ) self.register_buffer("relative_coords_table", relative_coords_table) # get pair-wise relative position index for each token inside the window coords_h = torch.arange(self.window_size[0]) coords_w = torch.arange(self.window_size[1]) coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww relative_coords = ( coords_flatten[:, :, None] - coords_flatten[:, None, :] ) # 2, Wh*Ww, Wh*Ww relative_coords = relative_coords.permute( 1, 2, 0 ).contiguous() # Wh*Ww, Wh*Ww, 2 relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 relative_coords[:, :, 1] += self.window_size[1] - 1 relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww self.register_buffer("relative_position_index", relative_position_index) self.qkv = nn.Linear(dim, dim * 3, bias=False) if qkv_bias: self.q_bias = nn.Parameter(torch.zeros(dim)) # type: ignore self.v_bias = nn.Parameter(torch.zeros(dim)) # type: ignore else: self.q_bias = None self.v_bias = None self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) self.softmax = nn.Softmax(dim=-1) def forward(self, x, mask=None): B_, N, C = x.shape qkv_bias = None if self.q_bias is not None: qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias)) # type: ignore qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias) qkv = qkv.reshape(B_, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) q, k, v = ( qkv[0], qkv[1], qkv[2], ) # make torchscript happy (cannot use tensor as tuple) # cosine attention attn = F.normalize(q, dim=-1) @ F.normalize(k, dim=-1).transpose(-2, -1) logit_scale = torch.clamp( self.logit_scale, max=torch.log(torch.tensor(1.0 / 0.01)).to(self.logit_scale.device), ).exp() attn = attn * logit_scale relative_position_bias_table = self.cpb_mlp(self.relative_coords_table).view( -1, self.num_heads ) relative_position_bias = relative_position_bias_table[self.relative_position_index.view(-1)].view( # type: ignore self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1, ) # Wh*Ww,Wh*Ww,nH relative_position_bias = relative_position_bias.permute( 2, 0, 1 ).contiguous() # nH, Wh*Ww, Wh*Ww relative_position_bias = 16 * torch.sigmoid(relative_position_bias) attn = attn + relative_position_bias.unsqueeze(0) if mask is not None: nW = mask.shape[0] attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze( 1 ).unsqueeze(0) attn = attn.view(-1, self.num_heads, N, N) attn = self.softmax(attn) else: attn = self.softmax(attn) attn = self.attn_drop(attn) x = (attn @ v).transpose(1, 2).reshape(B_, N, C) x = self.proj(x) x = self.proj_drop(x) return x def extra_repr(self) -> str: return ( f"dim={self.dim}, window_size={self.window_size}, " f"pretrained_window_size={self.pretrained_window_size}, num_heads={self.num_heads}" ) def flops(self, N): # calculate flops for 1 window with token length of N flops = 0 # qkv = self.qkv(x) flops += N * self.dim * 3 * self.dim # attn = (q @ k.transpose(-2, -1)) flops += self.num_heads * N * (self.dim // self.num_heads) * N # x = (attn @ v) flops += self.num_heads * N * N * (self.dim // self.num_heads) # x = self.proj(x) flops += N * self.dim * self.dim return flops class SwinTransformerBlock(nn.Module): def __init__( self, dim, input_resolution, num_heads, window_size=7, shift_size=0, mlp_ratio=4.0, qkv_bias=True, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm, pretrained_window_size=0, ): super().__init__() self.dim = dim self.input_resolution = input_resolution self.num_heads = num_heads self.window_size = window_size self.shift_size = shift_size self.mlp_ratio = mlp_ratio if min(self.input_resolution) <= self.window_size: # if window size is larger than input resolution, we don't partition windows self.shift_size = 0 self.window_size = min(self.input_resolution) assert ( 0 <= self.shift_size < self.window_size ), "shift_size must in 0-window_size" self.norm1 = norm_layer(dim) self.attn = WindowAttention( dim, window_size=to_2tuple(self.window_size), num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop, pretrained_window_size=to_2tuple(pretrained_window_size), ) self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp( in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop, ) if self.shift_size > 0: attn_mask = self.calculate_mask(self.input_resolution) else: attn_mask = None self.register_buffer("attn_mask", attn_mask) def calculate_mask(self, x_size): # calculate attention mask for SW-MSA H, W = x_size img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1 h_slices = ( slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None), ) w_slices = ( slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None), ) cnt = 0 for h in h_slices: for w in w_slices: img_mask[:, h, w, :] = cnt cnt += 1 mask_windows = window_partition( img_mask, self.window_size ) # nW, window_size, window_size, 1 mask_windows = mask_windows.view(-1, self.window_size * self.window_size) attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill( attn_mask == 0, float(0.0) ) return attn_mask def forward(self, x, x_size): H, W = x_size B, L, C = x.shape # assert L == H * W, "input feature has wrong size" shortcut = x x = x.view(B, H, W, C) # cyclic shift if self.shift_size > 0: shifted_x = torch.roll( x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2) ) else: shifted_x = x # partition windows x_windows = window_partition( shifted_x, self.window_size ) # nW*B, window_size, window_size, C x_windows = x_windows.view( -1, self.window_size * self.window_size, C ) # nW*B, window_size*window_size, C # W-MSA/SW-MSA (to be compatible for testing on images whose shapes are the multiple of window size if self.input_resolution == x_size: attn_windows = self.attn( x_windows, mask=self.attn_mask ) # nW*B, window_size*window_size, C else: attn_windows = self.attn( x_windows, mask=self.calculate_mask(x_size).to(x.device) ) # merge windows attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C # reverse cyclic shift if self.shift_size > 0: x = torch.roll( shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2) ) else: x = shifted_x x = x.view(B, H * W, C) x = shortcut + self.drop_path(self.norm1(x)) # FFN x = x + self.drop_path(self.norm2(self.mlp(x))) return x def extra_repr(self) -> str: return ( f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}" ) def flops(self): flops = 0 H, W = self.input_resolution # norm1 flops += self.dim * H * W # W-MSA/SW-MSA nW = H * W / self.window_size / self.window_size flops += nW * self.attn.flops(self.window_size * self.window_size) # mlp flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio # norm2 flops += self.dim * H * W return flops class PatchMerging(nn.Module): def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm): super().__init__() self.input_resolution = input_resolution self.dim = dim self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) self.norm = norm_layer(2 * dim) def forward(self, x): H, W = self.input_resolution B, L, C = x.shape assert L == H * W, "input feature has wrong size" assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even." x = x.view(B, H, W, C) x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C x = self.reduction(x) x = self.norm(x) return x def extra_repr(self) -> str: return f"input_resolution={self.input_resolution}, dim={self.dim}" def flops(self): H, W = self.input_resolution flops = (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim flops += H * W * self.dim // 2 return flops class BasicLayer(nn.Module): def __init__( self, dim, input_resolution, depth, num_heads, window_size, mlp_ratio=4.0, qkv_bias=True, drop=0.0, attn_drop=0.0, drop_path=0.0, norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False, pretrained_window_size=0, ): super().__init__() self.dim = dim self.input_resolution = input_resolution self.depth = depth self.use_checkpoint = use_checkpoint # build blocks self.blocks = nn.ModuleList( [ SwinTransformerBlock( dim=dim, input_resolution=input_resolution, num_heads=num_heads, window_size=window_size, shift_size=0 if (i % 2 == 0) else window_size // 2, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop=drop, attn_drop=attn_drop, drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, norm_layer=norm_layer, pretrained_window_size=pretrained_window_size, ) for i in range(depth) ] ) # patch merging layer if downsample is not None: self.downsample = downsample( input_resolution, dim=dim, norm_layer=norm_layer ) else: self.downsample = None def forward(self, x, x_size): for blk in self.blocks: if self.use_checkpoint: x = checkpoint.checkpoint(blk, x, x_size) else: x = blk(x, x_size) if self.downsample is not None: x = self.downsample(x) return x def extra_repr(self) -> str: return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}" def flops(self): flops = 0 for blk in self.blocks: flops += blk.flops() # type: ignore if self.downsample is not None: flops += self.downsample.flops() return flops def _init_respostnorm(self): for blk in self.blocks: nn.init.constant_(blk.norm1.bias, 0) # type: ignore nn.init.constant_(blk.norm1.weight, 0) # type: ignore nn.init.constant_(blk.norm2.bias, 0) # type: ignore nn.init.constant_(blk.norm2.weight, 0) # type: ignore class PatchEmbed(nn.Module): def __init__( self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None ): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]] # type: ignore self.img_size = img_size self.patch_size = patch_size self.patches_resolution = patches_resolution self.num_patches = patches_resolution[0] * patches_resolution[1] self.in_chans = in_chans self.embed_dim = embed_dim self.proj = nn.Conv2d( in_chans, embed_dim, kernel_size=patch_size, stride=patch_size # type: ignore ) if norm_layer is not None: self.norm = norm_layer(embed_dim) else: self.norm = None def forward(self, x): B, C, H, W = x.shape # FIXME look at relaxing size constraints # assert H == self.img_size[0] and W == self.img_size[1], # f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." x = self.proj(x).flatten(2).transpose(1, 2) # B Ph*Pw C if self.norm is not None: x = self.norm(x) return x def flops(self): Ho, Wo = self.patches_resolution flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1]) # type: ignore if self.norm is not None: flops += Ho * Wo * self.embed_dim return flops class RSTB(nn.Module): def __init__( self, dim, input_resolution, depth, num_heads, window_size, mlp_ratio=4.0, qkv_bias=True, drop=0.0, attn_drop=0.0, drop_path=0.0, norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False, img_size=224, patch_size=4, resi_connection="1conv", ): super(RSTB, self).__init__() self.dim = dim self.input_resolution = input_resolution self.residual_group = BasicLayer( dim=dim, input_resolution=input_resolution, depth=depth, num_heads=num_heads, window_size=window_size, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop=drop, attn_drop=attn_drop, drop_path=drop_path, norm_layer=norm_layer, downsample=downsample, use_checkpoint=use_checkpoint, ) if resi_connection == "1conv": self.conv = nn.Conv2d(dim, dim, 3, 1, 1) elif resi_connection == "3conv": # to save parameters and memory self.conv = nn.Sequential( nn.Conv2d(dim, dim // 4, 3, 1, 1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(dim // 4, dim // 4, 1, 1, 0), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(dim // 4, dim, 3, 1, 1), ) self.patch_embed = PatchEmbed( img_size=img_size, patch_size=patch_size, in_chans=dim, embed_dim=dim, norm_layer=None, ) self.patch_unembed = PatchUnEmbed( img_size=img_size, patch_size=patch_size, in_chans=dim, embed_dim=dim, norm_layer=None, ) def forward(self, x, x_size): return ( self.patch_embed( self.conv(self.patch_unembed(self.residual_group(x, x_size), x_size)) ) + x ) def flops(self): flops = 0 flops += self.residual_group.flops() H, W = self.input_resolution flops += H * W * self.dim * self.dim * 9 flops += self.patch_embed.flops() flops += self.patch_unembed.flops() return flops class PatchUnEmbed(nn.Module): def __init__( self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None ): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]] # type: ignore self.img_size = img_size self.patch_size = patch_size self.patches_resolution = patches_resolution self.num_patches = patches_resolution[0] * patches_resolution[1] self.in_chans = in_chans self.embed_dim = embed_dim def forward(self, x, x_size): B, HW, C = x.shape x = x.transpose(1, 2).view(B, self.embed_dim, x_size[0], x_size[1]) # B Ph*Pw C return x def flops(self): flops = 0 return flops class Upsample(nn.Sequential): def __init__(self, scale, num_feat): m = [] if (scale & (scale - 1)) == 0: # scale = 2^n for _ in range(int(math.log(scale, 2))): m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1)) m.append(nn.PixelShuffle(2)) elif scale == 3: m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1)) m.append(nn.PixelShuffle(3)) else: raise ValueError( f"scale {scale} is not supported. " "Supported scales: 2^n and 3." ) super(Upsample, self).__init__(*m) class Upsample_hf(nn.Sequential): def __init__(self, scale, num_feat): m = [] if (scale & (scale - 1)) == 0: # scale = 2^n for _ in range(int(math.log(scale, 2))): m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1)) m.append(nn.PixelShuffle(2)) elif scale == 3: m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1)) m.append(nn.PixelShuffle(3)) else: raise ValueError( f"scale {scale} is not supported. " "Supported scales: 2^n and 3." ) super(Upsample_hf, self).__init__(*m) class UpsampleOneStep(nn.Sequential): def __init__(self, scale, num_feat, num_out_ch, input_resolution=None): self.num_feat = num_feat self.input_resolution = input_resolution m = [] m.append(nn.Conv2d(num_feat, (scale**2) * num_out_ch, 3, 1, 1)) m.append(nn.PixelShuffle(scale)) super(UpsampleOneStep, self).__init__(*m) def flops(self): H, W = self.input_resolution # type: ignore flops = H * W * self.num_feat * 3 * 9 return flops class Swin2SR(nn.Module): def __init__( self, state_dict, **kwargs, ): super(Swin2SR, self).__init__() # Defaults img_size = 128 patch_size = 1 in_chans = 3 embed_dim = 96 depths = [6, 6, 6, 6] num_heads = [6, 6, 6, 6] window_size = 7 mlp_ratio = 4.0 qkv_bias = True drop_rate = 0.0 attn_drop_rate = 0.0 drop_path_rate = 0.1 norm_layer = nn.LayerNorm ape = False patch_norm = True use_checkpoint = False upscale = 2 img_range = 1.0 upsampler = "" resi_connection = "1conv" num_in_ch = in_chans num_out_ch = in_chans num_feat = 64 self.model_arch = "Swin2SR" self.sub_type = "SR" self.state = state_dict if "params_ema" in self.state: self.state = self.state["params_ema"] elif "params" in self.state: self.state = self.state["params"] state_keys = self.state.keys() if "conv_before_upsample.0.weight" in state_keys: if "conv_aux.weight" in state_keys: upsampler = "pixelshuffle_aux" elif "conv_up1.weight" in state_keys: upsampler = "nearest+conv" else: upsampler = "pixelshuffle" supports_fp16 = False elif "upsample.0.weight" in state_keys: upsampler = "pixelshuffledirect" else: upsampler = "" num_feat = ( self.state.get("conv_before_upsample.0.weight", None).shape[1] if self.state.get("conv_before_upsample.weight", None) else 64 ) num_in_ch = self.state["conv_first.weight"].shape[1] in_chans = num_in_ch if "conv_last.weight" in state_keys: num_out_ch = self.state["conv_last.weight"].shape[0] else: num_out_ch = num_in_ch upscale = 1 if upsampler == "nearest+conv": upsample_keys = [ x for x in state_keys if "conv_up" in x and "bias" not in x ] for upsample_key in upsample_keys: upscale *= 2 elif upsampler == "pixelshuffle" or upsampler == "pixelshuffle_aux": upsample_keys = [ x for x in state_keys if "upsample" in x and "conv" not in x and "bias" not in x ] for upsample_key in upsample_keys: shape = self.state[upsample_key].shape[0] upscale *= math.sqrt(shape // num_feat) upscale = int(upscale) elif upsampler == "pixelshuffledirect": upscale = int( math.sqrt(self.state["upsample.0.bias"].shape[0] // num_out_ch) ) max_layer_num = 0 max_block_num = 0 for key in state_keys: result = re.match( r"layers.(\d*).residual_group.blocks.(\d*).norm1.weight", key ) if result: layer_num, block_num = result.groups() max_layer_num = max(max_layer_num, int(layer_num)) max_block_num = max(max_block_num, int(block_num)) depths = [max_block_num + 1 for _ in range(max_layer_num + 1)] if ( "layers.0.residual_group.blocks.0.attn.relative_position_bias_table" in state_keys ): num_heads_num = self.state[ "layers.0.residual_group.blocks.0.attn.relative_position_bias_table" ].shape[-1] num_heads = [num_heads_num for _ in range(max_layer_num + 1)] else: num_heads = depths embed_dim = self.state["conv_first.weight"].shape[0] mlp_ratio = float( self.state["layers.0.residual_group.blocks.0.mlp.fc1.bias"].shape[0] / embed_dim ) # TODO: could actually count the layers, but this should do if "layers.0.conv.4.weight" in state_keys: resi_connection = "3conv" else: resi_connection = "1conv" window_size = int( math.sqrt( self.state[ "layers.0.residual_group.blocks.0.attn.relative_position_index" ].shape[0] ) ) if "layers.0.residual_group.blocks.1.attn_mask" in state_keys: img_size = int( math.sqrt( self.state["layers.0.residual_group.blocks.1.attn_mask"].shape[0] ) * window_size ) # The JPEG models are the only ones with window-size 7, and they also use this range img_range = 255.0 if window_size == 7 else 1.0 self.in_nc = num_in_ch self.out_nc = num_out_ch self.num_feat = num_feat self.embed_dim = embed_dim self.num_heads = num_heads self.depths = depths self.window_size = window_size self.mlp_ratio = mlp_ratio self.scale = upscale self.upsampler = upsampler self.img_size = img_size self.img_range = img_range self.resi_connection = resi_connection self.supports_fp16 = False # Too much weirdness to support this at the moment self.supports_bfp16 = True self.min_size_restriction = 16 ## END AUTO DETECTION if in_chans == 3: rgb_mean = (0.4488, 0.4371, 0.4040) self.mean = torch.Tensor(rgb_mean).view(1, 3, 1, 1) else: self.mean = torch.zeros(1, 1, 1, 1) self.upscale = upscale self.upsampler = upsampler self.window_size = window_size ##################################################################################################### ################################### 1, shallow feature extraction ################################### self.conv_first = nn.Conv2d(num_in_ch, embed_dim, 3, 1, 1) ##################################################################################################### ################################### 2, deep feature extraction ###################################### self.num_layers = len(depths) self.embed_dim = embed_dim self.ape = ape self.patch_norm = patch_norm self.num_features = embed_dim self.mlp_ratio = mlp_ratio # split image into non-overlapping patches self.patch_embed = PatchEmbed( img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim, norm_layer=norm_layer if self.patch_norm else None, ) num_patches = self.patch_embed.num_patches patches_resolution = self.patch_embed.patches_resolution self.patches_resolution = patches_resolution # merge non-overlapping patches into image self.patch_unembed = PatchUnEmbed( img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim, norm_layer=norm_layer if self.patch_norm else None, ) # absolute position embedding if self.ape: self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim)) # type: ignore trunc_normal_(self.absolute_pos_embed, std=0.02) self.pos_drop = nn.Dropout(p=drop_rate) # stochastic depth dpr = [ x.item() for x in torch.linspace(0, drop_path_rate, sum(depths)) ] # stochastic depth decay rule # build Residual Swin Transformer blocks (RSTB) self.layers = nn.ModuleList() for i_layer in range(self.num_layers): layer = RSTB( dim=embed_dim, input_resolution=(patches_resolution[0], patches_resolution[1]), depth=depths[i_layer], num_heads=num_heads[i_layer], window_size=window_size, mlp_ratio=self.mlp_ratio, qkv_bias=qkv_bias, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[sum(depths[:i_layer]) : sum(depths[: i_layer + 1])], # type: ignore # no impact on SR results norm_layer=norm_layer, downsample=None, use_checkpoint=use_checkpoint, img_size=img_size, patch_size=patch_size, resi_connection=resi_connection, ) self.layers.append(layer) if self.upsampler == "pixelshuffle_hf": self.layers_hf = nn.ModuleList() for i_layer in range(self.num_layers): layer = RSTB( dim=embed_dim, input_resolution=(patches_resolution[0], patches_resolution[1]), depth=depths[i_layer], num_heads=num_heads[i_layer], window_size=window_size, mlp_ratio=self.mlp_ratio, qkv_bias=qkv_bias, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[sum(depths[:i_layer]) : sum(depths[: i_layer + 1])], # type: ignore # no impact on SR results # type: ignore norm_layer=norm_layer, downsample=None, use_checkpoint=use_checkpoint, img_size=img_size, patch_size=patch_size, resi_connection=resi_connection, ) self.layers_hf.append(layer) self.norm = norm_layer(self.num_features) # build the last conv layer in deep feature extraction if resi_connection == "1conv": self.conv_after_body = nn.Conv2d(embed_dim, embed_dim, 3, 1, 1) elif resi_connection == "3conv": # to save parameters and memory self.conv_after_body = nn.Sequential( nn.Conv2d(embed_dim, embed_dim // 4, 3, 1, 1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(embed_dim // 4, embed_dim // 4, 1, 1, 0), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(embed_dim // 4, embed_dim, 3, 1, 1), ) ##################################################################################################### ################################ 3, high quality image reconstruction ################################ if self.upsampler == "pixelshuffle": # for classical SR self.conv_before_upsample = nn.Sequential( nn.Conv2d(embed_dim, num_feat, 3, 1, 1), nn.LeakyReLU(inplace=True) ) self.upsample = Upsample(upscale, num_feat) self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1) elif self.upsampler == "pixelshuffle_aux": self.conv_bicubic = nn.Conv2d(num_in_ch, num_feat, 3, 1, 1) self.conv_before_upsample = nn.Sequential( nn.Conv2d(embed_dim, num_feat, 3, 1, 1), nn.LeakyReLU(inplace=True) ) self.conv_aux = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1) self.conv_after_aux = nn.Sequential( nn.Conv2d(3, num_feat, 3, 1, 1), nn.LeakyReLU(inplace=True) ) self.upsample = Upsample(upscale, num_feat) self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1) elif self.upsampler == "pixelshuffle_hf": self.conv_before_upsample = nn.Sequential( nn.Conv2d(embed_dim, num_feat, 3, 1, 1), nn.LeakyReLU(inplace=True) ) self.upsample = Upsample(upscale, num_feat) self.upsample_hf = Upsample_hf(upscale, num_feat) self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1) self.conv_first_hf = nn.Sequential( nn.Conv2d(num_feat, embed_dim, 3, 1, 1), nn.LeakyReLU(inplace=True) ) self.conv_after_body_hf = nn.Conv2d(embed_dim, embed_dim, 3, 1, 1) self.conv_before_upsample_hf = nn.Sequential( nn.Conv2d(embed_dim, num_feat, 3, 1, 1), nn.LeakyReLU(inplace=True) ) self.conv_last_hf = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1) elif self.upsampler == "pixelshuffledirect": # for lightweight SR (to save parameters) self.upsample = UpsampleOneStep( upscale, embed_dim, num_out_ch, (patches_resolution[0], patches_resolution[1]), ) elif self.upsampler == "nearest+conv": # for real-world SR (less artifacts) assert self.upscale == 4, "only support x4 now." self.conv_before_upsample = nn.Sequential( nn.Conv2d(embed_dim, num_feat, 3, 1, 1), nn.LeakyReLU(inplace=True) ) self.conv_up1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) self.conv_hr = nn.Conv2d(num_feat, num_feat, 3, 1, 1) self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1) self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True) else: # for image denoising and JPEG compression artifact reduction self.conv_last = nn.Conv2d(embed_dim, num_out_ch, 3, 1, 1) self.apply(self._init_weights) self.load_state_dict(state_dict) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=0.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) @torch.jit.ignore # type: ignore def no_weight_decay(self): return {"absolute_pos_embed"} @torch.jit.ignore # type: ignore def no_weight_decay_keywords(self): return {"relative_position_bias_table"} def check_image_size(self, x): _, _, h, w = x.size() mod_pad_h = (self.window_size - h % self.window_size) % self.window_size mod_pad_w = (self.window_size - w % self.window_size) % self.window_size x = F.pad(x, (0, mod_pad_w, 0, mod_pad_h), "reflect") return x def forward_features(self, x): x_size = (x.shape[2], x.shape[3]) x = self.patch_embed(x) if self.ape: x = x + self.absolute_pos_embed x = self.pos_drop(x) for layer in self.layers: x = layer(x, x_size) x = self.norm(x) # B L C x = self.patch_unembed(x, x_size) return x def forward_features_hf(self, x): x_size = (x.shape[2], x.shape[3]) x = self.patch_embed(x) if self.ape: x = x + self.absolute_pos_embed x = self.pos_drop(x) for layer in self.layers_hf: x = layer(x, x_size) x = self.norm(x) # B L C x = self.patch_unembed(x, x_size) return x def forward(self, x): H, W = x.shape[2:] x = self.check_image_size(x) self.mean = self.mean.type_as(x) x = (x - self.mean) * self.img_range if self.upsampler == "pixelshuffle": # for classical SR x = self.conv_first(x) x = self.conv_after_body(self.forward_features(x)) + x x = self.conv_before_upsample(x) x = self.conv_last(self.upsample(x)) elif self.upsampler == "pixelshuffle_aux": bicubic = F.interpolate( x, size=(H * self.upscale, W * self.upscale), mode="bicubic", align_corners=False, ) bicubic = self.conv_bicubic(bicubic) x = self.conv_first(x) x = self.conv_after_body(self.forward_features(x)) + x x = self.conv_before_upsample(x) aux = self.conv_aux(x) # b, 3, LR_H, LR_W x = self.conv_after_aux(aux) x = ( self.upsample(x)[:, :, : H * self.upscale, : W * self.upscale] + bicubic[:, :, : H * self.upscale, : W * self.upscale] ) x = self.conv_last(x) aux = aux / self.img_range + self.mean elif self.upsampler == "pixelshuffle_hf": # for classical SR with HF x = self.conv_first(x) x = self.conv_after_body(self.forward_features(x)) + x x_before = self.conv_before_upsample(x) x_out = self.conv_last(self.upsample(x_before)) x_hf = self.conv_first_hf(x_before) x_hf = self.conv_after_body_hf(self.forward_features_hf(x_hf)) + x_hf x_hf = self.conv_before_upsample_hf(x_hf) x_hf = self.conv_last_hf(self.upsample_hf(x_hf)) x = x_out + x_hf x_hf = x_hf / self.img_range + self.mean elif self.upsampler == "pixelshuffledirect": # for lightweight SR x = self.conv_first(x) x = self.conv_after_body(self.forward_features(x)) + x x = self.upsample(x) elif self.upsampler == "nearest+conv": # for real-world SR x = self.conv_first(x) x = self.conv_after_body(self.forward_features(x)) + x x = self.conv_before_upsample(x) x = self.lrelu( self.conv_up1( torch.nn.functional.interpolate(x, scale_factor=2, mode="nearest") ) ) x = self.lrelu( self.conv_up2( torch.nn.functional.interpolate(x, scale_factor=2, mode="nearest") ) ) x = self.conv_last(self.lrelu(self.conv_hr(x))) else: # for image denoising and JPEG compression artifact reduction x_first = self.conv_first(x) res = self.conv_after_body(self.forward_features(x_first)) + x_first x = x + self.conv_last(res) x = x / self.img_range + self.mean if self.upsampler == "pixelshuffle_aux": # NOTE: I removed an "aux" output here. not sure what that was for return x[:, :, : H * self.upscale, : W * self.upscale] # type: ignore elif self.upsampler == "pixelshuffle_hf": x_out = x_out / self.img_range + self.mean # type: ignore return x_out[:, :, : H * self.upscale, : W * self.upscale], x[:, :, : H * self.upscale, : W * self.upscale], x_hf[:, :, : H * self.upscale, : W * self.upscale] # type: ignore else: return x[:, :, : H * self.upscale, : W * self.upscale] def flops(self): flops = 0 H, W = self.patches_resolution flops += H * W * 3 * self.embed_dim * 9 flops += self.patch_embed.flops() for i, layer in enumerate(self.layers): flops += layer.flops() # type: ignore flops += H * W * 3 * self.embed_dim * self.embed_dim flops += self.upsample.flops() # type: ignore return flops
--- +++ @@ -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 // window_size, window_size, C) windows = ( @@ -56,6 +63,15 @@ def window_reverse(windows, window_size, H, W): + """ + Args: + windows: (num_windows*B, window_size, window_size, C) + window_size (int): Window size + H (int): Height of image + W (int): Width of image + Returns: + x: (B, H, W, C) + """ B = int(windows.shape[0] / (H * W / window_size / window_size)) x = windows.view( B, H // window_size, W // window_size, window_size, window_size, -1 @@ -65,6 +81,17 @@ class WindowAttention(nn.Module): + r"""Window based multi-head self attention (W-MSA) module with relative position bias. + It supports both of shifted and non-shifted window. + Args: + dim (int): Number of input channels. + window_size (tuple[int]): The height and width of the window. + num_heads (int): Number of attention heads. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 + proj_drop (float, optional): Dropout ratio of output. Default: 0.0 + pretrained_window_size (tuple[int]): The height and width of the window in pre-training. + """ def __init__( self, @@ -149,6 +176,11 @@ self.softmax = nn.Softmax(dim=-1) def forward(self, x, mask=None): + """ + Args: + x: input features with shape of (num_windows*B, N, C) + mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None + """ B_, N, C = x.shape qkv_bias = None if self.q_bias is not None: @@ -221,6 +253,22 @@ class SwinTransformerBlock(nn.Module): + r"""Swin Transformer Block. + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resulotion. + num_heads (int): Number of attention heads. + window_size (int): Window size. + shift_size (int): Shift size for SW-MSA. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float, optional): Stochastic depth rate. Default: 0.0 + act_layer (nn.Module, optional): Activation layer. Default: nn.GELU + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + pretrained_window_size (int): Window size in pre-training. + """ def __init__( self, @@ -387,6 +435,12 @@ class PatchMerging(nn.Module): + r"""Patch Merging Layer. + Args: + input_resolution (tuple[int]): Resolution of input feature. + dim (int): Number of input channels. + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + """ def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm): super().__init__() @@ -396,6 +450,9 @@ self.norm = norm_layer(2 * dim) def forward(self, x): + """ + x: B, H*W, C + """ H, W = self.input_resolution B, L, C = x.shape assert L == H * W, "input feature has wrong size" @@ -426,6 +483,23 @@ class BasicLayer(nn.Module): + """A basic Swin Transformer layer for one stage. + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resolution. + depth (int): Number of blocks. + num_heads (int): Number of attention heads. + window_size (int): Local window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. + pretrained_window_size (int): Local window size in pre-training. + """ def __init__( self, @@ -511,6 +585,14 @@ class PatchEmbed(nn.Module): + r"""Image to Patch Embedding + Args: + img_size (int): Image size. Default: 224. + patch_size (int): Patch token size. Default: 4. + in_chans (int): Number of input image channels. Default: 3. + embed_dim (int): Number of linear projection output channels. Default: 96. + norm_layer (nn.Module, optional): Normalization layer. Default: None + """ def __init__( self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None @@ -554,6 +636,26 @@ class RSTB(nn.Module): + """Residual Swin Transformer Block (RSTB). + + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resolution. + depth (int): Number of blocks. + num_heads (int): Number of attention heads. + window_size (int): Local window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. + img_size: Input image size. + patch_size: Patch size. + resi_connection: The convolutional block before residual connection. + """ def __init__( self, @@ -643,6 +745,15 @@ class PatchUnEmbed(nn.Module): + r"""Image to Patch Unembedding + + Args: + img_size (int): Image size. Default: 224. + patch_size (int): Patch token size. Default: 4. + in_chans (int): Number of input image channels. Default: 3. + embed_dim (int): Number of linear projection output channels. Default: 96. + norm_layer (nn.Module, optional): Normalization layer. Default: None + """ def __init__( self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None @@ -670,6 +781,12 @@ class Upsample(nn.Sequential): + """Upsample module. + + Args: + scale (int): Scale factor. Supported scales: 2^n and 3. + num_feat (int): Channel number of intermediate features. + """ def __init__(self, scale, num_feat): m = [] @@ -688,6 +805,12 @@ class Upsample_hf(nn.Sequential): + """Upsample module. + + Args: + scale (int): Scale factor. Supported scales: 2^n and 3. + num_feat (int): Channel number of intermediate features. + """ def __init__(self, scale, num_feat): m = [] @@ -706,6 +829,14 @@ class UpsampleOneStep(nn.Sequential): + """UpsampleOneStep module (the difference with Upsample is that it always only has 1conv + 1pixelshuffle) + Used in lightweight SR to save parameters. + + Args: + scale (int): Scale factor. Supported scales: 2^n and 3. + num_feat (int): Channel number of intermediate features. + + """ def __init__(self, scale, num_feat, num_out_ch, input_resolution=None): self.num_feat = num_feat @@ -722,6 +853,31 @@ class Swin2SR(nn.Module): + r"""Swin2SR + A PyTorch impl of : `Swin2SR: SwinV2 Transformer for Compressed Image Super-Resolution and Restoration`. + + Args: + img_size (int | tuple(int)): Input image size. Default 64 + patch_size (int | tuple(int)): Patch size. Default: 1 + in_chans (int): Number of input image channels. Default: 3 + embed_dim (int): Patch embedding dimension. Default: 96 + depths (tuple(int)): Depth of each Swin Transformer layer. + num_heads (tuple(int)): Number of attention heads in different layers. + window_size (int): Window size. Default: 7 + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4 + qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True + drop_rate (float): Dropout rate. Default: 0 + attn_drop_rate (float): Attention dropout rate. Default: 0 + drop_path_rate (float): Stochastic depth rate. Default: 0.1 + norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. + ape (bool): If True, add absolute position embedding to the patch embedding. Default: False + patch_norm (bool): If True, add normalization after patch embedding. Default: True + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False + upscale: Upscale factor. 2/3/4/8 for image SR, 1 for denoising and compress artifact reduction + img_range: Image range. 1. or 255. + upsampler: The reconstruction reconstruction module. 'pixelshuffle'/'pixelshuffledirect'/'nearest+conv'/None + resi_connection: The convolutional block before residual connection. '1conv'/'3conv' + """ def __init__( self, @@ -1218,4 +1374,4 @@ flops += layer.flops() # type: ignore flops += H * W * 3 * self.embed_dim * self.embed_dim flops += self.upsample.flops() # type: ignore - return flops+ return flops
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): return torch.tanh(x / 3) * 3 class Block(nn.Module): def __init__(self, n_in, n_out): super().__init__() self.conv = nn.Sequential(conv(n_in, n_out), nn.ReLU(), conv(n_out, n_out), nn.ReLU(), conv(n_out, n_out)) self.skip = ldm_patched.modules.ops.disable_weight_init.Conv2d(n_in, n_out, 1, bias=False) if n_in != n_out else nn.Identity() self.fuse = nn.ReLU() def forward(self, x): return self.fuse(self.conv(x) + self.skip(x)) def Encoder(): return nn.Sequential( conv(3, 64), Block(64, 64), conv(64, 64, stride=2, bias=False), Block(64, 64), Block(64, 64), Block(64, 64), conv(64, 64, stride=2, bias=False), Block(64, 64), Block(64, 64), Block(64, 64), conv(64, 64, stride=2, bias=False), Block(64, 64), Block(64, 64), Block(64, 64), conv(64, 4), ) def Decoder(): return nn.Sequential( Clamp(), conv(4, 64), nn.ReLU(), Block(64, 64), Block(64, 64), Block(64, 64), nn.Upsample(scale_factor=2), conv(64, 64, bias=False), Block(64, 64), Block(64, 64), Block(64, 64), nn.Upsample(scale_factor=2), conv(64, 64, bias=False), Block(64, 64), Block(64, 64), Block(64, 64), nn.Upsample(scale_factor=2), conv(64, 64, bias=False), Block(64, 64), conv(64, 3), ) class TAESD(nn.Module): latent_magnitude = 3 latent_shift = 0.5 def __init__(self, encoder_path=None, decoder_path=None): super().__init__() self.taesd_encoder = Encoder() self.taesd_decoder = Decoder() self.vae_scale = torch.nn.Parameter(torch.tensor(1.0)) if encoder_path is not None: self.taesd_encoder.load_state_dict(ldm_patched.modules.utils.load_torch_file(encoder_path, safe_load=True)) if decoder_path is not None: self.taesd_decoder.load_state_dict(ldm_patched.modules.utils.load_torch_file(decoder_path, safe_load=True)) @staticmethod def scale_latents(x): return x.div(2 * TAESD.latent_magnitude).add(TAESD.latent_shift).clamp(0, 1) @staticmethod def unscale_latents(x): return x.sub(TAESD.latent_shift).mul(2 * TAESD.latent_magnitude) def decode(self, x): x_sample = self.taesd_decoder(x * self.vae_scale) x_sample = x_sample.sub(0.5).mul(2) return x_sample def encode(self, x): return self.taesd_encoder(x * 0.5 + 0.5) / self.vae_scale
--- +++ @@ -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 pretrained TAESD on the given device from the given checkpoints.""" super().__init__() self.taesd_encoder = Encoder() self.taesd_decoder = Decoder() @@ -55,10 +60,12 @@ @staticmethod def scale_latents(x): + """raw latents -> [0, 1]""" return x.div(2 * TAESD.latent_magnitude).add(TAESD.latent_shift).clamp(0, 1) @staticmethod def unscale_latents(x): + """[0, 1] -> raw latents""" return x.sub(TAESD.latent_shift).mul(2 * TAESD.latent_magnitude) def decode(self, x): @@ -67,4 +74,4 @@ return x_sample def encode(self, x): - return self.taesd_encoder(x * 0.5 + 0.5) / self.vae_scale+ return self.taesd_encoder(x * 0.5 + 0.5) / self.vae_scale
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, continuous_beta_0=0.1, continuous_beta_1=20., ): if schedule not in ['discrete', 'linear', 'cosine']: raise ValueError("Unsupported noise schedule {}. The schedule needs to be 'discrete' or 'linear' or 'cosine'".format(schedule)) self.schedule = schedule if schedule == 'discrete': if betas is not None: log_alphas = 0.5 * torch.log(1 - betas).cumsum(dim=0) else: assert alphas_cumprod is not None log_alphas = 0.5 * torch.log(alphas_cumprod) self.total_N = len(log_alphas) self.T = 1. self.t_array = torch.linspace(0., 1., self.total_N + 1)[1:].reshape((1, -1)) self.log_alpha_array = log_alphas.reshape((1, -1,)) else: self.total_N = 1000 self.beta_0 = continuous_beta_0 self.beta_1 = continuous_beta_1 self.cosine_s = 0.008 self.cosine_beta_max = 999. self.cosine_t_max = math.atan(self.cosine_beta_max * (1. + self.cosine_s) / math.pi) * 2. * (1. + self.cosine_s) / math.pi - self.cosine_s self.cosine_log_alpha_0 = math.log(math.cos(self.cosine_s / (1. + self.cosine_s) * math.pi / 2.)) self.schedule = schedule if schedule == 'cosine': # For the cosine schedule, T = 1 will have numerical issues. So we manually set the ending time T. # Note that T = 0.9946 may be not the optimal setting. However, we find it works well. self.T = 0.9946 else: self.T = 1. def marginal_log_mean_coeff(self, t): if self.schedule == 'discrete': return interpolate_fn(t.reshape((-1, 1)), self.t_array.to(t.device), self.log_alpha_array.to(t.device)).reshape((-1)) elif self.schedule == 'linear': return -0.25 * t ** 2 * (self.beta_1 - self.beta_0) - 0.5 * t * self.beta_0 elif self.schedule == 'cosine': log_alpha_fn = lambda s: torch.log(torch.cos((s + self.cosine_s) / (1. + self.cosine_s) * math.pi / 2.)) log_alpha_t = log_alpha_fn(t) - self.cosine_log_alpha_0 return log_alpha_t def marginal_alpha(self, t): return torch.exp(self.marginal_log_mean_coeff(t)) def marginal_std(self, t): return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t))) def marginal_lambda(self, t): log_mean_coeff = self.marginal_log_mean_coeff(t) log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff)) return log_mean_coeff - log_std def inverse_lambda(self, lamb): if self.schedule == 'linear': tmp = 2. * (self.beta_1 - self.beta_0) * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb)) Delta = self.beta_0**2 + tmp return tmp / (torch.sqrt(Delta) + self.beta_0) / (self.beta_1 - self.beta_0) elif self.schedule == 'discrete': log_alpha = -0.5 * torch.logaddexp(torch.zeros((1,)).to(lamb.device), -2. * lamb) t = interpolate_fn(log_alpha.reshape((-1, 1)), torch.flip(self.log_alpha_array.to(lamb.device), [1]), torch.flip(self.t_array.to(lamb.device), [1])) return t.reshape((-1,)) else: log_alpha = -0.5 * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb)) t_fn = lambda log_alpha_t: torch.arccos(torch.exp(log_alpha_t + self.cosine_log_alpha_0)) * 2. * (1. + self.cosine_s) / math.pi - self.cosine_s t = t_fn(log_alpha) return t def model_wrapper( model, noise_schedule, model_type="noise", model_kwargs={}, guidance_type="uncond", condition=None, unconditional_condition=None, guidance_scale=1., classifier_fn=None, classifier_kwargs={}, ): def get_model_input_time(t_continuous): if noise_schedule.schedule == 'discrete': return (t_continuous - 1. / noise_schedule.total_N) * 1000. else: return t_continuous def noise_pred_fn(x, t_continuous, cond=None): if t_continuous.reshape((-1,)).shape[0] == 1: t_continuous = t_continuous.expand((x.shape[0])) t_input = get_model_input_time(t_continuous) output = model(x, t_input, **model_kwargs) if model_type == "noise": return output elif model_type == "x_start": alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous) dims = x.dim() return (x - expand_dims(alpha_t, dims) * output) / expand_dims(sigma_t, dims) elif model_type == "v": alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous) dims = x.dim() return expand_dims(alpha_t, dims) * output + expand_dims(sigma_t, dims) * x elif model_type == "score": sigma_t = noise_schedule.marginal_std(t_continuous) dims = x.dim() return -expand_dims(sigma_t, dims) * output def cond_grad_fn(x, t_input): with torch.enable_grad(): x_in = x.detach().requires_grad_(True) log_prob = classifier_fn(x_in, t_input, condition, **classifier_kwargs) return torch.autograd.grad(log_prob.sum(), x_in)[0] def model_fn(x, t_continuous): if t_continuous.reshape((-1,)).shape[0] == 1: t_continuous = t_continuous.expand((x.shape[0])) if guidance_type == "uncond": return noise_pred_fn(x, t_continuous) elif guidance_type == "classifier": assert classifier_fn is not None t_input = get_model_input_time(t_continuous) cond_grad = cond_grad_fn(x, t_input) sigma_t = noise_schedule.marginal_std(t_continuous) noise = noise_pred_fn(x, t_continuous) return noise - guidance_scale * expand_dims(sigma_t, dims=cond_grad.dim()) * cond_grad elif guidance_type == "classifier-free": if guidance_scale == 1. or unconditional_condition is None: return noise_pred_fn(x, t_continuous, cond=condition) else: x_in = torch.cat([x] * 2) t_in = torch.cat([t_continuous] * 2) c_in = torch.cat([unconditional_condition, condition]) noise_uncond, noise = noise_pred_fn(x_in, t_in, cond=c_in).chunk(2) return noise_uncond + guidance_scale * (noise - noise_uncond) assert model_type in ["noise", "x_start", "v"] assert guidance_type in ["uncond", "classifier", "classifier-free"] return model_fn class UniPC: def __init__( self, model_fn, noise_schedule, predict_x0=True, thresholding=False, max_val=1., variant='bh1', noise_mask=None, masked_image=None, noise=None, ): self.model = model_fn self.noise_schedule = noise_schedule self.variant = variant self.predict_x0 = predict_x0 self.thresholding = thresholding self.max_val = max_val self.noise_mask = noise_mask self.masked_image = masked_image self.noise = noise def dynamic_thresholding_fn(self, x0, t=None): dims = x0.dim() p = self.dynamic_thresholding_ratio s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1) s = expand_dims(torch.maximum(s, self.thresholding_max_val * torch.ones_like(s).to(s.device)), dims) x0 = torch.clamp(x0, -s, s) / s return x0 def noise_prediction_fn(self, x, t): if self.noise_mask is not None: return self.model(x, t) * self.noise_mask else: return self.model(x, t) def data_prediction_fn(self, x, t): noise = self.noise_prediction_fn(x, t) dims = x.dim() alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t) x0 = (x - expand_dims(sigma_t, dims) * noise) / expand_dims(alpha_t, dims) if self.thresholding: p = 0.995 # A hyperparameter in the paper of "Imagen" [1]. s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1) s = expand_dims(torch.maximum(s, self.max_val * torch.ones_like(s).to(s.device)), dims) x0 = torch.clamp(x0, -s, s) / s if self.noise_mask is not None: x0 = x0 * self.noise_mask + (1. - self.noise_mask) * self.masked_image return x0 def model_fn(self, x, t): if self.predict_x0: return self.data_prediction_fn(x, t) else: return self.noise_prediction_fn(x, t) def get_time_steps(self, skip_type, t_T, t_0, N, device): if skip_type == 'logSNR': lambda_T = self.noise_schedule.marginal_lambda(torch.tensor(t_T).to(device)) lambda_0 = self.noise_schedule.marginal_lambda(torch.tensor(t_0).to(device)) logSNR_steps = torch.linspace(lambda_T.cpu().item(), lambda_0.cpu().item(), N + 1).to(device) return self.noise_schedule.inverse_lambda(logSNR_steps) elif skip_type == 'time_uniform': return torch.linspace(t_T, t_0, N + 1).to(device) elif skip_type == 'time_quadratic': t_order = 2 t = torch.linspace(t_T**(1. / t_order), t_0**(1. / t_order), N + 1).pow(t_order).to(device) return t else: raise ValueError("Unsupported skip_type {}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'".format(skip_type)) def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device): if order == 3: K = steps // 3 + 1 if steps % 3 == 0: orders = [3,] * (K - 2) + [2, 1] elif steps % 3 == 1: orders = [3,] * (K - 1) + [1] else: orders = [3,] * (K - 1) + [2] elif order == 2: if steps % 2 == 0: K = steps // 2 orders = [2,] * K else: K = steps // 2 + 1 orders = [2,] * (K - 1) + [1] elif order == 1: K = steps orders = [1,] * steps else: raise ValueError("'order' must be '1' or '2' or '3'.") if skip_type == 'logSNR': # To reproduce the results in DPM-Solver paper timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, K, device) else: timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, steps, device)[torch.cumsum(torch.tensor([0,] + orders), 0).to(device)] return timesteps_outer, orders def denoise_to_zero_fn(self, x, s): return self.data_prediction_fn(x, s) def multistep_uni_pc_update(self, x, model_prev_list, t_prev_list, t, order, **kwargs): if len(t.shape) == 0: t = t.view(-1) if 'bh' in self.variant: return self.multistep_uni_pc_bh_update(x, model_prev_list, t_prev_list, t, order, **kwargs) else: assert self.variant == 'vary_coeff' return self.multistep_uni_pc_vary_update(x, model_prev_list, t_prev_list, t, order, **kwargs) def multistep_uni_pc_vary_update(self, x, model_prev_list, t_prev_list, t, order, use_corrector=True): print(f'using unified predictor-corrector with order {order} (solver type: vary coeff)') ns = self.noise_schedule assert order <= len(model_prev_list) # first compute rks t_prev_0 = t_prev_list[-1] lambda_prev_0 = ns.marginal_lambda(t_prev_0) lambda_t = ns.marginal_lambda(t) model_prev_0 = model_prev_list[-1] sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t) log_alpha_t = ns.marginal_log_mean_coeff(t) alpha_t = torch.exp(log_alpha_t) h = lambda_t - lambda_prev_0 rks = [] D1s = [] for i in range(1, order): t_prev_i = t_prev_list[-(i + 1)] model_prev_i = model_prev_list[-(i + 1)] lambda_prev_i = ns.marginal_lambda(t_prev_i) rk = (lambda_prev_i - lambda_prev_0) / h rks.append(rk) D1s.append((model_prev_i - model_prev_0) / rk) rks.append(1.) rks = torch.tensor(rks, device=x.device) K = len(rks) # build C matrix C = [] col = torch.ones_like(rks) for k in range(1, K + 1): C.append(col) col = col * rks / (k + 1) C = torch.stack(C, dim=1) if len(D1s) > 0: D1s = torch.stack(D1s, dim=1) # (B, K) C_inv_p = torch.linalg.inv(C[:-1, :-1]) A_p = C_inv_p if use_corrector: print('using corrector') C_inv = torch.linalg.inv(C) A_c = C_inv hh = -h if self.predict_x0 else h h_phi_1 = torch.expm1(hh) h_phi_ks = [] factorial_k = 1 h_phi_k = h_phi_1 for k in range(1, K + 2): h_phi_ks.append(h_phi_k) h_phi_k = h_phi_k / hh - 1 / factorial_k factorial_k *= (k + 1) model_t = None if self.predict_x0: x_t_ = ( sigma_t / sigma_prev_0 * x - alpha_t * h_phi_1 * model_prev_0 ) # now predictor x_t = x_t_ if len(D1s) > 0: # compute the residuals for predictor for k in range(K - 1): x_t = x_t - alpha_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_p[k]) # now corrector if use_corrector: model_t = self.model_fn(x_t, t) D1_t = (model_t - model_prev_0) x_t = x_t_ k = 0 for k in range(K - 1): x_t = x_t - alpha_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_c[k][:-1]) x_t = x_t - alpha_t * h_phi_ks[K] * (D1_t * A_c[k][-1]) else: log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t) x_t_ = ( (torch.exp(log_alpha_t - log_alpha_prev_0)) * x - (sigma_t * h_phi_1) * model_prev_0 ) # now predictor x_t = x_t_ if len(D1s) > 0: # compute the residuals for predictor for k in range(K - 1): x_t = x_t - sigma_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_p[k]) # now corrector if use_corrector: model_t = self.model_fn(x_t, t) D1_t = (model_t - model_prev_0) x_t = x_t_ k = 0 for k in range(K - 1): x_t = x_t - sigma_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_c[k][:-1]) x_t = x_t - sigma_t * h_phi_ks[K] * (D1_t * A_c[k][-1]) return x_t, model_t def multistep_uni_pc_bh_update(self, x, model_prev_list, t_prev_list, t, order, x_t=None, use_corrector=True): # print(f'using unified predictor-corrector with order {order} (solver type: B(h))') ns = self.noise_schedule assert order <= len(model_prev_list) dims = x.dim() # first compute rks t_prev_0 = t_prev_list[-1] lambda_prev_0 = ns.marginal_lambda(t_prev_0) lambda_t = ns.marginal_lambda(t) model_prev_0 = model_prev_list[-1] sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t) log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t) alpha_t = torch.exp(log_alpha_t) h = lambda_t - lambda_prev_0 rks = [] D1s = [] for i in range(1, order): t_prev_i = t_prev_list[-(i + 1)] model_prev_i = model_prev_list[-(i + 1)] lambda_prev_i = ns.marginal_lambda(t_prev_i) rk = ((lambda_prev_i - lambda_prev_0) / h)[0] rks.append(rk) D1s.append((model_prev_i - model_prev_0) / rk) rks.append(1.) rks = torch.tensor(rks, device=x.device) R = [] b = [] hh = -h[0] if self.predict_x0 else h[0] h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1 h_phi_k = h_phi_1 / hh - 1 factorial_i = 1 if self.variant == 'bh1': B_h = hh elif self.variant == 'bh2': B_h = torch.expm1(hh) else: raise NotImplementedError() for i in range(1, order + 1): R.append(torch.pow(rks, i - 1)) b.append(h_phi_k * factorial_i / B_h) factorial_i *= (i + 1) h_phi_k = h_phi_k / hh - 1 / factorial_i R = torch.stack(R) b = torch.tensor(b, device=x.device) # now predictor use_predictor = len(D1s) > 0 and x_t is None if len(D1s) > 0: D1s = torch.stack(D1s, dim=1) # (B, K) if x_t is None: # for order 2, we use a simplified version if order == 2: rhos_p = torch.tensor([0.5], device=b.device) else: rhos_p = torch.linalg.solve(R[:-1, :-1], b[:-1]) else: D1s = None if use_corrector: # print('using corrector') # for order 1, we use a simplified version if order == 1: rhos_c = torch.tensor([0.5], device=b.device) else: rhos_c = torch.linalg.solve(R, b) model_t = None if self.predict_x0: x_t_ = ( expand_dims(sigma_t / sigma_prev_0, dims) * x - expand_dims(alpha_t * h_phi_1, dims)* model_prev_0 ) if x_t is None: if use_predictor: pred_res = torch.einsum('k,bkchw->bchw', rhos_p, D1s) else: pred_res = 0 x_t = x_t_ - expand_dims(alpha_t * B_h, dims) * pred_res if use_corrector: model_t = self.model_fn(x_t, t) if D1s is not None: corr_res = torch.einsum('k,bkchw->bchw', rhos_c[:-1], D1s) else: corr_res = 0 D1_t = (model_t - model_prev_0) x_t = x_t_ - expand_dims(alpha_t * B_h, dims) * (corr_res + rhos_c[-1] * D1_t) else: x_t_ = ( expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x - expand_dims(sigma_t * h_phi_1, dims) * model_prev_0 ) if x_t is None: if use_predictor: pred_res = torch.einsum('k,bkchw->bchw', rhos_p, D1s) else: pred_res = 0 x_t = x_t_ - expand_dims(sigma_t * B_h, dims) * pred_res if use_corrector: model_t = self.model_fn(x_t, t) if D1s is not None: corr_res = torch.einsum('k,bkchw->bchw', rhos_c[:-1], D1s) else: corr_res = 0 D1_t = (model_t - model_prev_0) x_t = x_t_ - expand_dims(sigma_t * B_h, dims) * (corr_res + rhos_c[-1] * D1_t) return x_t, model_t def sample(self, x, timesteps, t_start=None, t_end=None, order=3, skip_type='time_uniform', method='singlestep', lower_order_final=True, denoise_to_zero=False, solver_type='dpm_solver', atol=0.0078, rtol=0.05, corrector=False, callback=None, disable_pbar=False ): # t_0 = 1. / self.noise_schedule.total_N if t_end is None else t_end # t_T = self.noise_schedule.T if t_start is None else t_start device = x.device steps = len(timesteps) - 1 if method == 'multistep': assert steps >= order # timesteps = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=steps, device=device) assert timesteps.shape[0] - 1 == steps # with torch.no_grad(): for step_index in trange(steps, disable=disable_pbar): if self.noise_mask is not None: x = x * self.noise_mask + (1. - self.noise_mask) * (self.masked_image * self.noise_schedule.marginal_alpha(timesteps[step_index]) + self.noise * self.noise_schedule.marginal_std(timesteps[step_index])) if step_index == 0: vec_t = timesteps[0].expand((x.shape[0])) model_prev_list = [self.model_fn(x, vec_t)] t_prev_list = [vec_t] elif step_index < order: init_order = step_index # Init the first `order` values by lower order multistep DPM-Solver. # for init_order in range(1, order): vec_t = timesteps[init_order].expand(x.shape[0]) x, model_x = self.multistep_uni_pc_update(x, model_prev_list, t_prev_list, vec_t, init_order, use_corrector=True) if model_x is None: model_x = self.model_fn(x, vec_t) model_prev_list.append(model_x) t_prev_list.append(vec_t) else: extra_final_step = 0 if step_index == (steps - 1): extra_final_step = 1 for step in range(step_index, step_index + 1 + extra_final_step): vec_t = timesteps[step].expand(x.shape[0]) if lower_order_final: step_order = min(order, steps + 1 - step) else: step_order = order # print('this step order:', step_order) if step == steps: # print('do not run corrector at the last step') use_corrector = False else: use_corrector = True x, model_x = self.multistep_uni_pc_update(x, model_prev_list, t_prev_list, vec_t, step_order, use_corrector=use_corrector) for i in range(order - 1): t_prev_list[i] = t_prev_list[i + 1] model_prev_list[i] = model_prev_list[i + 1] t_prev_list[-1] = vec_t # We do not need to evaluate the final model value. if step < steps: if model_x is None: model_x = self.model_fn(x, vec_t) model_prev_list[-1] = model_x if callback is not None: callback(step_index, model_prev_list[-1], x, steps) else: raise NotImplementedError() # if denoise_to_zero: # x = self.denoise_to_zero_fn(x, torch.ones((x.shape[0],)).to(device) * t_0) return x ############################################################# # other utility functions ############################################################# def interpolate_fn(x, xp, yp): N, K = x.shape[0], xp.shape[1] all_x = torch.cat([x.unsqueeze(2), xp.unsqueeze(0).repeat((N, 1, 1))], dim=2) sorted_all_x, x_indices = torch.sort(all_x, dim=2) x_idx = torch.argmin(x_indices, dim=2) cand_start_idx = x_idx - 1 start_idx = torch.where( torch.eq(x_idx, 0), torch.tensor(1, device=x.device), torch.where( torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx, ), ) end_idx = torch.where(torch.eq(start_idx, cand_start_idx), start_idx + 2, start_idx + 1) start_x = torch.gather(sorted_all_x, dim=2, index=start_idx.unsqueeze(2)).squeeze(2) end_x = torch.gather(sorted_all_x, dim=2, index=end_idx.unsqueeze(2)).squeeze(2) start_idx2 = torch.where( torch.eq(x_idx, 0), torch.tensor(0, device=x.device), torch.where( torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx, ), ) y_positions_expanded = yp.unsqueeze(0).expand(N, -1, -1) start_y = torch.gather(y_positions_expanded, dim=2, index=start_idx2.unsqueeze(2)).squeeze(2) end_y = torch.gather(y_positions_expanded, dim=2, index=(start_idx2 + 1).unsqueeze(2)).squeeze(2) cand = start_y + (x - start_x) * (end_y - start_y) / (end_x - start_x) return cand def expand_dims(v, dims): return v[(...,) + (None,)*(dims - 1)] class SigmaConvert: schedule = "" def marginal_log_mean_coeff(self, sigma): return 0.5 * torch.log(1 / ((sigma * sigma) + 1)) def marginal_alpha(self, t): return torch.exp(self.marginal_log_mean_coeff(t)) def marginal_std(self, t): return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t))) def marginal_lambda(self, t): log_mean_coeff = self.marginal_log_mean_coeff(t) log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff)) return log_mean_coeff - log_std def predict_eps_sigma(model, input, sigma_in, **kwargs): sigma = sigma_in.view(sigma_in.shape[:1] + (1,) * (input.ndim - 1)) input = input * ((sigma ** 2 + 1.0) ** 0.5) return (input - model(input, sigma_in, **kwargs)) / sigma def sample_unipc(model, noise, image, sigmas, max_denoise, extra_args=None, callback=None, disable=False, noise_mask=None, variant='bh1'): timesteps = sigmas.clone() if sigmas[-1] == 0: timesteps = sigmas[:] timesteps[-1] = 0.001 else: timesteps = sigmas.clone() ns = SigmaConvert() if image is not None: img = image * ns.marginal_alpha(timesteps[0]) if max_denoise: noise_mult = 1.0 else: noise_mult = ns.marginal_std(timesteps[0]) img += noise * noise_mult else: img = noise model_type = "noise" model_fn = model_wrapper( lambda input, sigma, **kwargs: predict_eps_sigma(model, input, sigma, **kwargs), ns, model_type=model_type, guidance_type="uncond", model_kwargs=extra_args, ) order = min(3, len(timesteps) - 2) uni_pc = UniPC(model_fn, ns, predict_x0=True, thresholding=False, noise_mask=noise_mask, masked_image=image, noise=noise, variant=variant) x = uni_pc.sample(img, timesteps=timesteps, skip_type="time_uniform", method="multistep", order=order, lower_order_final=True, callback=callback, disable_pbar=disable) x /= ns.marginal_alpha(timesteps[-1]) return x
--- +++ @@ -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. + We recommend to use schedule='discrete' for the discrete-time diffusion models, especially for high-resolution images. + *** + + The forward SDE ensures that the condition distribution q_{t|0}(x_t | x_0) = N ( alpha_t * x_0, sigma_t^2 * I ). + We further define lambda_t = log(alpha_t) - log(sigma_t), which is the half-logSNR (described in the DPM-Solver paper). + Therefore, we implement the functions for computing alpha_t, sigma_t and lambda_t. For t in [0, T], we have: + + log_alpha_t = self.marginal_log_mean_coeff(t) + sigma_t = self.marginal_std(t) + lambda_t = self.marginal_lambda(t) + + Moreover, as lambda(t) is an invertible function, we also support its inverse function: + + t = self.inverse_lambda(lambda_t) + + =============================================================== + + We support both discrete-time DPMs (trained on n = 0, 1, ..., N-1) and continuous-time DPMs (trained on t in [t_0, T]). + + 1. For discrete-time DPMs: + + For discrete-time DPMs trained on n = 0, 1, ..., N-1, we convert the discrete steps to continuous time steps by: + t_i = (i + 1) / N + e.g. for N = 1000, we have t_0 = 1e-3 and T = t_{N-1} = 1. + We solve the corresponding diffusion ODE from time T = 1 to time t_0 = 1e-3. + + Args: + betas: A `torch.Tensor`. The beta array for the discrete-time DPM. (See the original DDPM paper for details) + alphas_cumprod: A `torch.Tensor`. The cumprod alphas for the discrete-time DPM. (See the original DDPM paper for details) + + Note that we always have alphas_cumprod = cumprod(betas). Therefore, we only need to set one of `betas` and `alphas_cumprod`. + + **Important**: Please pay special attention for the args for `alphas_cumprod`: + The `alphas_cumprod` is the \hat{alpha_n} arrays in the notations of DDPM. Specifically, DDPMs assume that + q_{t_n | 0}(x_{t_n} | x_0) = N ( \sqrt{\hat{alpha_n}} * x_0, (1 - \hat{alpha_n}) * I ). + Therefore, the notation \hat{alpha_n} is different from the notation alpha_t in DPM-Solver. In fact, we have + alpha_{t_n} = \sqrt{\hat{alpha_n}}, + and + log(alpha_{t_n}) = 0.5 * log(\hat{alpha_n}). + + + 2. For continuous-time DPMs: + + We support two types of VPSDEs: linear (DDPM) and cosine (improved-DDPM). The hyperparameters for the noise + schedule are the default settings in DDPM and improved-DDPM: + + Args: + beta_min: A `float` number. The smallest beta for the linear schedule. + beta_max: A `float` number. The largest beta for the linear schedule. + cosine_s: A `float` number. The hyperparameter in the cosine schedule. + cosine_beta_max: A `float` number. The hyperparameter in the cosine schedule. + T: A `float` number. The ending time of the forward process. + + =============================================================== + + Args: + schedule: A `str`. The noise schedule of the forward SDE. 'discrete' for discrete-time DPMs, + 'linear' or 'cosine' for continuous-time DPMs. + Returns: + A wrapper object of the forward SDE (VP type). + + =============================================================== + + Example: + + # For discrete-time DPMs, given betas (the beta array for n = 0, 1, ..., N - 1): + >>> ns = NoiseScheduleVP('discrete', betas=betas) + + # For discrete-time DPMs, given alphas_cumprod (the \hat{alpha_n} array for n = 0, 1, ..., N - 1): + >>> ns = NoiseScheduleVP('discrete', alphas_cumprod=alphas_cumprod) + + # For continuous-time DPMs (VPSDE), linear schedule: + >>> ns = NoiseScheduleVP('linear', continuous_beta_0=0.1, continuous_beta_1=20.) + + """ if schedule not in ['discrete', 'linear', 'cosine']: raise ValueError("Unsupported noise schedule {}. The schedule needs to be 'discrete' or 'linear' or 'cosine'".format(schedule)) @@ -48,6 +127,9 @@ self.T = 1. def marginal_log_mean_coeff(self, t): + """ + Compute log(alpha_t) of a given continuous-time label t in [0, T]. + """ if self.schedule == 'discrete': return interpolate_fn(t.reshape((-1, 1)), self.t_array.to(t.device), self.log_alpha_array.to(t.device)).reshape((-1)) elif self.schedule == 'linear': @@ -58,17 +140,29 @@ return log_alpha_t def marginal_alpha(self, t): + """ + Compute alpha_t of a given continuous-time label t in [0, T]. + """ return torch.exp(self.marginal_log_mean_coeff(t)) def marginal_std(self, t): + """ + Compute sigma_t of a given continuous-time label t in [0, T]. + """ return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t))) def marginal_lambda(self, t): + """ + Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T]. + """ log_mean_coeff = self.marginal_log_mean_coeff(t) log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff)) return log_mean_coeff - log_std def inverse_lambda(self, lamb): + """ + Compute the continuous-time label t in [0, T] of a given half-logSNR lambda_t. + """ if self.schedule == 'linear': tmp = 2. * (self.beta_1 - self.beta_0) * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb)) Delta = self.beta_0**2 + tmp @@ -96,8 +190,101 @@ classifier_fn=None, classifier_kwargs={}, ): + """Create a wrapper function for the noise prediction model. + + DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to + firstly wrap the model function to a noise prediction model that accepts the continuous time as the input. + + We support four types of the diffusion model by setting `model_type`: + + 1. "noise": noise prediction model. (Trained by predicting noise). + + 2. "x_start": data prediction model. (Trained by predicting the data x_0 at time 0). + + 3. "v": velocity prediction model. (Trained by predicting the velocity). + The "v" prediction is derivation detailed in Appendix D of [1], and is used in Imagen-Video [2]. + + [1] Salimans, Tim, and Jonathan Ho. "Progressive distillation for fast sampling of diffusion models." + arXiv preprint arXiv:2202.00512 (2022). + [2] Ho, Jonathan, et al. "Imagen Video: High Definition Video Generation with Diffusion Models." + arXiv preprint arXiv:2210.02303 (2022). + + 4. "score": marginal score function. (Trained by denoising score matching). + Note that the score function and the noise prediction model follows a simple relationship: + ``` + noise(x_t, t) = -sigma_t * score(x_t, t) + ``` + + We support three types of guided sampling by DPMs by setting `guidance_type`: + 1. "uncond": unconditional sampling by DPMs. + The input `model` has the following format: + `` + model(x, t_input, **model_kwargs) -> noise | x_start | v | score + `` + + 2. "classifier": classifier guidance sampling [3] by DPMs and another classifier. + The input `model` has the following format: + `` + model(x, t_input, **model_kwargs) -> noise | x_start | v | score + `` + + The input `classifier_fn` has the following format: + `` + classifier_fn(x, t_input, cond, **classifier_kwargs) -> logits(x, t_input, cond) + `` + + [3] P. Dhariwal and A. Q. Nichol, "Diffusion models beat GANs on image synthesis," + in Advances in Neural Information Processing Systems, vol. 34, 2021, pp. 8780-8794. + + 3. "classifier-free": classifier-free guidance sampling by conditional DPMs. + The input `model` has the following format: + `` + model(x, t_input, cond, **model_kwargs) -> noise | x_start | v | score + `` + And if cond == `unconditional_condition`, the model output is the unconditional DPM output. + + [4] Ho, Jonathan, and Tim Salimans. "Classifier-free diffusion guidance." + arXiv preprint arXiv:2207.12598 (2022). + + + The `t_input` is the time label of the model, which may be discrete-time labels (i.e. 0 to 999) + or continuous-time labels (i.e. epsilon to T). + + We wrap the model function to accept only `x` and `t_continuous` as inputs, and outputs the predicted noise: + `` + def model_fn(x, t_continuous) -> noise: + t_input = get_model_input_time(t_continuous) + return noise_pred(model, x, t_input, **model_kwargs) + `` + where `t_continuous` is the continuous time labels (i.e. epsilon to T). And we use `model_fn` for DPM-Solver. + + =============================================================== + + Args: + model: A diffusion model with the corresponding format described above. + noise_schedule: A noise schedule object, such as NoiseScheduleVP. + model_type: A `str`. The parameterization type of the diffusion model. + "noise" or "x_start" or "v" or "score". + model_kwargs: A `dict`. A dict for the other inputs of the model function. + guidance_type: A `str`. The type of the guidance for sampling. + "uncond" or "classifier" or "classifier-free". + condition: A pytorch tensor. The condition for the guided sampling. + Only used for "classifier" or "classifier-free" guidance type. + unconditional_condition: A pytorch tensor. The condition for the unconditional sampling. + Only used for "classifier-free" guidance type. + guidance_scale: A `float`. The scale for the guided sampling. + classifier_fn: A classifier function. Only used for the classifier guidance. + classifier_kwargs: A `dict`. A dict for the other inputs of the classifier function. + Returns: + A noise prediction model that accepts the noised data and the continuous time as the inputs. + """ def get_model_input_time(t_continuous): + """ + Convert the continuous-time `t_continuous` (in [epsilon, T]) to the model input time. + For discrete-time DPMs, we convert `t_continuous` in [1 / N, 1] to `t_input` in [0, 1000 * (N - 1) / N]. + For continuous-time DPMs, we just use `t_continuous`. + """ if noise_schedule.schedule == 'discrete': return (t_continuous - 1. / noise_schedule.total_N) * 1000. else: @@ -124,12 +311,18 @@ return -expand_dims(sigma_t, dims) * output def cond_grad_fn(x, t_input): + """ + Compute the gradient of the classifier, i.e. nabla_{x} log p_t(cond | x_t). + """ with torch.enable_grad(): x_in = x.detach().requires_grad_(True) log_prob = classifier_fn(x_in, t_input, condition, **classifier_kwargs) return torch.autograd.grad(log_prob.sum(), x_in)[0] def model_fn(x, t_continuous): + """ + The noise predicition model function that is used for DPM-Solver. + """ if t_continuous.reshape((-1,)).shape[0] == 1: t_continuous = t_continuous.expand((x.shape[0])) if guidance_type == "uncond": @@ -169,6 +362,10 @@ masked_image=None, noise=None, ): + """Construct a UniPC. + + We support both data_prediction and noise_prediction. + """ self.model = model_fn self.noise_schedule = noise_schedule self.variant = variant @@ -180,6 +377,9 @@ self.noise = noise def dynamic_thresholding_fn(self, x0, t=None): + """ + The dynamic thresholding method. + """ dims = x0.dim() p = self.dynamic_thresholding_ratio s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1) @@ -188,12 +388,18 @@ return x0 def noise_prediction_fn(self, x, t): + """ + Return the noise prediction model. + """ if self.noise_mask is not None: return self.model(x, t) * self.noise_mask else: return self.model(x, t) def data_prediction_fn(self, x, t): + """ + Return the data prediction model (with thresholding). + """ noise = self.noise_prediction_fn(x, t) dims = x.dim() alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t) @@ -208,12 +414,17 @@ return x0 def model_fn(self, x, t): + """ + Convert the model to the noise prediction model or the data prediction model. + """ if self.predict_x0: return self.data_prediction_fn(x, t) else: return self.noise_prediction_fn(x, t) def get_time_steps(self, skip_type, t_T, t_0, N, device): + """Compute the intermediate time steps for sampling. + """ if skip_type == 'logSNR': lambda_T = self.noise_schedule.marginal_lambda(torch.tensor(t_T).to(device)) lambda_0 = self.noise_schedule.marginal_lambda(torch.tensor(t_0).to(device)) @@ -229,6 +440,9 @@ raise ValueError("Unsupported skip_type {}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'".format(skip_type)) def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device): + """ + Get the order of each step for sampling by the singlestep DPM-Solver. + """ if order == 3: K = steps // 3 + 1 if steps % 3 == 0: @@ -257,6 +471,9 @@ return timesteps_outer, orders def denoise_to_zero_fn(self, x, s): + """ + Denoise at the final step, which is equivalent to solve the ODE from lambda_s to infty by first-order discretization. + """ return self.data_prediction_fn(x, s) def multistep_uni_pc_update(self, x, model_prev_list, t_prev_list, t, order, **kwargs): @@ -562,6 +779,18 @@ ############################################################# def interpolate_fn(x, xp, yp): + """ + A piecewise linear function y = f(x), using xp and yp as keypoints. + We implement f(x) in a differentiable way (i.e. applicable for autograd). + The function f(x) is well-defined for all x-axis. (For x beyond the bounds of xp, we use the outmost points of xp to define the linear function.) + + Args: + x: PyTorch tensor with shape [N, C], where N is the batch size, C is the number of channels (we use C = 1 for DPM-Solver). + xp: PyTorch tensor with shape [C, K], where K is the number of keypoints. + yp: PyTorch tensor with shape [C, K]. + Returns: + The function values f(x), with shape [N, C]. + """ N, K = x.shape[0], xp.shape[1] all_x = torch.cat([x.unsqueeze(2), xp.unsqueeze(0).repeat((N, 1, 1))], dim=2) sorted_all_x, x_indices = torch.sort(all_x, dim=2) @@ -592,6 +821,15 @@ def expand_dims(v, dims): + """ + Expand the tensor `v` to the dim `dims`. + + Args: + `v`: a PyTorch tensor with shape [N]. + `dim`: a `int`. + Returns: + a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`. + """ return v[(...,) + (None,)*(dims - 1)] @@ -607,6 +845,9 @@ return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t))) def marginal_lambda(self, t): + """ + Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T]. + """ log_mean_coeff = self.marginal_log_mean_coeff(t) log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff)) return log_mean_coeff - log_std @@ -650,4 +891,4 @@ uni_pc = UniPC(model_fn, ns, predict_x0=True, thresholding=False, noise_mask=noise_mask, masked_image=image, noise=noise, variant=variant) x = uni_pc.sample(img, timesteps=timesteps, skip_type="time_uniform", method="multistep", order=order, lower_order_final=True, callback=callback, disable_pbar=disable) x /= ns.marginal_alpha(timesteps[-1]) - return x+ return x
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: return torch.randn(latent_image.size(), dtype=latent_image.dtype, layout=latent_image.layout, generator=generator, device="cpu") unique_inds, inverse = np.unique(noise_inds, return_inverse=True) noises = [] for i in range(unique_inds[-1]+1): noise = torch.randn([1] + list(latent_image.size())[1:], dtype=latent_image.dtype, layout=latent_image.layout, generator=generator, device="cpu") if i in unique_inds: noises.append(noise) noises = [noises[i] for i in inverse] noises = torch.cat(noises, axis=0) return noises def prepare_mask(noise_mask, shape, device): noise_mask = torch.nn.functional.interpolate(noise_mask.reshape((-1, 1, noise_mask.shape[-2], noise_mask.shape[-1])), size=(shape[2], shape[3]), mode="bilinear") noise_mask = torch.cat([noise_mask] * shape[1], dim=1) noise_mask = ldm_patched.modules.utils.repeat_to_batch_size(noise_mask, shape[0]) noise_mask = noise_mask.to(device) return noise_mask def get_models_from_cond(cond, model_type): models = [] for c in cond: if model_type in c: models += [c[model_type]] return models def convert_cond(cond): out = [] for c in cond: temp = c[1].copy() model_conds = temp.get("model_conds", {}) if c[0] is not None: model_conds["c_crossattn"] = ldm_patched.modules.conds.CONDCrossAttn(c[0]) #TODO: remove temp["cross_attn"] = c[0] temp["model_conds"] = model_conds out.append(temp) return out def get_additional_models(positive, negative, dtype): control_nets = set(get_models_from_cond(positive, "control") + get_models_from_cond(negative, "control")) inference_memory = 0 control_models = [] for m in control_nets: control_models += m.get_models() inference_memory += m.inference_memory_requirements(dtype) gligen = get_models_from_cond(positive, "gligen") + get_models_from_cond(negative, "gligen") gligen = [x[1] for x in gligen] models = control_models + gligen return models, inference_memory def cleanup_additional_models(models): for m in models: if hasattr(m, 'cleanup'): m.cleanup() def prepare_sampling(model, noise_shape, positive, negative, noise_mask): device = model.load_device positive = convert_cond(positive) negative = convert_cond(negative) if noise_mask is not None: noise_mask = prepare_mask(noise_mask, noise_shape, device) real_model = None models, inference_memory = get_additional_models(positive, negative, model.model_dtype()) ldm_patched.modules.model_management.load_models_gpu([model] + models, model.memory_required([noise_shape[0] * 2] + list(noise_shape[1:])) + inference_memory) real_model = model.model return real_model, positive, negative, noise_mask, models def sample(model, noise, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=1.0, disable_noise=False, start_step=None, last_step=None, force_full_denoise=False, noise_mask=None, sigmas=None, callback=None, disable_pbar=False, seed=None): real_model, positive_copy, negative_copy, noise_mask, models = prepare_sampling(model, noise.shape, positive, negative, noise_mask) noise = noise.to(model.load_device) latent_image = latent_image.to(model.load_device) sampler = ldm_patched.modules.samplers.KSampler(real_model, steps=steps, device=model.load_device, sampler=sampler_name, scheduler=scheduler, denoise=denoise, model_options=model.model_options) samples = sampler.sample(noise, positive_copy, negative_copy, cfg=cfg, latent_image=latent_image, start_step=start_step, last_step=last_step, force_full_denoise=force_full_denoise, denoise_mask=noise_mask, sigmas=sigmas, callback=callback, disable_pbar=disable_pbar, seed=seed) samples = samples.to(ldm_patched.modules.model_management.intermediate_device()) cleanup_additional_models(models) cleanup_additional_models(set(get_models_from_cond(positive_copy, "control") + get_models_from_cond(negative_copy, "control"))) return samples def sample_custom(model, noise, cfg, sampler, sigmas, positive, negative, latent_image, noise_mask=None, callback=None, disable_pbar=False, seed=None): real_model, positive_copy, negative_copy, noise_mask, models = prepare_sampling(model, noise.shape, positive, negative, noise_mask) noise = noise.to(model.load_device) latent_image = latent_image.to(model.load_device) sigmas = sigmas.to(model.load_device) samples = ldm_patched.modules.samplers.sample(real_model, noise, positive_copy, negative_copy, cfg, model.load_device, sampler, sigmas, model_options=model.model_options, latent_image=latent_image, denoise_mask=noise_mask, callback=callback, disable_pbar=disable_pbar, seed=seed) samples = samples.to(ldm_patched.modules.model_management.intermediate_device()) cleanup_additional_models(models) cleanup_additional_models(set(get_models_from_cond(positive_copy, "control") + get_models_from_cond(negative_copy, "control"))) return samples
--- +++ @@ -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(seed) if noise_inds is None: return torch.randn(latent_image.size(), dtype=latent_image.dtype, layout=latent_image.layout, generator=generator, device="cpu") @@ -22,6 +26,7 @@ return noises def prepare_mask(noise_mask, shape, device): + """ensures noise mask is of proper dimensions""" noise_mask = torch.nn.functional.interpolate(noise_mask.reshape((-1, 1, noise_mask.shape[-2], noise_mask.shape[-1])), size=(shape[2], shape[3]), mode="bilinear") noise_mask = torch.cat([noise_mask] * shape[1], dim=1) noise_mask = ldm_patched.modules.utils.repeat_to_batch_size(noise_mask, shape[0]) @@ -48,6 +53,7 @@ return out def get_additional_models(positive, negative, dtype): + """loads additional models in positive and negative conditioning""" control_nets = set(get_models_from_cond(positive, "control") + get_models_from_cond(negative, "control")) inference_memory = 0 @@ -62,6 +68,7 @@ return models, inference_memory def cleanup_additional_models(models): + """cleanup additional models that were loaded""" for m in models: if hasattr(m, 'cleanup'): m.cleanup() @@ -108,3 +115,4 @@ cleanup_additional_models(models) cleanup_additional_models(set(get_models_from_cond(positive_copy, "control") + get_models_from_cond(negative_copy, "control"))) return samples +
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_size = codebook_size # number of embeddings self.emb_dim = emb_dim # dimension of embedding self.beta = beta # commitment cost used in loss term, beta * ||z_e(x)-sg[e]||^2 self.embedding = nn.Embedding(self.codebook_size, self.emb_dim) self.embedding.weight.data.uniform_( -1.0 / self.codebook_size, 1.0 / self.codebook_size ) def forward(self, z): # reshape z -> (batch, height, width, channel) and flatten z = z.permute(0, 2, 3, 1).contiguous() z_flattened = z.view(-1, self.emb_dim) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z d = ( (z_flattened**2).sum(dim=1, keepdim=True) + (self.embedding.weight**2).sum(1) - 2 * torch.matmul(z_flattened, self.embedding.weight.t()) ) mean_distance = torch.mean(d) # find closest encodings # min_encoding_indices = torch.argmin(d, dim=1).unsqueeze(1) min_encoding_scores, min_encoding_indices = torch.topk( d, 1, dim=1, largest=False ) # [0-1], higher score, higher confidence min_encoding_scores = torch.exp(-min_encoding_scores / 10) min_encodings = torch.zeros( min_encoding_indices.shape[0], self.codebook_size ).to(z) min_encodings.scatter_(1, min_encoding_indices, 1) # get quantized latent vectors z_q = torch.matmul(min_encodings, self.embedding.weight).view(z.shape) # compute loss for embedding loss = torch.mean((z_q.detach() - z) ** 2) + self.beta * torch.mean( (z_q - z.detach()) ** 2 ) # preserve gradients z_q = z + (z_q - z).detach() # perplexity e_mean = torch.mean(min_encodings, dim=0) perplexity = torch.exp(-torch.sum(e_mean * torch.log(e_mean + 1e-10))) # reshape back to match original input shape z_q = z_q.permute(0, 3, 1, 2).contiguous() return ( z_q, loss, { "perplexity": perplexity, "min_encodings": min_encodings, "min_encoding_indices": min_encoding_indices, "min_encoding_scores": min_encoding_scores, "mean_distance": mean_distance, }, ) def get_codebook_feat(self, indices, shape): # input indices: batch*token_num -> (batch*token_num)*1 # shape: batch, height, width, channel indices = indices.view(-1, 1) min_encodings = torch.zeros(indices.shape[0], self.codebook_size).to(indices) min_encodings.scatter_(1, indices, 1) # get quantized latent vectors z_q = torch.matmul(min_encodings.float(), self.embedding.weight) if shape is not None: # reshape back to match original input shape z_q = z_q.view(shape).permute(0, 3, 1, 2).contiguous() return z_q class GumbelQuantizer(nn.Module): def __init__( self, codebook_size, emb_dim, num_hiddens, straight_through=False, kl_weight=5e-4, temp_init=1.0, ): super().__init__() self.codebook_size = codebook_size # number of embeddings self.emb_dim = emb_dim # dimension of embedding self.straight_through = straight_through self.temperature = temp_init self.kl_weight = kl_weight self.proj = nn.Conv2d( num_hiddens, codebook_size, 1 ) # projects last encoder layer to quantized logits self.embed = nn.Embedding(codebook_size, emb_dim) def forward(self, z): hard = self.straight_through if self.training else True logits = self.proj(z) soft_one_hot = F.gumbel_softmax(logits, tau=self.temperature, dim=1, hard=hard) z_q = torch.einsum("b n h w, n d -> b d h w", soft_one_hot, self.embed.weight) # + kl divergence to the prior loss qy = F.softmax(logits, dim=1) diff = ( self.kl_weight * torch.sum(qy * torch.log(qy * self.codebook_size + 1e-10), dim=1).mean() ) min_encoding_indices = soft_one_hot.argmax(dim=1) return z_q, diff, {"min_encoding_indices": min_encoding_indices} class Downsample(nn.Module): def __init__(self, in_channels): super().__init__() self.conv = torch.nn.Conv2d( in_channels, in_channels, kernel_size=3, stride=2, padding=0 ) def forward(self, x): pad = (0, 1, 0, 1) x = torch.nn.functional.pad(x, pad, mode="constant", value=0) x = self.conv(x) return x class Upsample(nn.Module): def __init__(self, in_channels): super().__init__() self.conv = nn.Conv2d( in_channels, in_channels, kernel_size=3, stride=1, padding=1 ) def forward(self, x): x = F.interpolate(x, scale_factor=2.0, mode="nearest") x = self.conv(x) return x class AttnBlock(nn.Module): def __init__(self, in_channels): super().__init__() self.in_channels = in_channels self.norm = normalize(in_channels) self.q = torch.nn.Conv2d( in_channels, in_channels, kernel_size=1, stride=1, padding=0 ) self.k = torch.nn.Conv2d( in_channels, in_channels, kernel_size=1, stride=1, padding=0 ) self.v = torch.nn.Conv2d( in_channels, in_channels, kernel_size=1, stride=1, padding=0 ) self.proj_out = torch.nn.Conv2d( in_channels, in_channels, kernel_size=1, stride=1, padding=0 ) def forward(self, x): h_ = x h_ = self.norm(h_) q = self.q(h_) k = self.k(h_) v = self.v(h_) # compute attention b, c, h, w = q.shape q = q.reshape(b, c, h * w) q = q.permute(0, 2, 1) k = k.reshape(b, c, h * w) w_ = torch.bmm(q, k) w_ = w_ * (int(c) ** (-0.5)) w_ = F.softmax(w_, dim=2) # attend to values v = v.reshape(b, c, h * w) w_ = w_.permute(0, 2, 1) h_ = torch.bmm(v, w_) h_ = h_.reshape(b, c, h, w) h_ = self.proj_out(h_) return x + h_ class Encoder(nn.Module): def __init__( self, in_channels, nf, out_channels, ch_mult, num_res_blocks, resolution, attn_resolutions, ): super().__init__() self.nf = nf self.num_resolutions = len(ch_mult) self.num_res_blocks = num_res_blocks self.resolution = resolution self.attn_resolutions = attn_resolutions curr_res = self.resolution in_ch_mult = (1,) + tuple(ch_mult) blocks = [] # initial convultion blocks.append(nn.Conv2d(in_channels, nf, kernel_size=3, stride=1, padding=1)) # residual and downsampling blocks, with attention on smaller res (16x16) for i in range(self.num_resolutions): block_in_ch = nf * in_ch_mult[i] block_out_ch = nf * ch_mult[i] for _ in range(self.num_res_blocks): blocks.append(ResBlock(block_in_ch, block_out_ch)) block_in_ch = block_out_ch if curr_res in attn_resolutions: blocks.append(AttnBlock(block_in_ch)) if i != self.num_resolutions - 1: blocks.append(Downsample(block_in_ch)) curr_res = curr_res // 2 # non-local attention block blocks.append(ResBlock(block_in_ch, block_in_ch)) # type: ignore blocks.append(AttnBlock(block_in_ch)) # type: ignore blocks.append(ResBlock(block_in_ch, block_in_ch)) # type: ignore # normalise and convert to latent size blocks.append(normalize(block_in_ch)) # type: ignore blocks.append( nn.Conv2d(block_in_ch, out_channels, kernel_size=3, stride=1, padding=1) # type: ignore ) self.blocks = nn.ModuleList(blocks) def forward(self, x): for block in self.blocks: x = block(x) return x class Generator(nn.Module): def __init__(self, nf, ch_mult, res_blocks, img_size, attn_resolutions, emb_dim): super().__init__() self.nf = nf self.ch_mult = ch_mult self.num_resolutions = len(self.ch_mult) self.num_res_blocks = res_blocks self.resolution = img_size self.attn_resolutions = attn_resolutions self.in_channels = emb_dim self.out_channels = 3 block_in_ch = self.nf * self.ch_mult[-1] curr_res = self.resolution // 2 ** (self.num_resolutions - 1) blocks = [] # initial conv blocks.append( nn.Conv2d(self.in_channels, block_in_ch, kernel_size=3, stride=1, padding=1) ) # non-local attention block blocks.append(ResBlock(block_in_ch, block_in_ch)) blocks.append(AttnBlock(block_in_ch)) blocks.append(ResBlock(block_in_ch, block_in_ch)) for i in reversed(range(self.num_resolutions)): block_out_ch = self.nf * self.ch_mult[i] for _ in range(self.num_res_blocks): blocks.append(ResBlock(block_in_ch, block_out_ch)) block_in_ch = block_out_ch if curr_res in self.attn_resolutions: blocks.append(AttnBlock(block_in_ch)) if i != 0: blocks.append(Upsample(block_in_ch)) curr_res = curr_res * 2 blocks.append(normalize(block_in_ch)) blocks.append( nn.Conv2d( block_in_ch, self.out_channels, kernel_size=3, stride=1, padding=1 ) ) self.blocks = nn.ModuleList(blocks) def forward(self, x): for block in self.blocks: x = block(x) return x class VQAutoEncoder(nn.Module): def __init__( self, img_size, nf, ch_mult, quantizer="nearest", res_blocks=2, attn_resolutions=[16], codebook_size=1024, emb_dim=256, beta=0.25, gumbel_straight_through=False, gumbel_kl_weight=1e-8, model_path=None, ): super().__init__() self.in_channels = 3 self.nf = nf self.n_blocks = res_blocks self.codebook_size = codebook_size self.embed_dim = emb_dim self.ch_mult = ch_mult self.resolution = img_size self.attn_resolutions = attn_resolutions self.quantizer_type = quantizer self.encoder = Encoder( self.in_channels, self.nf, self.embed_dim, self.ch_mult, self.n_blocks, self.resolution, self.attn_resolutions, ) if self.quantizer_type == "nearest": self.beta = beta # 0.25 self.quantize = VectorQuantizer( self.codebook_size, self.embed_dim, self.beta ) elif self.quantizer_type == "gumbel": self.gumbel_num_hiddens = emb_dim self.straight_through = gumbel_straight_through self.kl_weight = gumbel_kl_weight self.quantize = GumbelQuantizer( self.codebook_size, self.embed_dim, self.gumbel_num_hiddens, self.straight_through, self.kl_weight, ) self.generator = Generator( nf, ch_mult, res_blocks, img_size, attn_resolutions, emb_dim ) if model_path is not None: chkpt = torch.load(model_path, map_location="cpu", weights_only=True) if "params_ema" in chkpt: self.load_state_dict( torch.load(model_path, map_location="cpu", weights_only=True)["params_ema"] ) logger.info(f"vqgan is loaded from: {model_path} [params_ema]") elif "params" in chkpt: self.load_state_dict( torch.load(model_path, map_location="cpu", weights_only=True)["params"] ) logger.info(f"vqgan is loaded from: {model_path} [params]") else: raise ValueError("Wrong params!") def forward(self, x): x = self.encoder(x) quant, codebook_loss, quant_stats = self.quantize(x) x = self.generator(quant) return x, codebook_loss, quant_stats def calc_mean_std(feat, eps=1e-5): size = feat.size() assert len(size) == 4, "The input feature should be 4D tensor." b, c = size[:2] feat_var = feat.view(b, c, -1).var(dim=2) + eps feat_std = feat_var.sqrt().view(b, c, 1, 1) feat_mean = feat.view(b, c, -1).mean(dim=2).view(b, c, 1, 1) return feat_mean, feat_std def adaptive_instance_normalization(content_feat, style_feat): size = content_feat.size() style_mean, style_std = calc_mean_std(style_feat) content_mean, content_std = calc_mean_std(content_feat) normalized_feat = (content_feat - content_mean.expand(size)) / content_std.expand( size ) return normalized_feat * style_std.expand(size) + style_mean.expand(size) class PositionEmbeddingSine(nn.Module): def __init__( self, num_pos_feats=64, temperature=10000, normalize=False, scale=None ): super().__init__() self.num_pos_feats = num_pos_feats self.temperature = temperature self.normalize = normalize if scale is not None and normalize is False: raise ValueError("normalize should be True if scale is passed") if scale is None: scale = 2 * math.pi self.scale = scale def forward(self, x, mask=None): if mask is None: mask = torch.zeros( (x.size(0), x.size(2), x.size(3)), device=x.device, dtype=torch.bool ) not_mask = ~mask # pylint: disable=invalid-unary-operand-type y_embed = not_mask.cumsum(1, dtype=torch.float32) x_embed = not_mask.cumsum(2, dtype=torch.float32) if self.normalize: eps = 1e-6 y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats) pos_x = x_embed[:, :, :, None] / dim_t pos_y = y_embed[:, :, :, None] / dim_t pos_x = torch.stack( (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4 ).flatten(3) pos_y = torch.stack( (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4 ).flatten(3) pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2) return pos def _get_activation_fn(activation): if activation == "relu": return F.relu if activation == "gelu": return F.gelu if activation == "glu": return F.glu raise RuntimeError(f"activation should be relu/gelu, not {activation}.") class TransformerSALayer(nn.Module): def __init__( self, embed_dim, nhead=8, dim_mlp=2048, dropout=0.0, activation="gelu" ): super().__init__() self.self_attn = nn.MultiheadAttention(embed_dim, nhead, dropout=dropout) # Implementation of Feedforward model - MLP self.linear1 = nn.Linear(embed_dim, dim_mlp) self.dropout = nn.Dropout(dropout) self.linear2 = nn.Linear(dim_mlp, embed_dim) self.norm1 = nn.LayerNorm(embed_dim) self.norm2 = nn.LayerNorm(embed_dim) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.activation = _get_activation_fn(activation) def with_pos_embed(self, tensor, pos: Optional[Tensor]): return tensor if pos is None else tensor + pos def forward( self, tgt, tgt_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, query_pos: Optional[Tensor] = None, ): # self attention tgt2 = self.norm1(tgt) q = k = self.with_pos_embed(tgt2, query_pos) tgt2 = self.self_attn( q, k, value=tgt2, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask )[0] tgt = tgt + self.dropout1(tgt2) # ffn tgt2 = self.norm2(tgt) tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2)))) tgt = tgt + self.dropout2(tgt2) return tgt def normalize(in_channels): return torch.nn.GroupNorm( num_groups=32, num_channels=in_channels, eps=1e-6, affine=True ) @torch.jit.script # type: ignore def swish(x): return x * torch.sigmoid(x) class ResBlock(nn.Module): def __init__(self, in_channels, out_channels=None): super(ResBlock, self).__init__() self.in_channels = in_channels self.out_channels = in_channels if out_channels is None else out_channels self.norm1 = normalize(in_channels) self.conv1 = nn.Conv2d( in_channels, out_channels, kernel_size=3, stride=1, padding=1 # type: ignore ) self.norm2 = normalize(out_channels) self.conv2 = nn.Conv2d( out_channels, out_channels, kernel_size=3, stride=1, padding=1 # type: ignore ) if self.in_channels != self.out_channels: self.conv_out = nn.Conv2d( in_channels, out_channels, kernel_size=1, stride=1, padding=0 # type: ignore ) def forward(self, x_in): x = x_in x = self.norm1(x) x = swish(x) x = self.conv1(x) x = self.norm2(x) x = swish(x) x = self.conv2(x) if self.in_channels != self.out_channels: x_in = self.conv_out(x_in) return x + x_in class Fuse_sft_block(nn.Module): def __init__(self, in_ch, out_ch): super().__init__() self.encode_enc = ResBlock(2 * in_ch, out_ch) self.scale = nn.Sequential( nn.Conv2d(in_ch, out_ch, kernel_size=3, padding=1), nn.LeakyReLU(0.2, True), nn.Conv2d(out_ch, out_ch, kernel_size=3, padding=1), ) self.shift = nn.Sequential( nn.Conv2d(in_ch, out_ch, kernel_size=3, padding=1), nn.LeakyReLU(0.2, True), nn.Conv2d(out_ch, out_ch, kernel_size=3, padding=1), ) def forward(self, enc_feat, dec_feat, w=1): enc_feat = self.encode_enc(torch.cat([enc_feat, dec_feat], dim=1)) scale = self.scale(enc_feat) shift = self.shift(enc_feat) residual = w * (dec_feat * scale + shift) out = dec_feat + residual return out class CodeFormer(VQAutoEncoder): def __init__(self, state_dict): dim_embd = 512 n_head = 8 n_layers = 9 codebook_size = 1024 latent_size = 256 connect_list = ["32", "64", "128", "256"] fix_modules = ["quantize", "generator"] # This is just a guess as I only have one model to look at position_emb = state_dict["position_emb"] dim_embd = position_emb.shape[1] latent_size = position_emb.shape[0] try: n_layers = len( set([x.split(".")[1] for x in state_dict.keys() if "ft_layers" in x]) ) except: pass codebook_size = state_dict["quantize.embedding.weight"].shape[0] # This is also just another guess n_head_exp = ( state_dict["ft_layers.0.self_attn.in_proj_weight"].shape[0] // dim_embd ) n_head = 2**n_head_exp in_nc = state_dict["encoder.blocks.0.weight"].shape[1] self.model_arch = "CodeFormer" self.sub_type = "Face SR" self.scale = 8 self.in_nc = in_nc self.out_nc = in_nc self.state = state_dict self.supports_fp16 = False self.supports_bf16 = True self.min_size_restriction = 16 super(CodeFormer, self).__init__( 512, 64, [1, 2, 2, 4, 4, 8], "nearest", 2, [16], codebook_size ) if fix_modules is not None: for module in fix_modules: for param in getattr(self, module).parameters(): param.requires_grad = False self.connect_list = connect_list self.n_layers = n_layers self.dim_embd = dim_embd self.dim_mlp = dim_embd * 2 self.position_emb = nn.Parameter(torch.zeros(latent_size, self.dim_embd)) # type: ignore self.feat_emb = nn.Linear(256, self.dim_embd) # transformer self.ft_layers = nn.Sequential( *[ TransformerSALayer( embed_dim=dim_embd, nhead=n_head, dim_mlp=self.dim_mlp, dropout=0.0 ) for _ in range(self.n_layers) ] ) # logits_predict head self.idx_pred_layer = nn.Sequential( nn.LayerNorm(dim_embd), nn.Linear(dim_embd, codebook_size, bias=False) ) self.channels = { "16": 512, "32": 256, "64": 256, "128": 128, "256": 128, "512": 64, } # after second residual block for > 16, before attn layer for ==16 self.fuse_encoder_block = { "512": 2, "256": 5, "128": 8, "64": 11, "32": 14, "16": 18, } # after first residual block for > 16, before attn layer for ==16 self.fuse_generator_block = { "16": 6, "32": 9, "64": 12, "128": 15, "256": 18, "512": 21, } # fuse_convs_dict self.fuse_convs_dict = nn.ModuleDict() for f_size in self.connect_list: in_ch = self.channels[f_size] self.fuse_convs_dict[f_size] = Fuse_sft_block(in_ch, in_ch) self.load_state_dict(state_dict) def _init_weights(self, module): if isinstance(module, (nn.Linear, nn.Embedding)): module.weight.data.normal_(mean=0.0, std=0.02) if isinstance(module, nn.Linear) and module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.LayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) def forward(self, x, weight=0.5, **kwargs): detach_16 = True code_only = False adain = True # ################### Encoder ##################### enc_feat_dict = {} out_list = [self.fuse_encoder_block[f_size] for f_size in self.connect_list] for i, block in enumerate(self.encoder.blocks): x = block(x) if i in out_list: enc_feat_dict[str(x.shape[-1])] = x.clone() lq_feat = x # ################# Transformer ################### # quant_feat, codebook_loss, quant_stats = self.quantize(lq_feat) pos_emb = self.position_emb.unsqueeze(1).repeat(1, x.shape[0], 1) # BCHW -> BC(HW) -> (HW)BC feat_emb = self.feat_emb(lq_feat.flatten(2).permute(2, 0, 1)) query_emb = feat_emb # Transformer encoder for layer in self.ft_layers: query_emb = layer(query_emb, query_pos=pos_emb) # output logits logits = self.idx_pred_layer(query_emb) # (hw)bn logits = logits.permute(1, 0, 2) # (hw)bn -> b(hw)n if code_only: # for training stage II # logits doesn't need softmax before cross_entropy loss return logits, lq_feat # ################# Quantization ################### # if self.training: # quant_feat = torch.einsum('btn,nc->btc', [soft_one_hot, self.quantize.embedding.weight]) # # b(hw)c -> bc(hw) -> bchw # quant_feat = quant_feat.permute(0,2,1).view(lq_feat.shape) # ------------ soft_one_hot = F.softmax(logits, dim=2) _, top_idx = torch.topk(soft_one_hot, 1, dim=2) quant_feat = self.quantize.get_codebook_feat( top_idx, shape=[x.shape[0], 16, 16, 256] # type: ignore ) # preserve gradients # quant_feat = lq_feat + (quant_feat - lq_feat).detach() if detach_16: quant_feat = quant_feat.detach() # for training stage III if adain: quant_feat = adaptive_instance_normalization(quant_feat, lq_feat) # ################## Generator #################### x = quant_feat fuse_list = [self.fuse_generator_block[f_size] for f_size in self.connect_list] for i, block in enumerate(self.generator.blocks): x = block(x) if i in fuse_list: # fuse after i-th block f_size = str(x.shape[-1]) if weight > 0: x = self.fuse_convs_dict[f_size]( enc_feat_dict[f_size].detach(), x, weight ) out = x # logits doesn't need softmax before cross_entropy loss # return out, logits, lq_feat return out, logits
--- +++ @@ -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 GFPGAN. If this is a problem, please contact me. +""" import math from typing import Optional @@ -393,6 +399,12 @@ def calc_mean_std(feat, eps=1e-5): + """Calculate mean and std for adaptive_instance_normalization. + Args: + feat (Tensor): 4D tensor. + eps (float): A small value added to the variance to avoid + divide-by-zero. Default: 1e-5. + """ size = feat.size() assert len(size) == 4, "The input feature should be 4D tensor." b, c = size[:2] @@ -403,6 +415,13 @@ def adaptive_instance_normalization(content_feat, style_feat): + """Adaptive instance normalization. + Adjust the reference features to have the similar color and illuminations + as those in the degradate features. + Args: + content_feat (Tensor): The reference feature. + style_feat (Tensor): The degradate features. + """ size = content_feat.size() style_mean, style_std = calc_mean_std(style_feat) content_mean, content_std = calc_mean_std(content_feat) @@ -413,6 +432,10 @@ class PositionEmbeddingSine(nn.Module): + """ + This is a more standard version of the position embedding, very similar to the one + used by the Attention is all you need paper, generalized to work on images. + """ def __init__( self, num_pos_feats=64, temperature=10000, normalize=False, scale=None @@ -456,6 +479,7 @@ def _get_activation_fn(activation): + """Return an activation function given a string""" if activation == "relu": return F.relu if activation == "gelu": @@ -763,4 +787,4 @@ out = x # logits doesn't need softmax before cross_entropy loss # return out, logits, lq_feat - return out, logits+ return out, logits
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, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class IRBlock(nn.Module): expansion = 1 # output channel expansion ratio def __init__(self, inplanes, planes, stride=1, downsample=None, use_se=True): super(IRBlock, self).__init__() self.bn0 = nn.BatchNorm2d(inplanes) self.conv1 = conv3x3(inplanes, inplanes) self.bn1 = nn.BatchNorm2d(inplanes) self.prelu = nn.PReLU() self.conv2 = conv3x3(inplanes, planes, stride) self.bn2 = nn.BatchNorm2d(planes) self.downsample = downsample self.stride = stride self.use_se = use_se if self.use_se: self.se = SEBlock(planes) def forward(self, x): residual = x out = self.bn0(x) out = self.conv1(out) out = self.bn1(out) out = self.prelu(out) out = self.conv2(out) out = self.bn2(out) if self.use_se: out = self.se(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.prelu(out) return out class Bottleneck(nn.Module): expansion = 4 # output channel expansion ratio def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d( planes, planes, kernel_size=3, stride=stride, padding=1, bias=False ) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d( planes, planes * self.expansion, kernel_size=1, bias=False ) self.bn3 = nn.BatchNorm2d(planes * self.expansion) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class SEBlock(nn.Module): def __init__(self, channel, reduction=16): super(SEBlock, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d( 1 ) # pool to 1x1 without spatial information self.fc = nn.Sequential( nn.Linear(channel, channel // reduction), nn.PReLU(), nn.Linear(channel // reduction, channel), nn.Sigmoid(), ) def forward(self, x): b, c, _, _ = x.size() y = self.avg_pool(x).view(b, c) y = self.fc(y).view(b, c, 1, 1) return x * y class ResNetArcFace(nn.Module): def __init__(self, block, layers, use_se=True): if block == "IRBlock": block = IRBlock self.inplanes = 64 self.use_se = use_se super(ResNetArcFace, self).__init__() self.conv1 = nn.Conv2d(1, 64, kernel_size=3, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(64) self.prelu = nn.PReLU() self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=2) self.bn4 = nn.BatchNorm2d(512) self.dropout = nn.Dropout() self.fc5 = nn.Linear(512 * 8 * 8, 512) self.bn5 = nn.BatchNorm1d(512) # initialization for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.xavier_normal_(m.weight) elif isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.BatchNorm1d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.xavier_normal_(m.weight) nn.init.constant_(m.bias, 0) def _make_layer(self, block, planes, num_blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d( self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False, ), nn.BatchNorm2d(planes * block.expansion), ) layers = [] layers.append( block(self.inplanes, planes, stride, downsample, use_se=self.use_se) ) self.inplanes = planes for _ in range(1, num_blocks): layers.append(block(self.inplanes, planes, use_se=self.use_se)) return nn.Sequential(*layers) def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.prelu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.bn4(x) x = self.dropout(x) x = x.view(x.size(0), -1) x = self.fc5(x) x = self.bn5(x) return x
--- +++ @@ -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. + """ return nn.Conv2d( inplanes, outplanes, kernel_size=3, stride=stride, padding=1, bias=False ) class BasicBlock(nn.Module): + """Basic residual block used in the ResNetArcFace architecture. + + Args: + inplanes (int): Channel number of inputs. + planes (int): Channel number of outputs. + stride (int): Stride in convolution. Default: 1. + downsample (nn.Module): The downsample module. Default: None. + """ expansion = 1 # output channel expansion ratio @@ -41,6 +56,15 @@ class IRBlock(nn.Module): + """Improved residual block (IR Block) used in the ResNetArcFace architecture. + + Args: + inplanes (int): Channel number of inputs. + planes (int): Channel number of outputs. + stride (int): Stride in convolution. Default: 1. + downsample (nn.Module): The downsample module. Default: None. + use_se (bool): Whether use the SEBlock (squeeze and excitation block). Default: True. + """ expansion = 1 # output channel expansion ratio @@ -80,6 +104,14 @@ class Bottleneck(nn.Module): + """Bottleneck block used in the ResNetArcFace architecture. + + Args: + inplanes (int): Channel number of inputs. + planes (int): Channel number of outputs. + stride (int): Stride in convolution. Default: 1. + downsample (nn.Module): The downsample module. Default: None. + """ expansion = 4 # output channel expansion ratio @@ -123,6 +155,12 @@ class SEBlock(nn.Module): + """The squeeze-and-excitation block (SEBlock) used in the IRBlock. + + Args: + channel (int): Channel number of inputs. + reduction (int): Channel reduction ration. Default: 16. + """ def __init__(self, channel, reduction=16): super(SEBlock, self).__init__() @@ -144,6 +182,15 @@ class ResNetArcFace(nn.Module): + """ArcFace with ResNet architectures. + + Ref: ArcFace: Additive Angular Margin Loss for Deep Face Recognition. + + Args: + block (str): Block used in the ArcFace architecture. + layers (tuple(int)): Block numbers in each layer. + use_se (bool): Whether use the SEBlock (squeeze and excitation block). Default: True. + """ def __init__(self, block, layers, use_se=True): if block == "IRBlock": @@ -215,4 +262,4 @@ x = self.fc5(x) x = self.bn5(x) - return x+ return x
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 act(act_type: str, inplace=True, neg_slope=0.2, n_prelu=1): # helper selecting activation # neg_slope: for leakyrelu and init of prelu # n_prelu: for p_relu num_parameters act_type = act_type.lower() if act_type == "relu": layer = nn.ReLU(inplace) elif act_type == "leakyrelu": layer = nn.LeakyReLU(neg_slope, inplace) elif act_type == "prelu": layer = nn.PReLU(num_parameters=n_prelu, init=neg_slope) else: raise NotImplementedError( "activation layer [{:s}] is not found".format(act_type) ) return layer def norm(norm_type: str, nc: int): # helper selecting normalization layer norm_type = norm_type.lower() if norm_type == "batch": layer = nn.BatchNorm2d(nc, affine=True) elif norm_type == "instance": layer = nn.InstanceNorm2d(nc, affine=False) else: raise NotImplementedError( "normalization layer [{:s}] is not found".format(norm_type) ) return layer def pad(pad_type: str, padding): # helper selecting padding layer # if padding is 'zero', do by conv layers pad_type = pad_type.lower() if padding == 0: return None if pad_type == "reflect": layer = nn.ReflectionPad2d(padding) elif pad_type == "replicate": layer = nn.ReplicationPad2d(padding) else: raise NotImplementedError( "padding layer [{:s}] is not implemented".format(pad_type) ) return layer def get_valid_padding(kernel_size, dilation): kernel_size = kernel_size + (kernel_size - 1) * (dilation - 1) padding = (kernel_size - 1) // 2 return padding class ConcatBlock(nn.Module): # Concat the output of a submodule to its input def __init__(self, submodule): super(ConcatBlock, self).__init__() self.sub = submodule def forward(self, x): output = torch.cat((x, self.sub(x)), dim=1) return output def __repr__(self): tmpstr = "Identity .. \n|" modstr = self.sub.__repr__().replace("\n", "\n|") tmpstr = tmpstr + modstr return tmpstr class ShortcutBlock(nn.Module): # Elementwise sum the output of a submodule to its input def __init__(self, submodule): super(ShortcutBlock, self).__init__() self.sub = submodule def forward(self, x): output = x + self.sub(x) return output def __repr__(self): tmpstr = "Identity + \n|" modstr = self.sub.__repr__().replace("\n", "\n|") tmpstr = tmpstr + modstr return tmpstr class ShortcutBlockSPSR(nn.Module): # Elementwise sum the output of a submodule to its input def __init__(self, submodule): super(ShortcutBlockSPSR, self).__init__() self.sub = submodule def forward(self, x): return x, self.sub def __repr__(self): tmpstr = "Identity + \n|" modstr = self.sub.__repr__().replace("\n", "\n|") tmpstr = tmpstr + modstr return tmpstr def sequential(*args): # Flatten Sequential. It unwraps nn.Sequential. if len(args) == 1: if isinstance(args[0], OrderedDict): raise NotImplementedError("sequential does not support OrderedDict input.") return args[0] # No sequential is needed. modules = [] for module in args: if isinstance(module, nn.Sequential): for submodule in module.children(): modules.append(submodule) elif isinstance(module, nn.Module): modules.append(module) return nn.Sequential(*modules) ConvMode = Literal["CNA", "NAC", "CNAC"] # 2x2x2 Conv Block def conv_block_2c2( in_nc, out_nc, act_type="relu", ): return sequential( nn.Conv2d(in_nc, out_nc, kernel_size=2, padding=1), nn.Conv2d(out_nc, out_nc, kernel_size=2, padding=0), act(act_type) if act_type else None, ) def conv_block( in_nc: int, out_nc: int, kernel_size, stride=1, dilation=1, groups=1, bias=True, pad_type="zero", norm_type: str | None = None, act_type: str | None = "relu", mode: ConvMode = "CNA", c2x2=False, ): if c2x2: return conv_block_2c2(in_nc, out_nc, act_type=act_type) assert mode in ("CNA", "NAC", "CNAC"), "Wrong conv mode [{:s}]".format(mode) padding = get_valid_padding(kernel_size, dilation) p = pad(pad_type, padding) if pad_type and pad_type != "zero" else None padding = padding if pad_type == "zero" else 0 c = nn.Conv2d( in_nc, out_nc, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, bias=bias, groups=groups, ) a = act(act_type) if act_type else None if mode in ("CNA", "CNAC"): n = norm(norm_type, out_nc) if norm_type else None return sequential(p, c, n, a) elif mode == "NAC": if norm_type is None and act_type is not None: a = act(act_type, inplace=False) # Important! # input----ReLU(inplace)----Conv--+----output # |________________________| # inplace ReLU will modify the input, therefore wrong output n = norm(norm_type, in_nc) if norm_type else None return sequential(n, a, p, c) else: assert False, f"Invalid conv mode {mode}" #################### # Useful blocks #################### class ResNetBlock(nn.Module): def __init__( self, in_nc, mid_nc, out_nc, kernel_size=3, stride=1, dilation=1, groups=1, bias=True, pad_type="zero", norm_type=None, act_type="relu", mode: ConvMode = "CNA", res_scale=1, ): super(ResNetBlock, self).__init__() conv0 = conv_block( in_nc, mid_nc, kernel_size, stride, dilation, groups, bias, pad_type, norm_type, act_type, mode, ) if mode == "CNA": act_type = None if mode == "CNAC": # Residual path: |-CNAC-| act_type = None norm_type = None conv1 = conv_block( mid_nc, out_nc, kernel_size, stride, dilation, groups, bias, pad_type, norm_type, act_type, mode, ) # if in_nc != out_nc: # self.project = conv_block(in_nc, out_nc, 1, stride, dilation, 1, bias, pad_type, \ # None, None) # print('Need a projecter in ResNetBlock.') # else: # self.project = lambda x:x self.res = sequential(conv0, conv1) self.res_scale = res_scale def forward(self, x): res = self.res(x).mul(self.res_scale) return x + res class RRDB(nn.Module): def __init__( self, nf, kernel_size=3, gc=32, stride=1, bias: bool = True, pad_type="zero", norm_type=None, act_type="leakyrelu", mode: ConvMode = "CNA", _convtype="Conv2D", _spectral_norm=False, plus=False, c2x2=False, ): super(RRDB, self).__init__() self.RDB1 = ResidualDenseBlock_5C( nf, kernel_size, gc, stride, bias, pad_type, norm_type, act_type, mode, plus=plus, c2x2=c2x2, ) self.RDB2 = ResidualDenseBlock_5C( nf, kernel_size, gc, stride, bias, pad_type, norm_type, act_type, mode, plus=plus, c2x2=c2x2, ) self.RDB3 = ResidualDenseBlock_5C( nf, kernel_size, gc, stride, bias, pad_type, norm_type, act_type, mode, plus=plus, c2x2=c2x2, ) def forward(self, x): out = self.RDB1(x) out = self.RDB2(out) out = self.RDB3(out) return out * 0.2 + x class ResidualDenseBlock_5C(nn.Module): def __init__( self, nf=64, kernel_size=3, gc=32, stride=1, bias: bool = True, pad_type="zero", norm_type=None, act_type="leakyrelu", mode: ConvMode = "CNA", plus=False, c2x2=False, ): super(ResidualDenseBlock_5C, self).__init__() ## + self.conv1x1 = conv1x1(nf, gc) if plus else None ## + self.conv1 = conv_block( nf, gc, kernel_size, stride, bias=bias, pad_type=pad_type, norm_type=norm_type, act_type=act_type, mode=mode, c2x2=c2x2, ) self.conv2 = conv_block( nf + gc, gc, kernel_size, stride, bias=bias, pad_type=pad_type, norm_type=norm_type, act_type=act_type, mode=mode, c2x2=c2x2, ) self.conv3 = conv_block( nf + 2 * gc, gc, kernel_size, stride, bias=bias, pad_type=pad_type, norm_type=norm_type, act_type=act_type, mode=mode, c2x2=c2x2, ) self.conv4 = conv_block( nf + 3 * gc, gc, kernel_size, stride, bias=bias, pad_type=pad_type, norm_type=norm_type, act_type=act_type, mode=mode, c2x2=c2x2, ) if mode == "CNA": last_act = None else: last_act = act_type self.conv5 = conv_block( nf + 4 * gc, nf, 3, stride, bias=bias, pad_type=pad_type, norm_type=norm_type, act_type=last_act, mode=mode, c2x2=c2x2, ) def forward(self, x): x1 = self.conv1(x) x2 = self.conv2(torch.cat((x, x1), 1)) if self.conv1x1: # pylint: disable=not-callable x2 = x2 + self.conv1x1(x) # + x3 = self.conv3(torch.cat((x, x1, x2), 1)) x4 = self.conv4(torch.cat((x, x1, x2, x3), 1)) if self.conv1x1: x4 = x4 + x2 # + x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1)) return x5 * 0.2 + x def conv1x1(in_planes, out_planes, stride=1): return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) #################### # Upsampler #################### def pixelshuffle_block( in_nc: int, out_nc: int, upscale_factor=2, kernel_size=3, stride=1, bias=True, pad_type="zero", norm_type: str | None = None, act_type="relu", ): conv = conv_block( in_nc, out_nc * (upscale_factor**2), kernel_size, stride, bias=bias, pad_type=pad_type, norm_type=None, act_type=None, ) pixel_shuffle = nn.PixelShuffle(upscale_factor) n = norm(norm_type, out_nc) if norm_type else None a = act(act_type) if act_type else None return sequential(conv, pixel_shuffle, n, a) def upconv_block( in_nc: int, out_nc: int, upscale_factor=2, kernel_size=3, stride=1, bias=True, pad_type="zero", norm_type: str | None = None, act_type="relu", mode="nearest", c2x2=False, ): # Up conv # described in https://distill.pub/2016/deconv-checkerboard/ upsample = nn.Upsample(scale_factor=upscale_factor, mode=mode) conv = conv_block( in_nc, out_nc, kernel_size, stride, bias=bias, pad_type=pad_type, norm_type=norm_type, act_type=act_type, c2x2=c2x2, ) return sequential(upsample, conv)
--- +++ @@ -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_block_2c2(in_nc, out_nc, act_type=act_type) @@ -210,6 +215,11 @@ class ResNetBlock(nn.Module): + """ + ResNet Block, 3-3 style + with extra residual scaling used in EDSR + (Enhanced Deep Residual Networks for Single Image Super-Resolution, CVPRW 17) + """ def __init__( self, @@ -274,6 +284,10 @@ class RRDB(nn.Module): + """ + Residual in Residual Dense Block + (ESRGAN: Enhanced Super-Resolution Generative Adversarial Networks) + """ def __init__( self, @@ -340,6 +354,26 @@ class ResidualDenseBlock_5C(nn.Module): + """ + Residual Dense Block + style: 5 convs + The core module of paper: (Residual Dense Network for Image Super-Resolution, CVPR 18) + Modified options that can be used: + - "Partial Convolution based Padding" arXiv:1811.11718 + - "Spectral normalization" arXiv:1802.05957 + - "ICASSP 2020 - ESRGAN+ : Further Improving ESRGAN" N. C. + {Rakotonirina} and A. {Rasoanaivo} + + Args: + nf (int): Channel number of intermediate features (num_feat). + gc (int): Channels for each growth (num_grow_ch: growth channel, + i.e. intermediate channels). + convtype (str): the type of convolution to use. Default: 'Conv2D' + gaussian_noise (bool): enable the ESRGAN+ gaussian noise (no new + trainable parameters) + plus (bool): enable the additional residual paths from ESRGAN+ + (adds trainable parameters) + """ def __init__( self, @@ -460,6 +494,11 @@ norm_type: str | None = None, act_type="relu", ): + """ + Pixel shuffle layer + (Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional + Neural Network, CVPR17) + """ conv = conv_block( in_nc, out_nc * (upscale_factor**2), @@ -504,4 +543,4 @@ act_type=act_type, c2x2=c2x2, ) - return sequential(upsample, conv)+ return sequential(upsample, 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_group from gradio_client.serializing import ImgSerializable from PIL import Image as _Image # using _ to minimize namespace pollution from gradio import processing_utils, utils, Error from gradio.components.base import IOComponent, _Keywords, Block from gradio.deprecation import warn_style_method_deprecation from gradio.events import ( Changeable, Clearable, Editable, EventListenerMethod, Selectable, Streamable, Uploadable, ) from gradio.interpretation import TokenInterpretable set_documentation_group("component") _Image.init() # fixes https://github.com/gradio-app/gradio/issues/2843 @document() class Image( Editable, Clearable, Changeable, Streamable, Selectable, Uploadable, IOComponent, ImgSerializable, TokenInterpretable, ): def __init__( self, value: str | _Image.Image | np.ndarray | None = None, *, shape: tuple[int, int] | None = None, height: int | None = None, width: int | None = None, image_mode: Literal[ "1", "L", "P", "RGB", "RGBA", "CMYK", "YCbCr", "LAB", "HSV", "I", "F" ] = "RGB", invert_colors: bool = False, source: Literal["upload", "webcam", "canvas"] = "upload", tool: Literal["editor", "select", "sketch", "color-sketch"] | None = None, type: Literal["numpy", "pil", "filepath"] = "numpy", label: str | None = None, every: float | None = None, show_label: bool | None = None, show_download_button: bool = True, container: bool = True, scale: int | None = None, min_width: int = 160, interactive: bool | None = None, visible: bool = True, streaming: bool = False, elem_id: str | None = None, elem_classes: list[str] | str | None = None, mirror_webcam: bool = True, brush_radius: float | None = None, brush_color: str = "#000000", mask_opacity: float = 0.7, show_share_button: bool | None = None, **kwargs, ): self.brush_radius = brush_radius self.brush_color = brush_color self.mask_opacity = mask_opacity self.mirror_webcam = mirror_webcam valid_types = ["numpy", "pil", "filepath"] if type not in valid_types: raise ValueError( f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}" ) self.type = type self.shape = shape self.height = height self.width = width self.image_mode = image_mode valid_sources = ["upload", "webcam", "canvas"] if source not in valid_sources: raise ValueError( f"Invalid value for parameter `source`: {source}. Please choose from one of: {valid_sources}" ) self.source = source if tool is None: self.tool = "sketch" if source == "canvas" else "editor" else: self.tool = tool self.invert_colors = invert_colors self.streaming = streaming self.show_download_button = show_download_button if streaming and source != "webcam": raise ValueError("Image streaming only available if source is 'webcam'.") self.select: EventListenerMethod """ Event listener for when the user clicks on a pixel within the image. Uses event data gradio.SelectData to carry `index` to refer to the [x, y] coordinates of the clicked pixel. See EventData documentation on how to use this event data. """ self.show_share_button = ( (utils.get_space() is not None) if show_share_button is None else show_share_button ) IOComponent.__init__( self, label=label, every=every, show_label=show_label, container=container, scale=scale, min_width=min_width, interactive=interactive, visible=visible, elem_id=elem_id, elem_classes=elem_classes, value=value, **kwargs, ) TokenInterpretable.__init__(self) def get_config(self): return { "image_mode": self.image_mode, "shape": self.shape, "height": self.height, "width": self.width, "source": self.source, "tool": self.tool, "value": self.value, "streaming": self.streaming, "mirror_webcam": self.mirror_webcam, "brush_radius": self.brush_radius, "brush_color": self.brush_color, "mask_opacity": self.mask_opacity, "selectable": self.selectable, "show_share_button": self.show_share_button, "show_download_button": self.show_download_button, **IOComponent.get_config(self), } @staticmethod def update( value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE, height: int | None = None, width: int | None = None, label: str | None = None, show_label: bool | None = None, show_download_button: bool | None = None, container: bool | None = None, scale: int | None = None, min_width: int | None = None, interactive: bool | None = None, visible: bool | None = None, brush_radius: float | None = None, brush_color: str | None = None, mask_opacity: float | None = None, show_share_button: bool | None = None, ): return { "height": height, "width": width, "label": label, "show_label": show_label, "show_download_button": show_download_button, "container": container, "scale": scale, "min_width": min_width, "interactive": interactive, "visible": visible, "value": value, "brush_radius": brush_radius, "brush_color": brush_color, "mask_opacity": mask_opacity, "show_share_button": show_share_button, "__type__": "update", } def _format_image( self, im: _Image.Image | None ) -> np.ndarray | _Image.Image | str | None: if im is None: return im fmt = im.format if self.type == "pil": return im elif self.type == "numpy": return np.array(im) elif self.type == "filepath": path = self.pil_to_temp_file( im, dir=self.DEFAULT_TEMP_DIR, format=fmt or "png" ) self.temp_files.add(path) return path else: raise ValueError( "Unknown type: " + str(self.type) + ". Please choose from: 'numpy', 'pil', 'filepath'." ) def preprocess( self, x: str | dict[str, str] ) -> np.ndarray | _Image.Image | str | dict | None: if x is None: return x mask = None if self.tool == "sketch" and self.source in ["upload", "webcam"]: if isinstance(x, dict): x, mask = x["image"], x["mask"] assert isinstance(x, str) try: im = processing_utils.decode_base64_to_image(x) except PIL.UnidentifiedImageError: raise Error("Unsupported image type in input") with warnings.catch_warnings(): warnings.simplefilter("ignore") im = im.convert(self.image_mode) if self.shape is not None: im = processing_utils.resize_and_crop(im, self.shape) if self.invert_colors: im = PIL.ImageOps.invert(im) if ( self.source == "webcam" and self.mirror_webcam is True and self.tool != "color-sketch" ): im = PIL.ImageOps.mirror(im) if self.tool == "sketch" and self.source in ["upload", "webcam"]: if mask is not None: mask_im = processing_utils.decode_base64_to_image(mask) if mask_im.mode == "RGBA": # whiten any opaque pixels in the mask alpha_data = mask_im.getchannel("A").convert("L") mask_im = _Image.merge("RGB", [alpha_data, alpha_data, alpha_data]) return { "image": self._format_image(im), "mask": self._format_image(mask_im), } else: return { "image": self._format_image(im), "mask": None, } return self._format_image(im) def postprocess( self, y: np.ndarray | _Image.Image | str | Path | None ) -> str | None: if y is None: return None if isinstance(y, np.ndarray): return processing_utils.encode_array_to_base64(y) elif isinstance(y, _Image.Image): return processing_utils.encode_pil_to_base64(y) elif isinstance(y, (str, Path)): return client_utils.encode_url_or_file_to_base64(y) else: raise ValueError("Cannot process this value as an Image") def set_interpret_parameters(self, segments: int = 16): self.interpretation_segments = segments return self def _segment_by_slic(self, x): x = processing_utils.decode_base64_to_image(x) if self.shape is not None: x = processing_utils.resize_and_crop(x, self.shape) resized_and_cropped_image = np.array(x) try: from skimage.segmentation import slic except (ImportError, ModuleNotFoundError) as err: raise ValueError( "Error: running this interpretation for images requires scikit-image, please install it first." ) from err try: segments_slic = slic( resized_and_cropped_image, self.interpretation_segments, compactness=10, sigma=1, start_label=1, ) except TypeError: # For skimage 0.16 and older segments_slic = slic( resized_and_cropped_image, self.interpretation_segments, compactness=10, sigma=1, ) return segments_slic, resized_and_cropped_image def tokenize(self, x): segments_slic, resized_and_cropped_image = self._segment_by_slic(x) tokens, masks, leave_one_out_tokens = [], [], [] replace_color = np.mean(resized_and_cropped_image, axis=(0, 1)) for segment_value in np.unique(segments_slic): mask = segments_slic == segment_value image_screen = np.copy(resized_and_cropped_image) image_screen[segments_slic == segment_value] = replace_color leave_one_out_tokens.append( processing_utils.encode_array_to_base64(image_screen) ) token = np.copy(resized_and_cropped_image) token[segments_slic != segment_value] = 0 tokens.append(token) masks.append(mask) return tokens, leave_one_out_tokens, masks def get_masked_inputs(self, tokens, binary_mask_matrix): masked_inputs = [] for binary_mask_vector in binary_mask_matrix: masked_input = np.zeros_like(tokens[0], dtype=int) for token, b in zip(tokens, binary_mask_vector): masked_input = masked_input + token * int(b) masked_inputs.append(processing_utils.encode_array_to_base64(masked_input)) return masked_inputs def get_interpretation_scores( self, x, neighbors, scores, masks, tokens=None, **kwargs ) -> list[list[float]]: x = processing_utils.decode_base64_to_image(x) if self.shape is not None: x = processing_utils.resize_and_crop(x, self.shape) x = np.array(x) output_scores = np.zeros((x.shape[0], x.shape[1])) for score, mask in zip(scores, masks): output_scores += score * mask max_val, min_val = np.max(output_scores), np.min(output_scores) if max_val > 0: output_scores = (output_scores - min_val) / (max_val - min_val) return output_scores.tolist() def style(self, *, height: int | None = None, width: int | None = None, **kwargs): warn_style_method_deprecation() if height is not None: self.height = height if width is not None: self.width = width return self def check_streamable(self): if self.source != "webcam": raise ValueError("Image streaming only available if source is 'webcam'.") def as_example(self, input_data: str | None) -> str: if input_data is None: return "" elif ( self.root_url ): # If an externally hosted image, don't convert to absolute path return input_data return str(utils.abspath(input_data)) all_components = [] if not hasattr(Block, 'original__init__'): Block.original_init = Block.__init__ def blk_ini(self, *args, **kwargs): all_components.append(self) return Block.original_init(self, *args, **kwargs) Block.__init__ = blk_ini gradio.routes.asyncio = importlib.reload(gradio.routes.asyncio) if not hasattr(gradio.routes.asyncio, 'original_wait_for'): gradio.routes.asyncio.original_wait_for = gradio.routes.asyncio.wait_for def patched_wait_for(fut, timeout): del timeout return gradio.routes.asyncio.original_wait_for(fut, timeout=65535) gradio.routes.asyncio.wait_for = patched_wait_for
--- +++ @@ -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 uploaded image as a {numpy.array}, {PIL.Image} or {str} filepath depending on `type` -- unless `tool` is `sketch` AND source is one of `upload` or `webcam`. In these cases, a {dict} with keys `image` and `mask` is passed, and the format of the corresponding values depends on `type`. + Postprocessing: expects a {numpy.array}, {PIL.Image} or {str} or {pathlib.Path} filepath to an image and displays the image. + Examples-format: a {str} filepath to a local file that contains the image. + Demos: image_mod, image_mod_default_image + Guides: image-classification-in-pytorch, image-classification-in-tensorflow, image-classification-with-vision-transformers, building-a-pictionary_app, create-your-own-friends-with-a-gan + """ def __init__( self, @@ -80,6 +89,35 @@ show_share_button: bool | None = None, **kwargs, ): + """ + Parameters: + value: A PIL Image, numpy array, path or URL for the default value that Image component is going to take. If callable, the function will be called whenever the app loads to set the initial value of the component. + shape: (width, height) shape to crop and resize image when passed to function. If None, matches input image size. Pass None for either width or height to only crop and resize the other. + height: Height of the displayed image in pixels. + width: Width of the displayed image in pixels. + image_mode: "RGB" if color, or "L" if black and white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html for other supported image modes and their meaning. + invert_colors: whether to invert the image as a preprocessing step. + source: Source of image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "canvas" defaults to a white image that can be edited and drawn upon with tools. + tool: Tools used for editing. "editor" allows a full screen editor (and is the default if source is "upload" or "webcam"), "select" provides a cropping and zoom tool, "sketch" allows you to create a binary sketch (and is the default if source="canvas"), and "color-sketch" allows you to created a sketch in different colors. "color-sketch" can be used with source="upload" or "webcam" to allow sketching on an image. "sketch" can also be used with "upload" or "webcam" to create a mask over an image and in that case both the image and mask are passed into the function as a dictionary with keys "image" and "mask" respectively. + type: The format the image is converted to before being passed into the prediction function. "numpy" converts the image to a numpy array with shape (height, width, 3) and values from 0 to 255, "pil" converts the image to a PIL image object, "filepath" passes a str path to a temporary file containing the image. + label: component name in interface. + every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. + show_label: if True, will display label. + show_download_button: If True, will display button to download image. + container: If True, will place the component in a container - providing some extra padding around the border. + scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer. + min_width: minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first. + interactive: if True, will allow users to upload and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output. + visible: If False, component will be hidden. + streaming: If True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'webcam'. + elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. + elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. + mirror_webcam: If True webcam will be mirrored. Default is True. + brush_radius: Size of the brush for Sketch. Default is None which chooses a sensible default + brush_color: Color of the brush for Sketch as hex string. Default is "#000000". + mask_opacity: Opacity of mask drawn on image, as a value between 0 and 1. + show_share_button: If True, will show a share icon in the corner of the component that allows user to share outputs to Hugging Face Spaces Discussions. If False, icon does not appear. If set to None (default behavior), then the icon appears if this Gradio app is launched on Spaces, but not otherwise. + """ self.brush_radius = brush_radius self.brush_color = brush_color self.mask_opacity = mask_opacity @@ -197,6 +235,7 @@ def _format_image( self, im: _Image.Image | None ) -> np.ndarray | _Image.Image | str | None: + """Helper method to format an image based on self.type""" if im is None: return im fmt = im.format @@ -220,6 +259,12 @@ def preprocess( self, x: str | dict[str, str] ) -> np.ndarray | _Image.Image | str | dict | None: + """ + Parameters: + x: base64 url data, or (if tool == "sketch") a dict of image and mask base64 url data + Returns: + image in requested format, or (if tool == "sketch") a dict of image and mask in requested format + """ if x is None: return x @@ -269,6 +314,12 @@ def postprocess( self, y: np.ndarray | _Image.Image | str | Path | None ) -> str | None: + """ + Parameters: + y: image as a numpy array, PIL Image, string/Path filepath, or string URL + Returns: + base64 url data + """ if y is None: return None if isinstance(y, np.ndarray): @@ -281,10 +332,20 @@ raise ValueError("Cannot process this value as an Image") def set_interpret_parameters(self, segments: int = 16): + """ + Calculates interpretation score of image subsections by splitting the image into subsections, then using a "leave one out" method to calculate the score of each subsection by whiting out the subsection and measuring the delta of the output value. + Parameters: + segments: Number of interpretation segments to split image into. + """ self.interpretation_segments = segments return self def _segment_by_slic(self, x): + """ + Helper method that segments an image into superpixels using slic. + Parameters: + x: base64 representation of an image + """ x = processing_utils.decode_base64_to_image(x) if self.shape is not None: x = processing_utils.resize_and_crop(x, self.shape) @@ -313,6 +374,15 @@ return segments_slic, resized_and_cropped_image def tokenize(self, x): + """ + Segments image into tokens, masks, and leave-one-out-tokens + Parameters: + x: base64 representation of an image + Returns: + tokens: list of tokens, used by the get_masked_input() method + leave_one_out_tokens: list of left-out tokens, used by the get_interpretation_neighbors() method + masks: list of masks, used by the get_interpretation_neighbors() method + """ segments_slic, resized_and_cropped_image = self._segment_by_slic(x) tokens, masks, leave_one_out_tokens = [], [], [] replace_color = np.mean(resized_and_cropped_image, axis=(0, 1)) @@ -341,6 +411,10 @@ def get_interpretation_scores( self, x, neighbors, scores, masks, tokens=None, **kwargs ) -> list[list[float]]: + """ + Returns: + A 2D array representing the interpretation score of each pixel of the image. + """ x = processing_utils.decode_base64_to_image(x) if self.shape is not None: x = processing_utils.resize_and_crop(x, self.shape) @@ -356,6 +430,9 @@ return output_scores.tolist() def style(self, *, height: int | None = None, width: int | None = None, **kwargs): + """ + This method is deprecated. Please set these arguments in the constructor instead. + """ warn_style_method_deprecation() if height is not None: self.height = height @@ -403,3 +480,4 @@ gradio.routes.asyncio.wait_for = patched_wait_for +
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. # ----------------------------------------------------------------------------------- import math import re import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint # Originally from the timm package from .timm.drop import DropPath from .timm.helpers import to_2tuple from .timm.weight_init import trunc_normal_ class Mlp(nn.Module): def __init__( self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0, ): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop) def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x def window_partition(x, window_size): B, H, W, C = x.shape x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) windows = ( x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) ) return windows def window_reverse(windows, window_size, H, W): B = int(windows.shape[0] / (H * W / window_size / window_size)) x = windows.view( B, H // window_size, W // window_size, window_size, window_size, -1 ) x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) return x class WindowAttention(nn.Module): def __init__( self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0.0, proj_drop=0.0, ): super().__init__() self.dim = dim self.window_size = window_size # Wh, Ww self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim**-0.5 # define a parameter table of relative position bias self.relative_position_bias_table = nn.Parameter( # type: ignore torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads) ) # 2*Wh-1 * 2*Ww-1, nH # get pair-wise relative position index for each token inside the window coords_h = torch.arange(self.window_size[0]) coords_w = torch.arange(self.window_size[1]) coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww relative_coords = ( coords_flatten[:, :, None] - coords_flatten[:, None, :] ) # 2, Wh*Ww, Wh*Ww relative_coords = relative_coords.permute( 1, 2, 0 ).contiguous() # Wh*Ww, Wh*Ww, 2 relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 relative_coords[:, :, 1] += self.window_size[1] - 1 relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww self.register_buffer("relative_position_index", relative_position_index) self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) trunc_normal_(self.relative_position_bias_table, std=0.02) self.softmax = nn.Softmax(dim=-1) def forward(self, x, mask=None): B_, N, C = x.shape qkv = ( self.qkv(x) .reshape(B_, N, 3, self.num_heads, C // self.num_heads) .permute(2, 0, 3, 1, 4) ) q, k, v = ( qkv[0], qkv[1], qkv[2], ) # make torchscript happy (cannot use tensor as tuple) q = q * self.scale attn = q @ k.transpose(-2, -1) relative_position_bias = self.relative_position_bias_table[ self.relative_position_index.view(-1) # type: ignore ].view( self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1, ) # Wh*Ww,Wh*Ww,nH relative_position_bias = relative_position_bias.permute( 2, 0, 1 ).contiguous() # nH, Wh*Ww, Wh*Ww attn = attn + relative_position_bias.unsqueeze(0) if mask is not None: nW = mask.shape[0] attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze( 1 ).unsqueeze(0) attn = attn.view(-1, self.num_heads, N, N) attn = self.softmax(attn) else: attn = self.softmax(attn) attn = self.attn_drop(attn) x = (attn @ v).transpose(1, 2).reshape(B_, N, C) x = self.proj(x) x = self.proj_drop(x) return x def extra_repr(self) -> str: return f"dim={self.dim}, window_size={self.window_size}, num_heads={self.num_heads}" def flops(self, N): # calculate flops for 1 window with token length of N flops = 0 # qkv = self.qkv(x) flops += N * self.dim * 3 * self.dim # attn = (q @ k.transpose(-2, -1)) flops += self.num_heads * N * (self.dim // self.num_heads) * N # x = (attn @ v) flops += self.num_heads * N * N * (self.dim // self.num_heads) # x = self.proj(x) flops += N * self.dim * self.dim return flops class SwinTransformerBlock(nn.Module): def __init__( self, dim, input_resolution, num_heads, window_size=7, shift_size=0, mlp_ratio=4.0, qkv_bias=True, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm, ): super().__init__() self.dim = dim self.input_resolution = input_resolution self.num_heads = num_heads self.window_size = window_size self.shift_size = shift_size self.mlp_ratio = mlp_ratio if min(self.input_resolution) <= self.window_size: # if window size is larger than input resolution, we don't partition windows self.shift_size = 0 self.window_size = min(self.input_resolution) assert ( 0 <= self.shift_size < self.window_size ), "shift_size must in 0-window_size" self.norm1 = norm_layer(dim) self.attn = WindowAttention( dim, window_size=to_2tuple(self.window_size), num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, ) self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp( in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop, ) if self.shift_size > 0: attn_mask = self.calculate_mask(self.input_resolution) else: attn_mask = None self.register_buffer("attn_mask", attn_mask) def calculate_mask(self, x_size): # calculate attention mask for SW-MSA H, W = x_size img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1 h_slices = ( slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None), ) w_slices = ( slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None), ) cnt = 0 for h in h_slices: for w in w_slices: img_mask[:, h, w, :] = cnt cnt += 1 mask_windows = window_partition( img_mask, self.window_size ) # nW, window_size, window_size, 1 mask_windows = mask_windows.view(-1, self.window_size * self.window_size) attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill( attn_mask == 0, float(0.0) ) return attn_mask def forward(self, x, x_size): H, W = x_size B, L, C = x.shape # assert L == H * W, "input feature has wrong size" shortcut = x x = self.norm1(x) x = x.view(B, H, W, C) # cyclic shift if self.shift_size > 0: shifted_x = torch.roll( x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2) ) else: shifted_x = x # partition windows x_windows = window_partition( shifted_x, self.window_size ) # nW*B, window_size, window_size, C x_windows = x_windows.view( -1, self.window_size * self.window_size, C ) # nW*B, window_size*window_size, C # W-MSA/SW-MSA (to be compatible for testing on images whose shapes are the multiple of window size if self.input_resolution == x_size: attn_windows = self.attn( x_windows, mask=self.attn_mask ) # nW*B, window_size*window_size, C else: attn_windows = self.attn( x_windows, mask=self.calculate_mask(x_size).to(x.device) ) # merge windows attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C # reverse cyclic shift if self.shift_size > 0: x = torch.roll( shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2) ) else: x = shifted_x x = x.view(B, H * W, C) # FFN x = shortcut + self.drop_path(x) x = x + self.drop_path(self.mlp(self.norm2(x))) return x def extra_repr(self) -> str: return ( f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}" ) def flops(self): flops = 0 H, W = self.input_resolution # norm1 flops += self.dim * H * W # W-MSA/SW-MSA nW = H * W / self.window_size / self.window_size flops += nW * self.attn.flops(self.window_size * self.window_size) # mlp flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio # norm2 flops += self.dim * H * W return flops class PatchMerging(nn.Module): def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm): super().__init__() self.input_resolution = input_resolution self.dim = dim self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) self.norm = norm_layer(4 * dim) def forward(self, x): H, W = self.input_resolution B, L, C = x.shape assert L == H * W, "input feature has wrong size" assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even." x = x.view(B, H, W, C) x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C x = self.norm(x) x = self.reduction(x) return x def extra_repr(self) -> str: return f"input_resolution={self.input_resolution}, dim={self.dim}" def flops(self): H, W = self.input_resolution flops = H * W * self.dim flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim return flops class BasicLayer(nn.Module): def __init__( self, dim, input_resolution, depth, num_heads, window_size, mlp_ratio=4.0, qkv_bias=True, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False, ): super().__init__() self.dim = dim self.input_resolution = input_resolution self.depth = depth self.use_checkpoint = use_checkpoint # build blocks self.blocks = nn.ModuleList( [ SwinTransformerBlock( dim=dim, input_resolution=input_resolution, num_heads=num_heads, window_size=window_size, shift_size=0 if (i % 2 == 0) else window_size // 2, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop, attn_drop=attn_drop, drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, norm_layer=norm_layer, ) for i in range(depth) ] ) # patch merging layer if downsample is not None: self.downsample = downsample( input_resolution, dim=dim, norm_layer=norm_layer ) else: self.downsample = None def forward(self, x, x_size): for blk in self.blocks: if self.use_checkpoint: x = checkpoint.checkpoint(blk, x, x_size) else: x = blk(x, x_size) if self.downsample is not None: x = self.downsample(x) return x def extra_repr(self) -> str: return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}" def flops(self): flops = 0 for blk in self.blocks: flops += blk.flops() # type: ignore if self.downsample is not None: flops += self.downsample.flops() return flops class RSTB(nn.Module): def __init__( self, dim, input_resolution, depth, num_heads, window_size, mlp_ratio=4.0, qkv_bias=True, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False, img_size=224, patch_size=4, resi_connection="1conv", ): super(RSTB, self).__init__() self.dim = dim self.input_resolution = input_resolution self.residual_group = BasicLayer( dim=dim, input_resolution=input_resolution, depth=depth, num_heads=num_heads, window_size=window_size, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop, attn_drop=attn_drop, drop_path=drop_path, norm_layer=norm_layer, downsample=downsample, use_checkpoint=use_checkpoint, ) if resi_connection == "1conv": self.conv = nn.Conv2d(dim, dim, 3, 1, 1) elif resi_connection == "3conv": # to save parameters and memory self.conv = nn.Sequential( nn.Conv2d(dim, dim // 4, 3, 1, 1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(dim // 4, dim // 4, 1, 1, 0), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(dim // 4, dim, 3, 1, 1), ) self.patch_embed = PatchEmbed( img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim, norm_layer=None, ) self.patch_unembed = PatchUnEmbed( img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim, norm_layer=None, ) def forward(self, x, x_size): return ( self.patch_embed( self.conv(self.patch_unembed(self.residual_group(x, x_size), x_size)) ) + x ) def flops(self): flops = 0 flops += self.residual_group.flops() H, W = self.input_resolution flops += H * W * self.dim * self.dim * 9 flops += self.patch_embed.flops() flops += self.patch_unembed.flops() return flops class PatchEmbed(nn.Module): def __init__( self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None ): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) patches_resolution = [ img_size[0] // patch_size[0], # type: ignore img_size[1] // patch_size[1], # type: ignore ] self.img_size = img_size self.patch_size = patch_size self.patches_resolution = patches_resolution self.num_patches = patches_resolution[0] * patches_resolution[1] self.in_chans = in_chans self.embed_dim = embed_dim if norm_layer is not None: self.norm = norm_layer(embed_dim) else: self.norm = None def forward(self, x): x = x.flatten(2).transpose(1, 2) # B Ph*Pw C if self.norm is not None: x = self.norm(x) return x def flops(self): flops = 0 H, W = self.img_size if self.norm is not None: flops += H * W * self.embed_dim # type: ignore return flops class PatchUnEmbed(nn.Module): def __init__( self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None ): super().__init__() img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) patches_resolution = [ img_size[0] // patch_size[0], # type: ignore img_size[1] // patch_size[1], # type: ignore ] self.img_size = img_size self.patch_size = patch_size self.patches_resolution = patches_resolution self.num_patches = patches_resolution[0] * patches_resolution[1] self.in_chans = in_chans self.embed_dim = embed_dim def forward(self, x, x_size): B, HW, C = x.shape x = x.transpose(1, 2).view(B, self.embed_dim, x_size[0], x_size[1]) # B Ph*Pw C return x def flops(self): flops = 0 return flops class Upsample(nn.Sequential): def __init__(self, scale, num_feat): m = [] if (scale & (scale - 1)) == 0: # scale = 2^n for _ in range(int(math.log(scale, 2))): m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1)) m.append(nn.PixelShuffle(2)) elif scale == 3: m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1)) m.append(nn.PixelShuffle(3)) else: raise ValueError( f"scale {scale} is not supported. " "Supported scales: 2^n and 3." ) super(Upsample, self).__init__(*m) class UpsampleOneStep(nn.Sequential): def __init__(self, scale, num_feat, num_out_ch, input_resolution=None): self.num_feat = num_feat self.input_resolution = input_resolution m = [] m.append(nn.Conv2d(num_feat, (scale**2) * num_out_ch, 3, 1, 1)) m.append(nn.PixelShuffle(scale)) super(UpsampleOneStep, self).__init__(*m) def flops(self): H, W = self.input_resolution # type: ignore flops = H * W * self.num_feat * 3 * 9 return flops class SwinIR(nn.Module): def __init__( self, state_dict, **kwargs, ): super(SwinIR, self).__init__() # Defaults img_size = 64 patch_size = 1 in_chans = 3 embed_dim = 96 depths = [6, 6, 6, 6] num_heads = [6, 6, 6, 6] window_size = 7 mlp_ratio = 4.0 qkv_bias = True qk_scale = None drop_rate = 0.0 attn_drop_rate = 0.0 drop_path_rate = 0.1 norm_layer = nn.LayerNorm ape = False patch_norm = True use_checkpoint = False upscale = 2 img_range = 1.0 upsampler = "" resi_connection = "1conv" num_feat = 64 num_in_ch = in_chans num_out_ch = in_chans supports_fp16 = True self.start_unshuffle = 1 self.model_arch = "SwinIR" self.sub_type = "SR" self.state = state_dict if "params_ema" in self.state: self.state = self.state["params_ema"] elif "params" in self.state: self.state = self.state["params"] state_keys = self.state.keys() if "conv_before_upsample.0.weight" in state_keys: if "conv_up1.weight" in state_keys: upsampler = "nearest+conv" else: upsampler = "pixelshuffle" supports_fp16 = False elif "upsample.0.weight" in state_keys: upsampler = "pixelshuffledirect" else: upsampler = "" num_feat = ( self.state.get("conv_before_upsample.0.weight", None).shape[1] if self.state.get("conv_before_upsample.weight", None) else 64 ) if "conv_first.1.weight" in self.state: self.state["conv_first.weight"] = self.state.pop("conv_first.1.weight") self.state["conv_first.bias"] = self.state.pop("conv_first.1.bias") self.start_unshuffle = round(math.sqrt(self.state["conv_first.weight"].shape[1] // 3)) num_in_ch = self.state["conv_first.weight"].shape[1] in_chans = num_in_ch if "conv_last.weight" in state_keys: num_out_ch = self.state["conv_last.weight"].shape[0] else: num_out_ch = num_in_ch upscale = 1 if upsampler == "nearest+conv": upsample_keys = [ x for x in state_keys if "conv_up" in x and "bias" not in x ] for upsample_key in upsample_keys: upscale *= 2 elif upsampler == "pixelshuffle": upsample_keys = [ x for x in state_keys if "upsample" in x and "conv" not in x and "bias" not in x ] for upsample_key in upsample_keys: shape = self.state[upsample_key].shape[0] upscale *= math.sqrt(shape // num_feat) upscale = int(upscale) elif upsampler == "pixelshuffledirect": upscale = int( math.sqrt(self.state["upsample.0.bias"].shape[0] // num_out_ch) ) max_layer_num = 0 max_block_num = 0 for key in state_keys: result = re.match( r"layers.(\d*).residual_group.blocks.(\d*).norm1.weight", key ) if result: layer_num, block_num = result.groups() max_layer_num = max(max_layer_num, int(layer_num)) max_block_num = max(max_block_num, int(block_num)) depths = [max_block_num + 1 for _ in range(max_layer_num + 1)] if ( "layers.0.residual_group.blocks.0.attn.relative_position_bias_table" in state_keys ): num_heads_num = self.state[ "layers.0.residual_group.blocks.0.attn.relative_position_bias_table" ].shape[-1] num_heads = [num_heads_num for _ in range(max_layer_num + 1)] else: num_heads = depths embed_dim = self.state["conv_first.weight"].shape[0] mlp_ratio = float( self.state["layers.0.residual_group.blocks.0.mlp.fc1.bias"].shape[0] / embed_dim ) # TODO: could actually count the layers, but this should do if "layers.0.conv.4.weight" in state_keys: resi_connection = "3conv" else: resi_connection = "1conv" window_size = int( math.sqrt( self.state[ "layers.0.residual_group.blocks.0.attn.relative_position_index" ].shape[0] ) ) if "layers.0.residual_group.blocks.1.attn_mask" in state_keys: img_size = int( math.sqrt( self.state["layers.0.residual_group.blocks.1.attn_mask"].shape[0] ) * window_size ) # The JPEG models are the only ones with window-size 7, and they also use this range img_range = 255.0 if window_size == 7 else 1.0 self.in_nc = num_in_ch self.out_nc = num_out_ch self.num_feat = num_feat self.embed_dim = embed_dim self.num_heads = num_heads self.depths = depths self.window_size = window_size self.mlp_ratio = mlp_ratio self.scale = upscale / self.start_unshuffle self.upsampler = upsampler self.img_size = img_size self.img_range = img_range self.resi_connection = resi_connection self.supports_fp16 = False # Too much weirdness to support this at the moment self.supports_bfp16 = True self.min_size_restriction = 16 self.img_range = img_range if in_chans == 3: rgb_mean = (0.4488, 0.4371, 0.4040) self.mean = torch.Tensor(rgb_mean).view(1, 3, 1, 1) else: self.mean = torch.zeros(1, 1, 1, 1) self.upscale = upscale self.upsampler = upsampler self.window_size = window_size ##################################################################################################### ################################### 1, shallow feature extraction ################################### self.conv_first = nn.Conv2d(num_in_ch, embed_dim, 3, 1, 1) ##################################################################################################### ################################### 2, deep feature extraction ###################################### self.num_layers = len(depths) self.embed_dim = embed_dim self.ape = ape self.patch_norm = patch_norm self.num_features = embed_dim self.mlp_ratio = mlp_ratio # split image into non-overlapping patches self.patch_embed = PatchEmbed( img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim, norm_layer=norm_layer if self.patch_norm else None, ) num_patches = self.patch_embed.num_patches patches_resolution = self.patch_embed.patches_resolution self.patches_resolution = patches_resolution # merge non-overlapping patches into image self.patch_unembed = PatchUnEmbed( img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim, norm_layer=norm_layer if self.patch_norm else None, ) # absolute position embedding if self.ape: self.absolute_pos_embed = nn.Parameter( # type: ignore torch.zeros(1, num_patches, embed_dim) ) trunc_normal_(self.absolute_pos_embed, std=0.02) self.pos_drop = nn.Dropout(p=drop_rate) # stochastic depth dpr = [ x.item() for x in torch.linspace(0, drop_path_rate, sum(depths)) ] # stochastic depth decay rule # build Residual Swin Transformer blocks (RSTB) self.layers = nn.ModuleList() for i_layer in range(self.num_layers): layer = RSTB( dim=embed_dim, input_resolution=(patches_resolution[0], patches_resolution[1]), depth=depths[i_layer], num_heads=num_heads[i_layer], window_size=window_size, mlp_ratio=self.mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[ sum(depths[:i_layer]) : sum(depths[: i_layer + 1]) # type: ignore ], # no impact on SR results norm_layer=norm_layer, downsample=None, use_checkpoint=use_checkpoint, img_size=img_size, patch_size=patch_size, resi_connection=resi_connection, ) self.layers.append(layer) self.norm = norm_layer(self.num_features) # build the last conv layer in deep feature extraction if resi_connection == "1conv": self.conv_after_body = nn.Conv2d(embed_dim, embed_dim, 3, 1, 1) elif resi_connection == "3conv": # to save parameters and memory self.conv_after_body = nn.Sequential( nn.Conv2d(embed_dim, embed_dim // 4, 3, 1, 1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(embed_dim // 4, embed_dim // 4, 1, 1, 0), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(embed_dim // 4, embed_dim, 3, 1, 1), ) ##################################################################################################### ################################ 3, high quality image reconstruction ################################ if self.upsampler == "pixelshuffle": # for classical SR self.conv_before_upsample = nn.Sequential( nn.Conv2d(embed_dim, num_feat, 3, 1, 1), nn.LeakyReLU(inplace=True) ) self.upsample = Upsample(upscale, num_feat) self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1) elif self.upsampler == "pixelshuffledirect": # for lightweight SR (to save parameters) self.upsample = UpsampleOneStep( upscale, embed_dim, num_out_ch, (patches_resolution[0], patches_resolution[1]), ) elif self.upsampler == "nearest+conv": # for real-world SR (less artifacts) self.conv_before_upsample = nn.Sequential( nn.Conv2d(embed_dim, num_feat, 3, 1, 1), nn.LeakyReLU(inplace=True) ) self.conv_up1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) if self.upscale == 4: self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) elif self.upscale == 8: self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) self.conv_up3 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) self.conv_hr = nn.Conv2d(num_feat, num_feat, 3, 1, 1) self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1) self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True) else: # for image denoising and JPEG compression artifact reduction self.conv_last = nn.Conv2d(embed_dim, num_out_ch, 3, 1, 1) self.apply(self._init_weights) self.load_state_dict(self.state, strict=False) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=0.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.LayerNorm): nn.init.constant_(m.bias, 0) nn.init.constant_(m.weight, 1.0) @torch.jit.ignore # type: ignore def no_weight_decay(self): return {"absolute_pos_embed"} @torch.jit.ignore # type: ignore def no_weight_decay_keywords(self): return {"relative_position_bias_table"} def check_image_size(self, x): _, _, h, w = x.size() mod_pad_h = (self.window_size - h % self.window_size) % self.window_size mod_pad_w = (self.window_size - w % self.window_size) % self.window_size x = F.pad(x, (0, mod_pad_w, 0, mod_pad_h), "reflect") return x def forward_features(self, x): x_size = (x.shape[2], x.shape[3]) x = self.patch_embed(x) if self.ape: x = x + self.absolute_pos_embed x = self.pos_drop(x) for layer in self.layers: x = layer(x, x_size) x = self.norm(x) # B L C x = self.patch_unembed(x, x_size) return x def forward(self, x): H, W = x.shape[2:] x = self.check_image_size(x) self.mean = self.mean.type_as(x) x = (x - self.mean) * self.img_range if self.start_unshuffle > 1: x = torch.nn.functional.pixel_unshuffle(x, self.start_unshuffle) if self.upsampler == "pixelshuffle": # for classical SR x = self.conv_first(x) x = self.conv_after_body(self.forward_features(x)) + x x = self.conv_before_upsample(x) x = self.conv_last(self.upsample(x)) elif self.upsampler == "pixelshuffledirect": # for lightweight SR x = self.conv_first(x) x = self.conv_after_body(self.forward_features(x)) + x x = self.upsample(x) elif self.upsampler == "nearest+conv": # for real-world SR x = self.conv_first(x) x = self.conv_after_body(self.forward_features(x)) + x x = self.conv_before_upsample(x) x = self.lrelu( self.conv_up1( torch.nn.functional.interpolate(x, scale_factor=2, mode="nearest") # type: ignore ) ) if self.upscale == 4: x = self.lrelu( self.conv_up2( torch.nn.functional.interpolate( # type: ignore x, scale_factor=2, mode="nearest" ) ) ) elif self.upscale == 8: x = self.lrelu(self.conv_up2(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest'))) x = self.lrelu(self.conv_up3(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest'))) x = self.conv_last(self.lrelu(self.conv_hr(x))) else: # for image denoising and JPEG compression artifact reduction x_first = self.conv_first(x) res = self.conv_after_body(self.forward_features(x_first)) + x_first x = x + self.conv_last(res) x = x / self.img_range + self.mean return x[:, :, : H * self.upscale, : W * self.upscale] def flops(self): flops = 0 H, W = self.patches_resolution flops += H * W * 3 * self.embed_dim * 9 flops += self.patch_embed.flops() for i, layer in enumerate(self.layers): flops += layer.flops() # type: ignore flops += H * W * 3 * self.embed_dim * self.embed_dim flops += self.upsample.flops() # type: ignore return flops
--- +++ @@ -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 // window_size, window_size, C) windows = ( @@ -54,6 +62,16 @@ def window_reverse(windows, window_size, H, W): + """ + Args: + windows: (num_windows*B, window_size, window_size, C) + window_size (int): Window size + H (int): Height of image + W (int): Width of image + + Returns: + x: (B, H, W, C) + """ B = int(windows.shape[0] / (H * W / window_size / window_size)) x = windows.view( B, H // window_size, W // window_size, window_size, window_size, -1 @@ -63,6 +81,18 @@ class WindowAttention(nn.Module): + r"""Window based multi-head self attention (W-MSA) module with relative position bias. + It supports both of shifted and non-shifted window. + + Args: + dim (int): Number of input channels. + window_size (tuple[int]): The height and width of the window. + num_heads (int): Number of attention heads. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set + attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 + proj_drop (float, optional): Dropout ratio of output. Default: 0.0 + """ def __init__( self, @@ -113,6 +143,11 @@ self.softmax = nn.Softmax(dim=-1) def forward(self, x, mask=None): + """ + Args: + x: input features with shape of (num_windows*B, N, C) + mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None + """ B_, N, C = x.shape qkv = ( self.qkv(x) @@ -175,6 +210,23 @@ class SwinTransformerBlock(nn.Module): + r"""Swin Transformer Block. + + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resulotion. + num_heads (int): Number of attention heads. + window_size (int): Window size. + shift_size (int): Shift size for SW-MSA. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float, optional): Stochastic depth rate. Default: 0.0 + act_layer (nn.Module, optional): Activation layer. Default: nn.GELU + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + """ def __init__( self, @@ -342,6 +394,13 @@ class PatchMerging(nn.Module): + r"""Patch Merging Layer. + + Args: + input_resolution (tuple[int]): Resolution of input feature. + dim (int): Number of input channels. + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + """ def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm): super().__init__() @@ -351,6 +410,9 @@ self.norm = norm_layer(4 * dim) def forward(self, x): + """ + x: B, H*W, C + """ H, W = self.input_resolution B, L, C = x.shape assert L == H * W, "input feature has wrong size" @@ -381,6 +443,24 @@ class BasicLayer(nn.Module): + """A basic Swin Transformer layer for one stage. + + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resolution. + depth (int): Number of blocks. + num_heads (int): Number of attention heads. + window_size (int): Local window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. + """ def __init__( self, @@ -459,6 +539,27 @@ class RSTB(nn.Module): + """Residual Swin Transformer Block (RSTB). + + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resolution. + depth (int): Number of blocks. + num_heads (int): Number of attention heads. + window_size (int): Local window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. + img_size: Input image size. + patch_size: Patch size. + resi_connection: The convolutional block before residual connection. + """ def __init__( self, @@ -550,6 +651,15 @@ class PatchEmbed(nn.Module): + r"""Image to Patch Embedding + + Args: + img_size (int): Image size. Default: 224. + patch_size (int): Patch token size. Default: 4. + in_chans (int): Number of input image channels. Default: 3. + embed_dim (int): Number of linear projection output channels. Default: 96. + norm_layer (nn.Module, optional): Normalization layer. Default: None + """ def __init__( self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None @@ -589,6 +699,15 @@ class PatchUnEmbed(nn.Module): + r"""Image to Patch Unembedding + + Args: + img_size (int): Image size. Default: 224. + patch_size (int): Patch token size. Default: 4. + in_chans (int): Number of input image channels. Default: 3. + embed_dim (int): Number of linear projection output channels. Default: 96. + norm_layer (nn.Module, optional): Normalization layer. Default: None + """ def __init__( self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None @@ -619,6 +738,12 @@ class Upsample(nn.Sequential): + """Upsample module. + + Args: + scale (int): Scale factor. Supported scales: 2^n and 3. + num_feat (int): Channel number of intermediate features. + """ def __init__(self, scale, num_feat): m = [] @@ -637,6 +762,14 @@ class UpsampleOneStep(nn.Sequential): + """UpsampleOneStep module (the difference with Upsample is that it always only has 1conv + 1pixelshuffle) + Used in lightweight SR to save parameters. + + Args: + scale (int): Scale factor. Supported scales: 2^n and 3. + num_feat (int): Channel number of intermediate features. + + """ def __init__(self, scale, num_feat, num_out_ch, input_resolution=None): self.num_feat = num_feat @@ -653,6 +786,32 @@ class SwinIR(nn.Module): + r"""SwinIR + A PyTorch impl of : `SwinIR: Image Restoration Using Swin Transformer`, based on Swin Transformer. + + Args: + img_size (int | tuple(int)): Input image size. Default 64 + patch_size (int | tuple(int)): Patch size. Default: 1 + in_chans (int): Number of input image channels. Default: 3 + embed_dim (int): Patch embedding dimension. Default: 96 + depths (tuple(int)): Depth of each Swin Transformer layer. + num_heads (tuple(int)): Number of attention heads in different layers. + window_size (int): Window size. Default: 7 + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4 + qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. Default: None + drop_rate (float): Dropout rate. Default: 0 + attn_drop_rate (float): Attention dropout rate. Default: 0 + drop_path_rate (float): Stochastic depth rate. Default: 0.1 + norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. + ape (bool): If True, add absolute position embedding to the patch embedding. Default: False + patch_norm (bool): If True, add normalization after patch embedding. Default: True + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False + upscale: Upscale factor. 2/3/4/8 for image SR, 1 for denoising and compress artifact reduction + img_range: Image range. 1. or 255. + upsampler: The reconstruction reconstruction module. 'pixelshuffle'/'pixelshuffledirect'/'nearest+conv'/None + resi_connection: The convolutional block before residual connection. '1conv'/'3conv' + """ def __init__( self, @@ -1062,4 +1221,4 @@ flops += layer.flops() # type: ignore flops += H * W * 3 * self.embed_dim * self.embed_dim flops += self.upsample.flops() # type: ignore - return flops+ return flops
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 StyleGAN2GeneratorSFT(StyleGAN2Generator): def __init__( self, out_size, num_style_feat=512, num_mlp=8, channel_multiplier=2, resample_kernel=(1, 3, 3, 1), lr_mlp=0.01, narrow=1, sft_half=False, ): super(StyleGAN2GeneratorSFT, self).__init__( out_size, num_style_feat=num_style_feat, num_mlp=num_mlp, channel_multiplier=channel_multiplier, resample_kernel=resample_kernel, lr_mlp=lr_mlp, narrow=narrow, ) self.sft_half = sft_half def forward( self, styles, conditions, input_is_latent=False, noise=None, randomize_noise=True, truncation=1, truncation_latent=None, inject_index=None, return_latents=False, ): # style codes -> latents with Style MLP layer if not input_is_latent: styles = [self.style_mlp(s) for s in styles] # noises if noise is None: if randomize_noise: noise = [None] * self.num_layers # for each style conv layer else: # use the stored noise noise = [ getattr(self.noises, f"noise{i}") for i in range(self.num_layers) ] # style truncation if truncation < 1: style_truncation = [] for style in styles: style_truncation.append( truncation_latent + truncation * (style - truncation_latent) ) styles = style_truncation # get style latents with injection if len(styles) == 1: inject_index = self.num_latent if styles[0].ndim < 3: # repeat latent code for all the layers latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1) else: # used for encoder with different latent code for each layer latent = styles[0] elif len(styles) == 2: # mixing noises if inject_index is None: inject_index = random.randint(1, self.num_latent - 1) latent1 = styles[0].unsqueeze(1).repeat(1, inject_index, 1) latent2 = ( styles[1].unsqueeze(1).repeat(1, self.num_latent - inject_index, 1) ) latent = torch.cat([latent1, latent2], 1) # main generation out = self.constant_input(latent.shape[0]) out = self.style_conv1(out, latent[:, 0], noise=noise[0]) skip = self.to_rgb1(out, latent[:, 1]) i = 1 for conv1, conv2, noise1, noise2, to_rgb in zip( self.style_convs[::2], self.style_convs[1::2], noise[1::2], noise[2::2], self.to_rgbs, ): out = conv1(out, latent[:, i], noise=noise1) # the conditions may have fewer levels if i < len(conditions): # SFT part to combine the conditions if self.sft_half: # only apply SFT to half of the channels out_same, out_sft = torch.split(out, int(out.size(1) // 2), dim=1) out_sft = out_sft * conditions[i - 1] + conditions[i] out = torch.cat([out_same, out_sft], dim=1) else: # apply SFT to all the channels out = out * conditions[i - 1] + conditions[i] out = conv2(out, latent[:, i + 1], noise=noise2) skip = to_rgb(out, latent[:, i + 2], skip) # feature back to the rgb space i += 2 image = skip if return_latents: return image, latent else: return image, None class ConvUpLayer(nn.Module): def __init__( self, in_channels, out_channels, kernel_size, stride=1, padding=0, bias=True, bias_init_val=0, activate=True, ): super(ConvUpLayer, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.stride = stride self.padding = padding # self.scale is used to scale the convolution weights, which is related to the common initializations. self.scale = 1 / math.sqrt(in_channels * kernel_size**2) self.weight = nn.Parameter( torch.randn(out_channels, in_channels, kernel_size, kernel_size) ) if bias and not activate: self.bias = nn.Parameter(torch.zeros(out_channels).fill_(bias_init_val)) else: self.register_parameter("bias", None) # activation if activate: if bias: self.activation = FusedLeakyReLU(out_channels) else: self.activation = ScaledLeakyReLU(0.2) else: self.activation = None def forward(self, x): # bilinear upsample out = F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=False) # conv out = F.conv2d( out, self.weight * self.scale, bias=self.bias, stride=self.stride, padding=self.padding, ) # activation if self.activation is not None: out = self.activation(out) return out class ResUpBlock(nn.Module): def __init__(self, in_channels, out_channels): super(ResUpBlock, self).__init__() self.conv1 = ConvLayer(in_channels, in_channels, 3, bias=True, activate=True) self.conv2 = ConvUpLayer( in_channels, out_channels, 3, stride=1, padding=1, bias=True, activate=True ) self.skip = ConvUpLayer( in_channels, out_channels, 1, bias=False, activate=False ) def forward(self, x): out = self.conv1(x) out = self.conv2(out) skip = self.skip(x) out = (out + skip) / math.sqrt(2) return out class GFPGANv1(nn.Module): def __init__( self, out_size, num_style_feat=512, channel_multiplier=1, resample_kernel=(1, 3, 3, 1), decoder_load_path=None, fix_decoder=True, # for stylegan decoder num_mlp=8, lr_mlp=0.01, input_is_latent=False, different_w=False, narrow=1, sft_half=False, ): super(GFPGANv1, self).__init__() self.input_is_latent = input_is_latent self.different_w = different_w self.num_style_feat = num_style_feat unet_narrow = narrow * 0.5 # by default, use a half of input channels channels = { "4": int(512 * unet_narrow), "8": int(512 * unet_narrow), "16": int(512 * unet_narrow), "32": int(512 * unet_narrow), "64": int(256 * channel_multiplier * unet_narrow), "128": int(128 * channel_multiplier * unet_narrow), "256": int(64 * channel_multiplier * unet_narrow), "512": int(32 * channel_multiplier * unet_narrow), "1024": int(16 * channel_multiplier * unet_narrow), } self.log_size = int(math.log(out_size, 2)) first_out_size = 2 ** (int(math.log(out_size, 2))) self.conv_body_first = ConvLayer( 3, channels[f"{first_out_size}"], 1, bias=True, activate=True ) # downsample in_channels = channels[f"{first_out_size}"] self.conv_body_down = nn.ModuleList() for i in range(self.log_size, 2, -1): out_channels = channels[f"{2**(i - 1)}"] self.conv_body_down.append( ResBlock(in_channels, out_channels, resample_kernel) ) in_channels = out_channels self.final_conv = ConvLayer( in_channels, channels["4"], 3, bias=True, activate=True ) # upsample in_channels = channels["4"] self.conv_body_up = nn.ModuleList() for i in range(3, self.log_size + 1): out_channels = channels[f"{2**i}"] self.conv_body_up.append(ResUpBlock(in_channels, out_channels)) in_channels = out_channels # to RGB self.toRGB = nn.ModuleList() for i in range(3, self.log_size + 1): self.toRGB.append( EqualConv2d( channels[f"{2**i}"], 3, 1, stride=1, padding=0, bias=True, bias_init_val=0, ) ) if different_w: linear_out_channel = (int(math.log(out_size, 2)) * 2 - 2) * num_style_feat else: linear_out_channel = num_style_feat self.final_linear = EqualLinear( channels["4"] * 4 * 4, linear_out_channel, bias=True, bias_init_val=0, lr_mul=1, activation=None, ) # the decoder: stylegan2 generator with SFT modulations self.stylegan_decoder = StyleGAN2GeneratorSFT( out_size=out_size, num_style_feat=num_style_feat, num_mlp=num_mlp, channel_multiplier=channel_multiplier, resample_kernel=resample_kernel, lr_mlp=lr_mlp, narrow=narrow, sft_half=sft_half, ) # load pre-trained stylegan2 model if necessary if decoder_load_path: self.stylegan_decoder.load_state_dict( torch.load( decoder_load_path, map_location=lambda storage, loc: storage, weights_only=True)["params_ema"] ) # fix decoder without updating params if fix_decoder: for _, param in self.stylegan_decoder.named_parameters(): param.requires_grad = False # for SFT modulations (scale and shift) self.condition_scale = nn.ModuleList() self.condition_shift = nn.ModuleList() for i in range(3, self.log_size + 1): out_channels = channels[f"{2**i}"] if sft_half: sft_out_channels = out_channels else: sft_out_channels = out_channels * 2 self.condition_scale.append( nn.Sequential( EqualConv2d( out_channels, out_channels, 3, stride=1, padding=1, bias=True, bias_init_val=0, ), ScaledLeakyReLU(0.2), EqualConv2d( out_channels, sft_out_channels, 3, stride=1, padding=1, bias=True, bias_init_val=1, ), ) ) self.condition_shift.append( nn.Sequential( EqualConv2d( out_channels, out_channels, 3, stride=1, padding=1, bias=True, bias_init_val=0, ), ScaledLeakyReLU(0.2), EqualConv2d( out_channels, sft_out_channels, 3, stride=1, padding=1, bias=True, bias_init_val=0, ), ) ) def forward( self, x, return_latents=False, return_rgb=True, randomize_noise=True, **kwargs ): conditions = [] unet_skips = [] out_rgbs = [] # encoder feat = self.conv_body_first(x) for i in range(self.log_size - 2): feat = self.conv_body_down[i](feat) unet_skips.insert(0, feat) feat = self.final_conv(feat) # style code style_code = self.final_linear(feat.view(feat.size(0), -1)) if self.different_w: style_code = style_code.view(style_code.size(0), -1, self.num_style_feat) # decode for i in range(self.log_size - 2): # add unet skip feat = feat + unet_skips[i] # ResUpLayer feat = self.conv_body_up[i](feat) # generate scale and shift for SFT layers scale = self.condition_scale[i](feat) conditions.append(scale.clone()) shift = self.condition_shift[i](feat) conditions.append(shift.clone()) # generate rgb images if return_rgb: out_rgbs.append(self.toRGB[i](feat)) # decoder image, _ = self.stylegan_decoder( [style_code], conditions, return_latents=return_latents, input_is_latent=self.input_is_latent, randomize_noise=randomize_noise, ) return image, out_rgbs class FacialComponentDiscriminator(nn.Module): def __init__(self): super(FacialComponentDiscriminator, self).__init__() # It now uses a VGG-style architectrue with fixed model size self.conv1 = ConvLayer( 3, 64, 3, downsample=False, resample_kernel=(1, 3, 3, 1), bias=True, activate=True, ) self.conv2 = ConvLayer( 64, 128, 3, downsample=True, resample_kernel=(1, 3, 3, 1), bias=True, activate=True, ) self.conv3 = ConvLayer( 128, 128, 3, downsample=False, resample_kernel=(1, 3, 3, 1), bias=True, activate=True, ) self.conv4 = ConvLayer( 128, 256, 3, downsample=True, resample_kernel=(1, 3, 3, 1), bias=True, activate=True, ) self.conv5 = ConvLayer( 256, 256, 3, downsample=False, resample_kernel=(1, 3, 3, 1), bias=True, activate=True, ) self.final_conv = ConvLayer(256, 1, 3, bias=True, activate=False) def forward(self, x, return_feats=False, **kwargs): feat = self.conv1(x) feat = self.conv3(self.conv2(feat)) rlt_feats = [] if return_feats: rlt_feats.append(feat.clone()) feat = self.conv5(self.conv4(feat)) if return_feats: rlt_feats.append(feat.clone()) out = self.final_conv(feat) if return_feats: return out, rlt_feats else: return out, None
--- +++ @@ -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 (int): Layer number of MLP style layers. Default: 8. + channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2. + resample_kernel (list[int]): A list indicating the 1D resample kernel magnitude. A cross production will be + applied to extent 1D resample kernel to 2D resample kernel. Default: (1, 3, 3, 1). + lr_mlp (float): Learning rate multiplier for mlp layers. Default: 0.01. + narrow (float): The narrow ratio for channels. Default: 1. + sft_half (bool): Whether to apply SFT on half of the input channels. Default: False. + """ def __init__( self, @@ -54,6 +66,18 @@ inject_index=None, return_latents=False, ): + """Forward function for StyleGAN2GeneratorSFT. + Args: + styles (list[Tensor]): Sample codes of styles. + conditions (list[Tensor]): SFT conditions to generators. + input_is_latent (bool): Whether input is latent style. Default: False. + noise (Tensor | None): Input noise or None. Default: None. + randomize_noise (bool): Randomize noise, used when 'noise' is False. Default: True. + truncation (float): The truncation ratio. Default: 1. + truncation_latent (Tensor | None): The truncation latent tensor. Default: None. + inject_index (int | None): The injection index for mixing noise. Default: None. + return_latents (bool): Whether to return style latents. Default: False. + """ # style codes -> latents with Style MLP layer if not input_is_latent: styles = [self.style_mlp(s) for s in styles] @@ -129,6 +153,17 @@ class ConvUpLayer(nn.Module): + """Convolutional upsampling layer. It uses bilinear upsampler + Conv. + Args: + in_channels (int): Channel number of the input. + out_channels (int): Channel number of the output. + kernel_size (int): Size of the convolving kernel. + stride (int): Stride of the convolution. Default: 1 + padding (int): Zero-padding added to both sides of the input. Default: 0. + bias (bool): If ``True``, adds a learnable bias to the output. Default: ``True``. + bias_init_val (float): Bias initialized value. Default: 0. + activate (bool): Whether use activateion. Default: True. + """ def __init__( self, @@ -186,6 +221,11 @@ class ResUpBlock(nn.Module): + """Residual block with upsampling. + Args: + in_channels (int): Channel number of the input. + out_channels (int): Channel number of the output. + """ def __init__(self, in_channels, out_channels): super(ResUpBlock, self).__init__() @@ -207,6 +247,23 @@ class GFPGANv1(nn.Module): + """The GFPGAN architecture: Unet + StyleGAN2 decoder with SFT. + Ref: GFP-GAN: Towards Real-World Blind Face Restoration with Generative Facial Prior. + Args: + out_size (int): The spatial size of outputs. + num_style_feat (int): Channel number of style features. Default: 512. + channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2. + resample_kernel (list[int]): A list indicating the 1D resample kernel magnitude. A cross production will be + applied to extent 1D resample kernel to 2D resample kernel. Default: (1, 3, 3, 1). + decoder_load_path (str): The path to the pre-trained decoder model (usually, the StyleGAN2). Default: None. + fix_decoder (bool): Whether to fix the decoder. Default: True. + num_mlp (int): Layer number of MLP style layers. Default: 8. + lr_mlp (float): Learning rate multiplier for mlp layers. Default: 0.01. + input_is_latent (bool): Whether input is latent style. Default: False. + different_w (bool): Whether to use different latent w for different layers. Default: False. + narrow (float): The narrow ratio for channels. Default: 1. + sft_half (bool): Whether to apply SFT on half of the input channels. Default: False. + """ def __init__( self, @@ -383,6 +440,13 @@ def forward( self, x, return_latents=False, return_rgb=True, randomize_noise=True, **kwargs ): + """Forward function for GFPGANv1. + Args: + x (Tensor): Input images. + return_latents (bool): Whether to return style latents. Default: False. + return_rgb (bool): Whether return intermediate rgb images. Default: True. + randomize_noise (bool): Randomize noise, used when 'noise' is False. Default: True. + """ conditions = [] unet_skips = [] out_rgbs = [] @@ -428,6 +492,7 @@ class FacialComponentDiscriminator(nn.Module): + """Facial component (eyes, mouth, noise) discriminator used in GFPGAN.""" def __init__(self): super(FacialComponentDiscriminator, self).__init__() @@ -480,6 +545,11 @@ self.final_conv = ConvLayer(256, 1, 3, bias=True, activate=False) def forward(self, x, return_feats=False, **kwargs): + """Forward function for FacialComponentDiscriminator. + Args: + x (Tensor): Input images. + return_feats (bool): Whether to return intermediate features. Default: False. + """ feat = self.conv1(x) feat = self.conv3(self.conv2(feat)) rlt_feats = [] @@ -493,4 +563,4 @@ if return_feats: return out, rlt_feats else: - return out, None+ return out, None
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_feat=512, num_mlp=8, channel_multiplier=2, narrow=1, sft_half=False, ): super(StyleGAN2GeneratorCSFT, self).__init__( out_size, num_style_feat=num_style_feat, num_mlp=num_mlp, channel_multiplier=channel_multiplier, narrow=narrow, ) self.sft_half = sft_half def forward( self, styles, conditions, input_is_latent=False, noise=None, randomize_noise=True, truncation=1, truncation_latent=None, inject_index=None, return_latents=False, ): # style codes -> latents with Style MLP layer if not input_is_latent: styles = [self.style_mlp(s) for s in styles] # noises if noise is None: if randomize_noise: noise = [None] * self.num_layers # for each style conv layer else: # use the stored noise noise = [ getattr(self.noises, f"noise{i}") for i in range(self.num_layers) ] # style truncation if truncation < 1: style_truncation = [] for style in styles: style_truncation.append( truncation_latent + truncation * (style - truncation_latent) ) styles = style_truncation # get style latents with injection if len(styles) == 1: inject_index = self.num_latent if styles[0].ndim < 3: # repeat latent code for all the layers latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1) else: # used for encoder with different latent code for each layer latent = styles[0] elif len(styles) == 2: # mixing noises if inject_index is None: inject_index = random.randint(1, self.num_latent - 1) latent1 = styles[0].unsqueeze(1).repeat(1, inject_index, 1) latent2 = ( styles[1].unsqueeze(1).repeat(1, self.num_latent - inject_index, 1) ) latent = torch.cat([latent1, latent2], 1) # main generation out = self.constant_input(latent.shape[0]) out = self.style_conv1(out, latent[:, 0], noise=noise[0]) skip = self.to_rgb1(out, latent[:, 1]) i = 1 for conv1, conv2, noise1, noise2, to_rgb in zip( self.style_convs[::2], self.style_convs[1::2], noise[1::2], noise[2::2], self.to_rgbs, ): out = conv1(out, latent[:, i], noise=noise1) # the conditions may have fewer levels if i < len(conditions): # SFT part to combine the conditions if self.sft_half: # only apply SFT to half of the channels out_same, out_sft = torch.split(out, int(out.size(1) // 2), dim=1) out_sft = out_sft * conditions[i - 1] + conditions[i] out = torch.cat([out_same, out_sft], dim=1) else: # apply SFT to all the channels out = out * conditions[i - 1] + conditions[i] out = conv2(out, latent[:, i + 1], noise=noise2) skip = to_rgb(out, latent[:, i + 2], skip) # feature back to the rgb space i += 2 image = skip if return_latents: return image, latent else: return image, None class ResBlock(nn.Module): def __init__(self, in_channels, out_channels, mode="down"): super(ResBlock, self).__init__() self.conv1 = nn.Conv2d(in_channels, in_channels, 3, 1, 1) self.conv2 = nn.Conv2d(in_channels, out_channels, 3, 1, 1) self.skip = nn.Conv2d(in_channels, out_channels, 1, bias=False) if mode == "down": self.scale_factor = 0.5 elif mode == "up": self.scale_factor = 2 def forward(self, x): out = F.leaky_relu_(self.conv1(x), negative_slope=0.2) # upsample/downsample out = F.interpolate( out, scale_factor=self.scale_factor, mode="bilinear", align_corners=False ) out = F.leaky_relu_(self.conv2(out), negative_slope=0.2) # skip x = F.interpolate( x, scale_factor=self.scale_factor, mode="bilinear", align_corners=False ) skip = self.skip(x) out = out + skip return out class GFPGANv1Clean(nn.Module): def __init__( self, state_dict, ): super(GFPGANv1Clean, self).__init__() out_size = 512 num_style_feat = 512 channel_multiplier = 2 decoder_load_path = None fix_decoder = False num_mlp = 8 input_is_latent = True different_w = True narrow = 1 sft_half = True self.model_arch = "GFPGAN" self.sub_type = "Face SR" self.scale = 8 self.in_nc = 3 self.out_nc = 3 self.state = state_dict self.supports_fp16 = False self.supports_bf16 = True self.min_size_restriction = 512 self.input_is_latent = input_is_latent self.different_w = different_w self.num_style_feat = num_style_feat unet_narrow = narrow * 0.5 # by default, use a half of input channels channels = { "4": int(512 * unet_narrow), "8": int(512 * unet_narrow), "16": int(512 * unet_narrow), "32": int(512 * unet_narrow), "64": int(256 * channel_multiplier * unet_narrow), "128": int(128 * channel_multiplier * unet_narrow), "256": int(64 * channel_multiplier * unet_narrow), "512": int(32 * channel_multiplier * unet_narrow), "1024": int(16 * channel_multiplier * unet_narrow), } self.log_size = int(math.log(out_size, 2)) first_out_size = 2 ** (int(math.log(out_size, 2))) self.conv_body_first = nn.Conv2d(3, channels[f"{first_out_size}"], 1) # downsample in_channels = channels[f"{first_out_size}"] self.conv_body_down = nn.ModuleList() for i in range(self.log_size, 2, -1): out_channels = channels[f"{2**(i - 1)}"] self.conv_body_down.append(ResBlock(in_channels, out_channels, mode="down")) in_channels = out_channels self.final_conv = nn.Conv2d(in_channels, channels["4"], 3, 1, 1) # upsample in_channels = channels["4"] self.conv_body_up = nn.ModuleList() for i in range(3, self.log_size + 1): out_channels = channels[f"{2**i}"] self.conv_body_up.append(ResBlock(in_channels, out_channels, mode="up")) in_channels = out_channels # to RGB self.toRGB = nn.ModuleList() for i in range(3, self.log_size + 1): self.toRGB.append(nn.Conv2d(channels[f"{2**i}"], 3, 1)) if different_w: linear_out_channel = (int(math.log(out_size, 2)) * 2 - 2) * num_style_feat else: linear_out_channel = num_style_feat self.final_linear = nn.Linear(channels["4"] * 4 * 4, linear_out_channel) # the decoder: stylegan2 generator with SFT modulations self.stylegan_decoder = StyleGAN2GeneratorCSFT( out_size=out_size, num_style_feat=num_style_feat, num_mlp=num_mlp, channel_multiplier=channel_multiplier, narrow=narrow, sft_half=sft_half, ) # load pre-trained stylegan2 model if necessary if decoder_load_path: self.stylegan_decoder.load_state_dict( torch.load( decoder_load_path, map_location=lambda storage, loc: storage, weights_only=True)["params_ema"] ) # fix decoder without updating params if fix_decoder: for _, param in self.stylegan_decoder.named_parameters(): param.requires_grad = False # for SFT modulations (scale and shift) self.condition_scale = nn.ModuleList() self.condition_shift = nn.ModuleList() for i in range(3, self.log_size + 1): out_channels = channels[f"{2**i}"] if sft_half: sft_out_channels = out_channels else: sft_out_channels = out_channels * 2 self.condition_scale.append( nn.Sequential( nn.Conv2d(out_channels, out_channels, 3, 1, 1), nn.LeakyReLU(0.2, True), nn.Conv2d(out_channels, sft_out_channels, 3, 1, 1), ) ) self.condition_shift.append( nn.Sequential( nn.Conv2d(out_channels, out_channels, 3, 1, 1), nn.LeakyReLU(0.2, True), nn.Conv2d(out_channels, sft_out_channels, 3, 1, 1), ) ) self.load_state_dict(state_dict) def forward( self, x, return_latents=False, return_rgb=True, randomize_noise=True, **kwargs ): conditions = [] unet_skips = [] out_rgbs = [] # encoder feat = F.leaky_relu_(self.conv_body_first(x), negative_slope=0.2) for i in range(self.log_size - 2): feat = self.conv_body_down[i](feat) unet_skips.insert(0, feat) feat = F.leaky_relu_(self.final_conv(feat), negative_slope=0.2) # style code style_code = self.final_linear(feat.view(feat.size(0), -1)) if self.different_w: style_code = style_code.view(style_code.size(0), -1, self.num_style_feat) # decode for i in range(self.log_size - 2): # add unet skip feat = feat + unet_skips[i] # ResUpLayer feat = self.conv_body_up[i](feat) # generate scale and shift for SFT layers scale = self.condition_scale[i](feat) conditions.append(scale.clone()) shift = self.condition_shift[i](feat) conditions.append(shift.clone()) # generate rgb images if return_rgb: out_rgbs.append(self.toRGB[i](feat)) # decoder image, _ = self.stylegan_decoder( [style_code], conditions, return_latents=return_latents, input_is_latent=self.input_is_latent, randomize_noise=randomize_noise, ) return image, out_rgbs
--- +++ @@ -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. + num_style_feat (int): Channel number of style features. Default: 512. + num_mlp (int): Layer number of MLP style layers. Default: 8. + channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2. + narrow (float): The narrow ratio for channels. Default: 1. + sft_half (bool): Whether to apply SFT on half of the input channels. Default: False. + """ def __init__( self, @@ -42,6 +52,18 @@ inject_index=None, return_latents=False, ): + """Forward function for StyleGAN2GeneratorCSFT. + Args: + styles (list[Tensor]): Sample codes of styles. + conditions (list[Tensor]): SFT conditions to generators. + input_is_latent (bool): Whether input is latent style. Default: False. + noise (Tensor | None): Input noise or None. Default: None. + randomize_noise (bool): Randomize noise, used when 'noise' is False. Default: True. + truncation (float): The truncation ratio. Default: 1. + truncation_latent (Tensor | None): The truncation latent tensor. Default: None. + inject_index (int | None): The injection index for mixing noise. Default: None. + return_latents (bool): Whether to return style latents. Default: False. + """ # style codes -> latents with Style MLP layer if not input_is_latent: styles = [self.style_mlp(s) for s in styles] @@ -117,6 +139,12 @@ class ResBlock(nn.Module): + """Residual block with bilinear upsampling/downsampling. + Args: + in_channels (int): Channel number of the input. + out_channels (int): Channel number of the output. + mode (str): Upsampling/downsampling mode. Options: down | up. Default: down. + """ def __init__(self, in_channels, out_channels, mode="down"): super(ResBlock, self).__init__() @@ -146,6 +174,21 @@ class GFPGANv1Clean(nn.Module): + """The GFPGAN architecture: Unet + StyleGAN2 decoder with SFT. + It is the clean version without custom compiled CUDA extensions used in StyleGAN2. + Ref: GFP-GAN: Towards Real-World Blind Face Restoration with Generative Facial Prior. + Args: + out_size (int): The spatial size of outputs. + num_style_feat (int): Channel number of style features. Default: 512. + channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2. + decoder_load_path (str): The path to the pre-trained decoder model (usually, the StyleGAN2). Default: None. + fix_decoder (bool): Whether to fix the decoder. Default: True. + num_mlp (int): Layer number of MLP style layers. Default: 8. + input_is_latent (bool): Whether input is latent style. Default: False. + different_w (bool): Whether to use different latent w for different layers. Default: False. + narrow (float): The narrow ratio for channels. Default: 1. + sft_half (bool): Whether to apply SFT on half of the input channels. Default: False. + """ def __init__( self, @@ -277,6 +320,13 @@ def forward( self, x, return_latents=False, return_rgb=True, randomize_noise=True, **kwargs ): + """Forward function for GFPGANv1Clean. + Args: + x (Tensor): Input images. + return_latents (bool): Whether to return style latents. Default: False. + return_rgb (bool): Whether return intermediate rgb images. Default: True. + randomize_noise (bool): Randomize noise, used when 'noise' is False. Default: True. + """ conditions = [] unet_skips = [] out_rgbs = [] @@ -317,4 +367,4 @@ randomize_noise=randomize_noise, ) - return image, out_rgbs+ return image, out_rgbs
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.mean(x**2, dim=1, keepdim=True) + 1e-8) def make_resample_kernel(k): k = torch.tensor(k, dtype=torch.float32) if k.ndim == 1: k = k[None, :] * k[:, None] # to 2D kernel, outer product # normalize k /= k.sum() return k class UpFirDnUpsample(nn.Module): def __init__(self, resample_kernel, factor=2): super(UpFirDnUpsample, self).__init__() self.kernel = make_resample_kernel(resample_kernel) * (factor**2) self.factor = factor pad = self.kernel.shape[0] - factor self.pad = ((pad + 1) // 2 + factor - 1, pad // 2) def forward(self, x): out = upfirdn2d(x, self.kernel.type_as(x), up=self.factor, down=1, pad=self.pad) return out def __repr__(self): return f"{self.__class__.__name__}(factor={self.factor})" class UpFirDnDownsample(nn.Module): def __init__(self, resample_kernel, factor=2): super(UpFirDnDownsample, self).__init__() self.kernel = make_resample_kernel(resample_kernel) self.factor = factor pad = self.kernel.shape[0] - factor self.pad = ((pad + 1) // 2, pad // 2) def forward(self, x): out = upfirdn2d(x, self.kernel.type_as(x), up=1, down=self.factor, pad=self.pad) return out def __repr__(self): return f"{self.__class__.__name__}(factor={self.factor})" class UpFirDnSmooth(nn.Module): def __init__( self, resample_kernel, upsample_factor=1, downsample_factor=1, kernel_size=1 ): super(UpFirDnSmooth, self).__init__() self.upsample_factor = upsample_factor self.downsample_factor = downsample_factor self.kernel = make_resample_kernel(resample_kernel) if upsample_factor > 1: self.kernel = self.kernel * (upsample_factor**2) if upsample_factor > 1: pad = (self.kernel.shape[0] - upsample_factor) - (kernel_size - 1) self.pad = ((pad + 1) // 2 + upsample_factor - 1, pad // 2 + 1) elif downsample_factor > 1: pad = (self.kernel.shape[0] - downsample_factor) + (kernel_size - 1) self.pad = ((pad + 1) // 2, pad // 2) else: raise NotImplementedError def forward(self, x): out = upfirdn2d(x, self.kernel.type_as(x), up=1, down=1, pad=self.pad) return out def __repr__(self): return ( f"{self.__class__.__name__}(upsample_factor={self.upsample_factor}" f", downsample_factor={self.downsample_factor})" ) class EqualLinear(nn.Module): def __init__( self, in_channels, out_channels, bias=True, bias_init_val=0, lr_mul=1, activation=None, ): super(EqualLinear, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.lr_mul = lr_mul self.activation = activation if self.activation not in ["fused_lrelu", None]: raise ValueError( f"Wrong activation value in EqualLinear: {activation}" "Supported ones are: ['fused_lrelu', None]." ) self.scale = (1 / math.sqrt(in_channels)) * lr_mul self.weight = nn.Parameter(torch.randn(out_channels, in_channels).div_(lr_mul)) if bias: self.bias = nn.Parameter(torch.zeros(out_channels).fill_(bias_init_val)) else: self.register_parameter("bias", None) def forward(self, x): if self.bias is None: bias = None else: bias = self.bias * self.lr_mul if self.activation == "fused_lrelu": out = F.linear(x, self.weight * self.scale) out = fused_leaky_relu(out, bias) else: out = F.linear(x, self.weight * self.scale, bias=bias) return out def __repr__(self): return ( f"{self.__class__.__name__}(in_channels={self.in_channels}, " f"out_channels={self.out_channels}, bias={self.bias is not None})" ) class ModulatedConv2d(nn.Module): def __init__( self, in_channels, out_channels, kernel_size, num_style_feat, demodulate=True, sample_mode=None, resample_kernel=(1, 3, 3, 1), eps=1e-8, ): super(ModulatedConv2d, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.demodulate = demodulate self.sample_mode = sample_mode self.eps = eps if self.sample_mode == "upsample": self.smooth = UpFirDnSmooth( resample_kernel, upsample_factor=2, downsample_factor=1, kernel_size=kernel_size, ) elif self.sample_mode == "downsample": self.smooth = UpFirDnSmooth( resample_kernel, upsample_factor=1, downsample_factor=2, kernel_size=kernel_size, ) elif self.sample_mode is None: pass else: raise ValueError( f"Wrong sample mode {self.sample_mode}, " "supported ones are ['upsample', 'downsample', None]." ) self.scale = 1 / math.sqrt(in_channels * kernel_size**2) # modulation inside each modulated conv self.modulation = EqualLinear( num_style_feat, in_channels, bias=True, bias_init_val=1, lr_mul=1, activation=None, ) self.weight = nn.Parameter( torch.randn(1, out_channels, in_channels, kernel_size, kernel_size) ) self.padding = kernel_size // 2 def forward(self, x, style): b, c, h, w = x.shape # c = c_in # weight modulation style = self.modulation(style).view(b, 1, c, 1, 1) # self.weight: (1, c_out, c_in, k, k); style: (b, 1, c, 1, 1) weight = self.scale * self.weight * style # (b, c_out, c_in, k, k) if self.demodulate: demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + self.eps) weight = weight * demod.view(b, self.out_channels, 1, 1, 1) weight = weight.view( b * self.out_channels, c, self.kernel_size, self.kernel_size ) if self.sample_mode == "upsample": x = x.view(1, b * c, h, w) weight = weight.view( b, self.out_channels, c, self.kernel_size, self.kernel_size ) weight = weight.transpose(1, 2).reshape( b * c, self.out_channels, self.kernel_size, self.kernel_size ) out = F.conv_transpose2d(x, weight, padding=0, stride=2, groups=b) out = out.view(b, self.out_channels, *out.shape[2:4]) out = self.smooth(out) elif self.sample_mode == "downsample": x = self.smooth(x) x = x.view(1, b * c, *x.shape[2:4]) out = F.conv2d(x, weight, padding=0, stride=2, groups=b) out = out.view(b, self.out_channels, *out.shape[2:4]) else: x = x.view(1, b * c, h, w) # weight: (b*c_out, c_in, k, k), groups=b out = F.conv2d(x, weight, padding=self.padding, groups=b) out = out.view(b, self.out_channels, *out.shape[2:4]) return out def __repr__(self): return ( f"{self.__class__.__name__}(in_channels={self.in_channels}, " f"out_channels={self.out_channels}, " f"kernel_size={self.kernel_size}, " f"demodulate={self.demodulate}, sample_mode={self.sample_mode})" ) class StyleConv(nn.Module): def __init__( self, in_channels, out_channels, kernel_size, num_style_feat, demodulate=True, sample_mode=None, resample_kernel=(1, 3, 3, 1), ): super(StyleConv, self).__init__() self.modulated_conv = ModulatedConv2d( in_channels, out_channels, kernel_size, num_style_feat, demodulate=demodulate, sample_mode=sample_mode, resample_kernel=resample_kernel, ) self.weight = nn.Parameter(torch.zeros(1)) # for noise injection self.activate = FusedLeakyReLU(out_channels) def forward(self, x, style, noise=None): # modulate out = self.modulated_conv(x, style) # noise injection if noise is None: b, _, h, w = out.shape noise = out.new_empty(b, 1, h, w).normal_() out = out + self.weight * noise # activation (with bias) out = self.activate(out) return out class ToRGB(nn.Module): def __init__( self, in_channels, num_style_feat, upsample=True, resample_kernel=(1, 3, 3, 1) ): super(ToRGB, self).__init__() if upsample: self.upsample = UpFirDnUpsample(resample_kernel, factor=2) else: self.upsample = None self.modulated_conv = ModulatedConv2d( in_channels, 3, kernel_size=1, num_style_feat=num_style_feat, demodulate=False, sample_mode=None, ) self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1)) def forward(self, x, style, skip=None): out = self.modulated_conv(x, style) out = out + self.bias if skip is not None: if self.upsample: skip = self.upsample(skip) out = out + skip return out class ConstantInput(nn.Module): def __init__(self, num_channel, size): super(ConstantInput, self).__init__() self.weight = nn.Parameter(torch.randn(1, num_channel, size, size)) def forward(self, batch): out = self.weight.repeat(batch, 1, 1, 1) return out class StyleGAN2Generator(nn.Module): def __init__( self, out_size, num_style_feat=512, num_mlp=8, channel_multiplier=2, resample_kernel=(1, 3, 3, 1), lr_mlp=0.01, narrow=1, ): super(StyleGAN2Generator, self).__init__() # Style MLP layers self.num_style_feat = num_style_feat style_mlp_layers = [NormStyleCode()] for i in range(num_mlp): style_mlp_layers.append( EqualLinear( num_style_feat, num_style_feat, bias=True, bias_init_val=0, lr_mul=lr_mlp, activation="fused_lrelu", ) ) self.style_mlp = nn.Sequential(*style_mlp_layers) channels = { "4": int(512 * narrow), "8": int(512 * narrow), "16": int(512 * narrow), "32": int(512 * narrow), "64": int(256 * channel_multiplier * narrow), "128": int(128 * channel_multiplier * narrow), "256": int(64 * channel_multiplier * narrow), "512": int(32 * channel_multiplier * narrow), "1024": int(16 * channel_multiplier * narrow), } self.channels = channels self.constant_input = ConstantInput(channels["4"], size=4) self.style_conv1 = StyleConv( channels["4"], channels["4"], kernel_size=3, num_style_feat=num_style_feat, demodulate=True, sample_mode=None, resample_kernel=resample_kernel, ) self.to_rgb1 = ToRGB( channels["4"], num_style_feat, upsample=False, resample_kernel=resample_kernel, ) self.log_size = int(math.log(out_size, 2)) self.num_layers = (self.log_size - 2) * 2 + 1 self.num_latent = self.log_size * 2 - 2 self.style_convs = nn.ModuleList() self.to_rgbs = nn.ModuleList() self.noises = nn.Module() in_channels = channels["4"] # noise for layer_idx in range(self.num_layers): resolution = 2 ** ((layer_idx + 5) // 2) shape = [1, 1, resolution, resolution] self.noises.register_buffer(f"noise{layer_idx}", torch.randn(*shape)) # style convs and to_rgbs for i in range(3, self.log_size + 1): out_channels = channels[f"{2**i}"] self.style_convs.append( StyleConv( in_channels, out_channels, kernel_size=3, num_style_feat=num_style_feat, demodulate=True, sample_mode="upsample", resample_kernel=resample_kernel, ) ) self.style_convs.append( StyleConv( out_channels, out_channels, kernel_size=3, num_style_feat=num_style_feat, demodulate=True, sample_mode=None, resample_kernel=resample_kernel, ) ) self.to_rgbs.append( ToRGB( out_channels, num_style_feat, upsample=True, resample_kernel=resample_kernel, ) ) in_channels = out_channels def make_noise(self): device = self.constant_input.weight.device noises = [torch.randn(1, 1, 4, 4, device=device)] for i in range(3, self.log_size + 1): for _ in range(2): noises.append(torch.randn(1, 1, 2**i, 2**i, device=device)) return noises def get_latent(self, x): return self.style_mlp(x) def mean_latent(self, num_latent): latent_in = torch.randn( num_latent, self.num_style_feat, device=self.constant_input.weight.device ) latent = self.style_mlp(latent_in).mean(0, keepdim=True) return latent def forward( self, styles, input_is_latent=False, noise=None, randomize_noise=True, truncation=1, truncation_latent=None, inject_index=None, return_latents=False, ): # style codes -> latents with Style MLP layer if not input_is_latent: styles = [self.style_mlp(s) for s in styles] # noises if noise is None: if randomize_noise: noise = [None] * self.num_layers # for each style conv layer else: # use the stored noise noise = [ getattr(self.noises, f"noise{i}") for i in range(self.num_layers) ] # style truncation if truncation < 1: style_truncation = [] for style in styles: style_truncation.append( truncation_latent + truncation * (style - truncation_latent) ) styles = style_truncation # get style latent with injection if len(styles) == 1: inject_index = self.num_latent if styles[0].ndim < 3: # repeat latent code for all the layers latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1) else: # used for encoder with different latent code for each layer latent = styles[0] elif len(styles) == 2: # mixing noises if inject_index is None: inject_index = random.randint(1, self.num_latent - 1) latent1 = styles[0].unsqueeze(1).repeat(1, inject_index, 1) latent2 = ( styles[1].unsqueeze(1).repeat(1, self.num_latent - inject_index, 1) ) latent = torch.cat([latent1, latent2], 1) # main generation out = self.constant_input(latent.shape[0]) out = self.style_conv1(out, latent[:, 0], noise=noise[0]) skip = self.to_rgb1(out, latent[:, 1]) i = 1 for conv1, conv2, noise1, noise2, to_rgb in zip( self.style_convs[::2], self.style_convs[1::2], noise[1::2], noise[2::2], self.to_rgbs, ): out = conv1(out, latent[:, i], noise=noise1) out = conv2(out, latent[:, i + 1], noise=noise2) skip = to_rgb(out, latent[:, i + 2], skip) i += 2 image = skip if return_latents: return image, latent else: return image, None class ScaledLeakyReLU(nn.Module): def __init__(self, negative_slope=0.2): super(ScaledLeakyReLU, self).__init__() self.negative_slope = negative_slope def forward(self, x): out = F.leaky_relu(x, negative_slope=self.negative_slope) return out * math.sqrt(2) class EqualConv2d(nn.Module): def __init__( self, in_channels, out_channels, kernel_size, stride=1, padding=0, bias=True, bias_init_val=0, ): super(EqualConv2d, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.stride = stride self.padding = padding self.scale = 1 / math.sqrt(in_channels * kernel_size**2) self.weight = nn.Parameter( torch.randn(out_channels, in_channels, kernel_size, kernel_size) ) if bias: self.bias = nn.Parameter(torch.zeros(out_channels).fill_(bias_init_val)) else: self.register_parameter("bias", None) def forward(self, x): out = F.conv2d( x, self.weight * self.scale, bias=self.bias, stride=self.stride, padding=self.padding, ) return out def __repr__(self): return ( f"{self.__class__.__name__}(in_channels={self.in_channels}, " f"out_channels={self.out_channels}, " f"kernel_size={self.kernel_size}," f" stride={self.stride}, padding={self.padding}, " f"bias={self.bias is not None})" ) class ConvLayer(nn.Sequential): def __init__( self, in_channels, out_channels, kernel_size, downsample=False, resample_kernel=(1, 3, 3, 1), bias=True, activate=True, ): layers = [] # downsample if downsample: layers.append( UpFirDnSmooth( resample_kernel, upsample_factor=1, downsample_factor=2, kernel_size=kernel_size, ) ) stride = 2 self.padding = 0 else: stride = 1 self.padding = kernel_size // 2 # conv layers.append( EqualConv2d( in_channels, out_channels, kernel_size, stride=stride, padding=self.padding, bias=bias and not activate, ) ) # activation if activate: if bias: layers.append(FusedLeakyReLU(out_channels)) else: layers.append(ScaledLeakyReLU(0.2)) super(ConvLayer, self).__init__(*layers) class ResBlock(nn.Module): def __init__(self, in_channels, out_channels, resample_kernel=(1, 3, 3, 1)): super(ResBlock, self).__init__() self.conv1 = ConvLayer(in_channels, in_channels, 3, bias=True, activate=True) self.conv2 = ConvLayer( in_channels, out_channels, 3, downsample=True, resample_kernel=resample_kernel, bias=True, activate=True, ) self.skip = ConvLayer( in_channels, out_channels, 1, downsample=True, resample_kernel=resample_kernel, bias=False, activate=False, ) def forward(self, x): out = self.conv1(x) out = self.conv2(out) skip = self.skip(x) out = (out + skip) / math.sqrt(2) return out
--- +++ @@ -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**2, dim=1, keepdim=True) + 1e-8) def make_resample_kernel(k): + """Make resampling kernel for UpFirDn. + + Args: + k (list[int]): A list indicating the 1D resample kernel magnitude. + + Returns: + Tensor: 2D resampled kernel. + """ k = torch.tensor(k, dtype=torch.float32) if k.ndim == 1: k = k[None, :] * k[:, None] # to 2D kernel, outer product @@ -26,6 +42,17 @@ class UpFirDnUpsample(nn.Module): + """Upsample, FIR filter, and downsample (upsampole version). + + References: + 1. https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.upfirdn.html # noqa: E501 + 2. http://www.ece.northwestern.edu/local-apps/matlabhelp/toolbox/signal/upfirdn.html # noqa: E501 + + Args: + resample_kernel (list[int]): A list indicating the 1D resample kernel + magnitude. + factor (int): Upsampling scale factor. Default: 2. + """ def __init__(self, resample_kernel, factor=2): super(UpFirDnUpsample, self).__init__() @@ -44,6 +71,13 @@ class UpFirDnDownsample(nn.Module): + """Upsample, FIR filter, and downsample (downsampole version). + + Args: + resample_kernel (list[int]): A list indicating the 1D resample kernel + magnitude. + factor (int): Downsampling scale factor. Default: 2. + """ def __init__(self, resample_kernel, factor=2): super(UpFirDnDownsample, self).__init__() @@ -62,6 +96,15 @@ class UpFirDnSmooth(nn.Module): + """Upsample, FIR filter, and downsample (smooth version). + + Args: + resample_kernel (list[int]): A list indicating the 1D resample kernel + magnitude. + upsample_factor (int): Upsampling scale factor. Default: 1. + downsample_factor (int): Downsampling scale factor. Default: 1. + kernel_size (int): Kernel size: Default: 1. + """ def __init__( self, resample_kernel, upsample_factor=1, downsample_factor=1, kernel_size=1 @@ -94,6 +137,18 @@ class EqualLinear(nn.Module): + """Equalized Linear as StyleGAN2. + + Args: + in_channels (int): Size of each sample. + out_channels (int): Size of each output sample. + bias (bool): If set to ``False``, the layer will not learn an additive + bias. Default: ``True``. + bias_init_val (float): Bias initialized value. Default: 0. + lr_mul (float): Learning rate multiplier. Default: 1. + activation (None | str): The activation after ``linear`` operation. + Supported: 'fused_lrelu', None. Default: None. + """ def __init__( self, @@ -142,6 +197,24 @@ class ModulatedConv2d(nn.Module): + """Modulated Conv2d used in StyleGAN2. + + There is no bias in ModulatedConv2d. + + Args: + in_channels (int): Channel number of the input. + out_channels (int): Channel number of the output. + kernel_size (int): Size of the convolving kernel. + num_style_feat (int): Channel number of style features. + demodulate (bool): Whether to demodulate in the conv layer. + Default: True. + sample_mode (str | None): Indicating 'upsample', 'downsample' or None. + Default: None. + resample_kernel (list[int]): A list indicating the 1D resample kernel + magnitude. Default: (1, 3, 3, 1). + eps (float): A value added to the denominator for numerical stability. + Default: 1e-8. + """ def __init__( self, @@ -201,6 +274,15 @@ self.padding = kernel_size // 2 def forward(self, x, style): + """Forward function. + + Args: + x (Tensor): Tensor with shape (b, c, h, w). + style (Tensor): Tensor with shape (b, num_style_feat). + + Returns: + Tensor: Modulated tensor after convolution. + """ b, c, h, w = x.shape # c = c_in # weight modulation style = self.modulation(style).view(b, 1, c, 1, 1) @@ -249,6 +331,19 @@ class StyleConv(nn.Module): + """Style conv. + + Args: + in_channels (int): Channel number of the input. + out_channels (int): Channel number of the output. + kernel_size (int): Size of the convolving kernel. + num_style_feat (int): Channel number of style features. + demodulate (bool): Whether demodulate in the conv layer. Default: True. + sample_mode (str | None): Indicating 'upsample', 'downsample' or None. + Default: None. + resample_kernel (list[int]): A list indicating the 1D resample kernel + magnitude. Default: (1, 3, 3, 1). + """ def __init__( self, @@ -287,6 +382,15 @@ class ToRGB(nn.Module): + """To RGB from features. + + Args: + in_channels (int): Channel number of input. + num_style_feat (int): Channel number of style features. + upsample (bool): Whether to upsample. Default: True. + resample_kernel (list[int]): A list indicating the 1D resample kernel + magnitude. Default: (1, 3, 3, 1). + """ def __init__( self, in_channels, num_style_feat, upsample=True, resample_kernel=(1, 3, 3, 1) @@ -307,6 +411,16 @@ self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1)) def forward(self, x, style, skip=None): + """Forward function. + + Args: + x (Tensor): Feature tensor with shape (b, c, h, w). + style (Tensor): Tensor with shape (b, num_style_feat). + skip (Tensor): Base/skip tensor. Default: None. + + Returns: + Tensor: RGB images. + """ out = self.modulated_conv(x, style) out = out + self.bias if skip is not None: @@ -317,6 +431,12 @@ class ConstantInput(nn.Module): + """Constant input. + + Args: + num_channel (int): Channel number of constant input. + size (int): Spatial size of constant input. + """ def __init__(self, num_channel, size): super(ConstantInput, self).__init__() @@ -328,6 +448,20 @@ class StyleGAN2Generator(nn.Module): + """StyleGAN2 Generator. + + Args: + out_size (int): The spatial size of outputs. + num_style_feat (int): Channel number of style features. Default: 512. + num_mlp (int): Layer number of MLP style layers. Default: 8. + channel_multiplier (int): Channel multiplier for large networks of + StyleGAN2. Default: 2. + resample_kernel (list[int]): A list indicating the 1D resample kernel + magnitude. A cross production will be applied to extent 1D resample + kernel to 2D resample kernel. Default: (1, 3, 3, 1). + lr_mlp (float): Learning rate multiplier for mlp layers. Default: 0.01. + narrow (float): Narrow ratio for channels. Default: 1.0. + """ def __init__( self, @@ -436,6 +570,7 @@ in_channels = out_channels def make_noise(self): + """Make noise for noise injection.""" device = self.constant_input.weight.device noises = [torch.randn(1, 1, 4, 4, device=device)] @@ -466,6 +601,22 @@ inject_index=None, return_latents=False, ): + """Forward function for StyleGAN2Generator. + + Args: + styles (list[Tensor]): Sample codes of styles. + input_is_latent (bool): Whether input is latent style. + Default: False. + noise (Tensor | None): Input noise or None. Default: None. + randomize_noise (bool): Randomize noise, used when 'noise' is + False. Default: True. + truncation (float): TODO. Default: 1. + truncation_latent (Tensor | None): TODO. Default: None. + inject_index (int | None): The injection index for mixing noise. + Default: None. + return_latents (bool): Whether to return style latents. + Default: False. + """ # style codes -> latents with Style MLP layer if not input_is_latent: styles = [self.style_mlp(s) for s in styles] @@ -530,6 +681,11 @@ class ScaledLeakyReLU(nn.Module): + """Scaled LeakyReLU. + + Args: + negative_slope (float): Negative slope. Default: 0.2. + """ def __init__(self, negative_slope=0.2): super(ScaledLeakyReLU, self).__init__() @@ -541,6 +697,19 @@ class EqualConv2d(nn.Module): + """Equalized Linear as StyleGAN2. + + Args: + in_channels (int): Channel number of the input. + out_channels (int): Channel number of the output. + kernel_size (int): Size of the convolving kernel. + stride (int): Stride of the convolution. Default: 1 + padding (int): Zero-padding added to both sides of the input. + Default: 0. + bias (bool): If ``True``, adds a learnable bias to the output. + Default: ``True``. + bias_init_val (float): Bias initialized value. Default: 0. + """ def __init__( self, @@ -590,6 +759,21 @@ class ConvLayer(nn.Sequential): + """Conv Layer used in StyleGAN2 Discriminator. + + Args: + in_channels (int): Channel number of the input. + out_channels (int): Channel number of the output. + kernel_size (int): Kernel size. + downsample (bool): Whether downsample by a factor of 2. + Default: False. + resample_kernel (list[int]): A list indicating the 1D resample + kernel magnitude. A cross production will be applied to + extent 1D resample kernel to 2D resample kernel. + Default: (1, 3, 3, 1). + bias (bool): Whether with bias. Default: True. + activate (bool): Whether use activateion. Default: True. + """ def __init__( self, @@ -639,6 +823,16 @@ class ResBlock(nn.Module): + """Residual block used in StyleGAN2 Discriminator. + + Args: + in_channels (int): Channel number of the input. + out_channels (int): Channel number of the output. + resample_kernel (list[int]): A list indicating the 1D resample + kernel magnitude. A cross production will be applied to + extent 1D resample kernel to 2D resample kernel. + Default: (1, 3, 3, 1). + """ def __init__(self, in_channels, out_channels, resample_kernel=(1, 3, 3, 1)): super(ResBlock, self).__init__() @@ -668,4 +862,4 @@ out = self.conv2(out) skip = self.skip(x) out = (out + skip) / math.sqrt(2) - return out+ return out
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) + 1e-8) class EqualLinear(nn.Module): def __init__( self, in_channels, out_channels, bias=True, bias_init_val=0, lr_mul=1, activation=None, ): super(EqualLinear, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.lr_mul = lr_mul self.activation = activation if self.activation not in ["fused_lrelu", None]: raise ValueError( f"Wrong activation value in EqualLinear: {activation}" "Supported ones are: ['fused_lrelu', None]." ) self.scale = (1 / math.sqrt(in_channels)) * lr_mul self.weight = nn.Parameter(torch.randn(out_channels, in_channels).div_(lr_mul)) if bias: self.bias = nn.Parameter(torch.zeros(out_channels).fill_(bias_init_val)) else: self.register_parameter("bias", None) def forward(self, x): if self.bias is None: bias = None else: bias = self.bias * self.lr_mul if self.activation == "fused_lrelu": out = F.linear(x, self.weight * self.scale) out = fused_leaky_relu(out, bias) else: out = F.linear(x, self.weight * self.scale, bias=bias) return out def __repr__(self): return ( f"{self.__class__.__name__}(in_channels={self.in_channels}, " f"out_channels={self.out_channels}, bias={self.bias is not None})" ) class ModulatedConv2d(nn.Module): def __init__( self, in_channels, out_channels, kernel_size, num_style_feat, demodulate=True, sample_mode=None, eps=1e-8, interpolation_mode="bilinear", ): super(ModulatedConv2d, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.demodulate = demodulate self.sample_mode = sample_mode self.eps = eps self.interpolation_mode = interpolation_mode if self.interpolation_mode == "nearest": self.align_corners = None else: self.align_corners = False self.scale = 1 / math.sqrt(in_channels * kernel_size**2) # modulation inside each modulated conv self.modulation = EqualLinear( num_style_feat, in_channels, bias=True, bias_init_val=1, lr_mul=1, activation=None, ) self.weight = nn.Parameter( torch.randn(1, out_channels, in_channels, kernel_size, kernel_size) ) self.padding = kernel_size // 2 def forward(self, x, style): b, c, h, w = x.shape # c = c_in # weight modulation style = self.modulation(style).view(b, 1, c, 1, 1) # self.weight: (1, c_out, c_in, k, k); style: (b, 1, c, 1, 1) weight = self.scale * self.weight * style # (b, c_out, c_in, k, k) if self.demodulate: demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + self.eps) weight = weight * demod.view(b, self.out_channels, 1, 1, 1) weight = weight.view( b * self.out_channels, c, self.kernel_size, self.kernel_size ) if self.sample_mode == "upsample": x = F.interpolate( x, scale_factor=2, mode=self.interpolation_mode, align_corners=self.align_corners, ) elif self.sample_mode == "downsample": x = F.interpolate( x, scale_factor=0.5, mode=self.interpolation_mode, align_corners=self.align_corners, ) b, c, h, w = x.shape x = x.view(1, b * c, h, w) # weight: (b*c_out, c_in, k, k), groups=b out = F.conv2d(x, weight, padding=self.padding, groups=b) out = out.view(b, self.out_channels, *out.shape[2:4]) return out def __repr__(self): return ( f"{self.__class__.__name__}(in_channels={self.in_channels}, " f"out_channels={self.out_channels}, " f"kernel_size={self.kernel_size}, " f"demodulate={self.demodulate}, sample_mode={self.sample_mode})" ) class StyleConv(nn.Module): def __init__( self, in_channels, out_channels, kernel_size, num_style_feat, demodulate=True, sample_mode=None, interpolation_mode="bilinear", ): super(StyleConv, self).__init__() self.modulated_conv = ModulatedConv2d( in_channels, out_channels, kernel_size, num_style_feat, demodulate=demodulate, sample_mode=sample_mode, interpolation_mode=interpolation_mode, ) self.weight = nn.Parameter(torch.zeros(1)) # for noise injection self.activate = FusedLeakyReLU(out_channels) def forward(self, x, style, noise=None): # modulate out = self.modulated_conv(x, style) # noise injection if noise is None: b, _, h, w = out.shape noise = out.new_empty(b, 1, h, w).normal_() out = out + self.weight * noise # activation (with bias) out = self.activate(out) return out class ToRGB(nn.Module): def __init__( self, in_channels, num_style_feat, upsample=True, interpolation_mode="bilinear" ): super(ToRGB, self).__init__() self.upsample = upsample self.interpolation_mode = interpolation_mode if self.interpolation_mode == "nearest": self.align_corners = None else: self.align_corners = False self.modulated_conv = ModulatedConv2d( in_channels, 3, kernel_size=1, num_style_feat=num_style_feat, demodulate=False, sample_mode=None, interpolation_mode=interpolation_mode, ) self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1)) def forward(self, x, style, skip=None): out = self.modulated_conv(x, style) out = out + self.bias if skip is not None: if self.upsample: skip = F.interpolate( skip, scale_factor=2, mode=self.interpolation_mode, align_corners=self.align_corners, ) out = out + skip return out class ConstantInput(nn.Module): def __init__(self, num_channel, size): super(ConstantInput, self).__init__() self.weight = nn.Parameter(torch.randn(1, num_channel, size, size)) def forward(self, batch): out = self.weight.repeat(batch, 1, 1, 1) return out class StyleGAN2GeneratorBilinear(nn.Module): def __init__( self, out_size, num_style_feat=512, num_mlp=8, channel_multiplier=2, lr_mlp=0.01, narrow=1, interpolation_mode="bilinear", ): super(StyleGAN2GeneratorBilinear, self).__init__() # Style MLP layers self.num_style_feat = num_style_feat style_mlp_layers = [NormStyleCode()] for i in range(num_mlp): style_mlp_layers.append( EqualLinear( num_style_feat, num_style_feat, bias=True, bias_init_val=0, lr_mul=lr_mlp, activation="fused_lrelu", ) ) self.style_mlp = nn.Sequential(*style_mlp_layers) channels = { "4": int(512 * narrow), "8": int(512 * narrow), "16": int(512 * narrow), "32": int(512 * narrow), "64": int(256 * channel_multiplier * narrow), "128": int(128 * channel_multiplier * narrow), "256": int(64 * channel_multiplier * narrow), "512": int(32 * channel_multiplier * narrow), "1024": int(16 * channel_multiplier * narrow), } self.channels = channels self.constant_input = ConstantInput(channels["4"], size=4) self.style_conv1 = StyleConv( channels["4"], channels["4"], kernel_size=3, num_style_feat=num_style_feat, demodulate=True, sample_mode=None, interpolation_mode=interpolation_mode, ) self.to_rgb1 = ToRGB( channels["4"], num_style_feat, upsample=False, interpolation_mode=interpolation_mode, ) self.log_size = int(math.log(out_size, 2)) self.num_layers = (self.log_size - 2) * 2 + 1 self.num_latent = self.log_size * 2 - 2 self.style_convs = nn.ModuleList() self.to_rgbs = nn.ModuleList() self.noises = nn.Module() in_channels = channels["4"] # noise for layer_idx in range(self.num_layers): resolution = 2 ** ((layer_idx + 5) // 2) shape = [1, 1, resolution, resolution] self.noises.register_buffer(f"noise{layer_idx}", torch.randn(*shape)) # style convs and to_rgbs for i in range(3, self.log_size + 1): out_channels = channels[f"{2**i}"] self.style_convs.append( StyleConv( in_channels, out_channels, kernel_size=3, num_style_feat=num_style_feat, demodulate=True, sample_mode="upsample", interpolation_mode=interpolation_mode, ) ) self.style_convs.append( StyleConv( out_channels, out_channels, kernel_size=3, num_style_feat=num_style_feat, demodulate=True, sample_mode=None, interpolation_mode=interpolation_mode, ) ) self.to_rgbs.append( ToRGB( out_channels, num_style_feat, upsample=True, interpolation_mode=interpolation_mode, ) ) in_channels = out_channels def make_noise(self): device = self.constant_input.weight.device noises = [torch.randn(1, 1, 4, 4, device=device)] for i in range(3, self.log_size + 1): for _ in range(2): noises.append(torch.randn(1, 1, 2**i, 2**i, device=device)) return noises def get_latent(self, x): return self.style_mlp(x) def mean_latent(self, num_latent): latent_in = torch.randn( num_latent, self.num_style_feat, device=self.constant_input.weight.device ) latent = self.style_mlp(latent_in).mean(0, keepdim=True) return latent def forward( self, styles, input_is_latent=False, noise=None, randomize_noise=True, truncation=1, truncation_latent=None, inject_index=None, return_latents=False, ): # style codes -> latents with Style MLP layer if not input_is_latent: styles = [self.style_mlp(s) for s in styles] # noises if noise is None: if randomize_noise: noise = [None] * self.num_layers # for each style conv layer else: # use the stored noise noise = [ getattr(self.noises, f"noise{i}") for i in range(self.num_layers) ] # style truncation if truncation < 1: style_truncation = [] for style in styles: style_truncation.append( truncation_latent + truncation * (style - truncation_latent) ) styles = style_truncation # get style latent with injection if len(styles) == 1: inject_index = self.num_latent if styles[0].ndim < 3: # repeat latent code for all the layers latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1) else: # used for encoder with different latent code for each layer latent = styles[0] elif len(styles) == 2: # mixing noises if inject_index is None: inject_index = random.randint(1, self.num_latent - 1) latent1 = styles[0].unsqueeze(1).repeat(1, inject_index, 1) latent2 = ( styles[1].unsqueeze(1).repeat(1, self.num_latent - inject_index, 1) ) latent = torch.cat([latent1, latent2], 1) # main generation out = self.constant_input(latent.shape[0]) out = self.style_conv1(out, latent[:, 0], noise=noise[0]) skip = self.to_rgb1(out, latent[:, 1]) i = 1 for conv1, conv2, noise1, noise2, to_rgb in zip( self.style_convs[::2], self.style_convs[1::2], noise[1::2], noise[2::2], self.to_rgbs, ): out = conv1(out, latent[:, i], noise=noise1) out = conv2(out, latent[:, i + 1], noise=noise2) skip = to_rgb(out, latent[:, i + 2], skip) i += 2 image = skip if return_latents: return image, latent else: return image, None class ScaledLeakyReLU(nn.Module): def __init__(self, negative_slope=0.2): super(ScaledLeakyReLU, self).__init__() self.negative_slope = negative_slope def forward(self, x): out = F.leaky_relu(x, negative_slope=self.negative_slope) return out * math.sqrt(2) class EqualConv2d(nn.Module): def __init__( self, in_channels, out_channels, kernel_size, stride=1, padding=0, bias=True, bias_init_val=0, ): super(EqualConv2d, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.stride = stride self.padding = padding self.scale = 1 / math.sqrt(in_channels * kernel_size**2) self.weight = nn.Parameter( torch.randn(out_channels, in_channels, kernel_size, kernel_size) ) if bias: self.bias = nn.Parameter(torch.zeros(out_channels).fill_(bias_init_val)) else: self.register_parameter("bias", None) def forward(self, x): out = F.conv2d( x, self.weight * self.scale, bias=self.bias, stride=self.stride, padding=self.padding, ) return out def __repr__(self): return ( f"{self.__class__.__name__}(in_channels={self.in_channels}, " f"out_channels={self.out_channels}, " f"kernel_size={self.kernel_size}," f" stride={self.stride}, padding={self.padding}, " f"bias={self.bias is not None})" ) class ConvLayer(nn.Sequential): def __init__( self, in_channels, out_channels, kernel_size, downsample=False, bias=True, activate=True, interpolation_mode="bilinear", ): layers = [] self.interpolation_mode = interpolation_mode # downsample if downsample: if self.interpolation_mode == "nearest": self.align_corners = None else: self.align_corners = False layers.append( torch.nn.Upsample( scale_factor=0.5, mode=interpolation_mode, align_corners=self.align_corners, ) ) stride = 1 self.padding = kernel_size // 2 # conv layers.append( EqualConv2d( in_channels, out_channels, kernel_size, stride=stride, padding=self.padding, bias=bias and not activate, ) ) # activation if activate: if bias: layers.append(FusedLeakyReLU(out_channels)) else: layers.append(ScaledLeakyReLU(0.2)) super(ConvLayer, self).__init__(*layers) class ResBlock(nn.Module): def __init__(self, in_channels, out_channels, interpolation_mode="bilinear"): super(ResBlock, self).__init__() self.conv1 = ConvLayer(in_channels, in_channels, 3, bias=True, activate=True) self.conv2 = ConvLayer( in_channels, out_channels, 3, downsample=True, interpolation_mode=interpolation_mode, bias=True, activate=True, ) self.skip = ConvLayer( in_channels, out_channels, 1, downsample=True, interpolation_mode=interpolation_mode, bias=False, activate=False, ) def forward(self, x): out = self.conv1(x) out = self.conv2(out) skip = self.skip(x) out = (out + skip) / math.sqrt(2) return out
--- +++ @@ -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, dim=1, keepdim=True) + 1e-8) class EqualLinear(nn.Module): + """Equalized Linear as StyleGAN2. + Args: + in_channels (int): Size of each sample. + out_channels (int): Size of each output sample. + bias (bool): If set to ``False``, the layer will not learn an additive + bias. Default: ``True``. + bias_init_val (float): Bias initialized value. Default: 0. + lr_mul (float): Learning rate multiplier. Default: 1. + activation (None | str): The activation after ``linear`` operation. + Supported: 'fused_lrelu', None. Default: None. + """ def __init__( self, @@ -64,6 +81,20 @@ class ModulatedConv2d(nn.Module): + """Modulated Conv2d used in StyleGAN2. + There is no bias in ModulatedConv2d. + Args: + in_channels (int): Channel number of the input. + out_channels (int): Channel number of the output. + kernel_size (int): Size of the convolving kernel. + num_style_feat (int): Channel number of style features. + demodulate (bool): Whether to demodulate in the conv layer. + Default: True. + sample_mode (str | None): Indicating 'upsample', 'downsample' or None. + Default: None. + eps (float): A value added to the denominator for numerical stability. + Default: 1e-8. + """ def __init__( self, @@ -106,6 +137,13 @@ self.padding = kernel_size // 2 def forward(self, x, style): + """Forward function. + Args: + x (Tensor): Tensor with shape (b, c, h, w). + style (Tensor): Tensor with shape (b, num_style_feat). + Returns: + Tensor: Modulated tensor after convolution. + """ b, c, h, w = x.shape # c = c_in # weight modulation style = self.modulation(style).view(b, 1, c, 1, 1) @@ -153,6 +191,16 @@ class StyleConv(nn.Module): + """Style conv. + Args: + in_channels (int): Channel number of the input. + out_channels (int): Channel number of the output. + kernel_size (int): Size of the convolving kernel. + num_style_feat (int): Channel number of style features. + demodulate (bool): Whether demodulate in the conv layer. Default: True. + sample_mode (str | None): Indicating 'upsample', 'downsample' or None. + Default: None. + """ def __init__( self, @@ -191,6 +239,12 @@ class ToRGB(nn.Module): + """To RGB from features. + Args: + in_channels (int): Channel number of input. + num_style_feat (int): Channel number of style features. + upsample (bool): Whether to upsample. Default: True. + """ def __init__( self, in_channels, num_style_feat, upsample=True, interpolation_mode="bilinear" @@ -214,6 +268,14 @@ self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1)) def forward(self, x, style, skip=None): + """Forward function. + Args: + x (Tensor): Feature tensor with shape (b, c, h, w). + style (Tensor): Tensor with shape (b, num_style_feat). + skip (Tensor): Base/skip tensor. Default: None. + Returns: + Tensor: RGB images. + """ out = self.modulated_conv(x, style) out = out + self.bias if skip is not None: @@ -229,6 +291,11 @@ class ConstantInput(nn.Module): + """Constant input. + Args: + num_channel (int): Channel number of constant input. + size (int): Spatial size of constant input. + """ def __init__(self, num_channel, size): super(ConstantInput, self).__init__() @@ -240,6 +307,16 @@ class StyleGAN2GeneratorBilinear(nn.Module): + """StyleGAN2 Generator. + Args: + out_size (int): The spatial size of outputs. + num_style_feat (int): Channel number of style features. Default: 512. + num_mlp (int): Layer number of MLP style layers. Default: 8. + channel_multiplier (int): Channel multiplier for large networks of + StyleGAN2. Default: 2. + lr_mlp (float): Learning rate multiplier for mlp layers. Default: 0.01. + narrow (float): Narrow ratio for channels. Default: 1.0. + """ def __init__( self, @@ -348,6 +425,7 @@ in_channels = out_channels def make_noise(self): + """Make noise for noise injection.""" device = self.constant_input.weight.device noises = [torch.randn(1, 1, 4, 4, device=device)] @@ -378,6 +456,21 @@ inject_index=None, return_latents=False, ): + """Forward function for StyleGAN2Generator. + Args: + styles (list[Tensor]): Sample codes of styles. + input_is_latent (bool): Whether input is latent style. + Default: False. + noise (Tensor | None): Input noise or None. Default: None. + randomize_noise (bool): Randomize noise, used when 'noise' is + False. Default: True. + truncation (float): TODO. Default: 1. + truncation_latent (Tensor | None): TODO. Default: None. + inject_index (int | None): The injection index for mixing noise. + Default: None. + return_latents (bool): Whether to return style latents. + Default: False. + """ # style codes -> latents with Style MLP layer if not input_is_latent: styles = [self.style_mlp(s) for s in styles] @@ -442,6 +535,10 @@ class ScaledLeakyReLU(nn.Module): + """Scaled LeakyReLU. + Args: + negative_slope (float): Negative slope. Default: 0.2. + """ def __init__(self, negative_slope=0.2): super(ScaledLeakyReLU, self).__init__() @@ -453,6 +550,18 @@ class EqualConv2d(nn.Module): + """Equalized Linear as StyleGAN2. + Args: + in_channels (int): Channel number of the input. + out_channels (int): Channel number of the output. + kernel_size (int): Size of the convolving kernel. + stride (int): Stride of the convolution. Default: 1 + padding (int): Zero-padding added to both sides of the input. + Default: 0. + bias (bool): If ``True``, adds a learnable bias to the output. + Default: ``True``. + bias_init_val (float): Bias initialized value. Default: 0. + """ def __init__( self, @@ -502,6 +611,16 @@ class ConvLayer(nn.Sequential): + """Conv Layer used in StyleGAN2 Discriminator. + Args: + in_channels (int): Channel number of the input. + out_channels (int): Channel number of the output. + kernel_size (int): Kernel size. + downsample (bool): Whether downsample by a factor of 2. + Default: False. + bias (bool): Whether with bias. Default: True. + activate (bool): Whether use activateion. Default: True. + """ def __init__( self, @@ -553,6 +672,11 @@ class ResBlock(nn.Module): + """Residual block used in StyleGAN2 Discriminator. + Args: + in_channels (int): Channel number of the input. + out_channels (int): Channel number of the output. + """ def __init__(self, in_channels, out_channels, interpolation_mode="bilinear"): super(ResBlock, self).__init__() @@ -582,4 +706,4 @@ out = self.conv2(out) skip = self.skip(x) out = (out + skip) / math.sqrt(2) - return out+ return out
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 = (Image.Resampling.LANCZOS if hasattr(Image, 'Resampling') else Image.LANCZOS) # Regexp compiled once. Matches entries with the following pattern: # <lora:some_lora:1> # <lora:aNotherLora:-1.6> LORAS_PROMPT_PATTERN = re.compile(r"(<lora:([^:]+):([+-]?(?:\d+(?:\.\d*)?|\.\d+))>)", re.X) HASH_SHA256_LENGTH = 10 def erode_or_dilate(x, k): k = int(k) if k > 0: return cv2.dilate(x, kernel=np.ones(shape=(3, 3), dtype=np.uint8), iterations=k) if k < 0: return cv2.erode(x, kernel=np.ones(shape=(3, 3), dtype=np.uint8), iterations=-k) return x def resample_image(im, width, height): im = Image.fromarray(im) im = im.resize((int(width), int(height)), resample=LANCZOS) return np.array(im) def resize_image(im, width, height, resize_mode=1): im = Image.fromarray(im) def resize(im, w, h): return im.resize((w, h), resample=LANCZOS) if resize_mode == 0: res = resize(im, width, height) elif resize_mode == 1: ratio = width / height src_ratio = im.width / im.height src_w = width if ratio > src_ratio else im.width * height // im.height src_h = height if ratio <= src_ratio else im.height * width // im.width resized = resize(im, src_w, src_h) res = Image.new("RGB", (width, height)) res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2)) else: ratio = width / height src_ratio = im.width / im.height src_w = width if ratio < src_ratio else im.width * height // im.height src_h = height if ratio >= src_ratio else im.height * width // im.width resized = resize(im, src_w, src_h) res = Image.new("RGB", (width, height)) res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2)) if ratio < src_ratio: fill_height = height // 2 - src_h // 2 if fill_height > 0: res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0)) res.paste(resized.resize((width, fill_height), box=(0, resized.height, width, resized.height)), box=(0, fill_height + src_h)) elif ratio > src_ratio: fill_width = width // 2 - src_w // 2 if fill_width > 0: res.paste(resized.resize((fill_width, height), box=(0, 0, 0, height)), box=(0, 0)) res.paste(resized.resize((fill_width, height), box=(resized.width, 0, resized.width, height)), box=(fill_width + src_w, 0)) return np.array(res) def get_shape_ceil(h, w): return math.ceil(((h * w) ** 0.5) / 64.0) * 64.0 def get_image_shape_ceil(im): H, W = im.shape[:2] return get_shape_ceil(H, W) def set_image_shape_ceil(im, shape_ceil): shape_ceil = float(shape_ceil) H_origin, W_origin, _ = im.shape H, W = H_origin, W_origin for _ in range(256): current_shape_ceil = get_shape_ceil(H, W) if abs(current_shape_ceil - shape_ceil) < 0.1: break k = shape_ceil / current_shape_ceil H = int(round(float(H) * k / 64.0) * 64) W = int(round(float(W) * k / 64.0) * 64) if H == H_origin and W == W_origin: return im return resample_image(im, width=W, height=H) def HWC3(x): assert x.dtype == np.uint8 if x.ndim == 2: x = x[:, :, None] assert x.ndim == 3 H, W, C = x.shape assert C == 1 or C == 3 or C == 4 if C == 3: return x if C == 1: return np.concatenate([x, x, x], axis=2) if C == 4: color = x[:, :, 0:3].astype(np.float32) alpha = x[:, :, 3:4].astype(np.float32) / 255.0 y = color * alpha + 255.0 * (1.0 - alpha) y = y.clip(0, 255).astype(np.uint8) return y def remove_empty_str(items, default=None): items = [x for x in items if x != ""] if len(items) == 0 and default is not None: return [default] return items def join_prompts(*args, **kwargs): prompts = [str(x) for x in args if str(x) != ""] if len(prompts) == 0: return "" if len(prompts) == 1: return prompts[0] return ', '.join(prompts) def generate_temp_filename(folder='./outputs/', extension='png'): current_time = datetime.datetime.now() date_string = current_time.strftime("%Y-%m-%d") time_string = current_time.strftime("%Y-%m-%d_%H-%M-%S") random_number = random.randint(1000, 9999) filename = f"{time_string}_{random_number}.{extension}" result = os.path.join(folder, date_string, filename) return date_string, os.path.abspath(result), filename def sha256(filename, use_addnet_hash=False, length=HASH_SHA256_LENGTH): if use_addnet_hash: with open(filename, "rb") as file: sha256_value = addnet_hash_safetensors(file) else: sha256_value = calculate_sha256(filename) return sha256_value[:length] if length is not None else sha256_value def addnet_hash_safetensors(b): hash_sha256 = hashlib.sha256() blksize = 1024 * 1024 b.seek(0) header = b.read(8) n = int.from_bytes(header, "little") offset = n + 8 b.seek(offset) for chunk in iter(lambda: b.read(blksize), b""): hash_sha256.update(chunk) return hash_sha256.hexdigest() def calculate_sha256(filename) -> str: hash_sha256 = hashlib.sha256() blksize = 1024 * 1024 with open(filename, "rb") as f: for chunk in iter(lambda: f.read(blksize), b""): hash_sha256.update(chunk) return hash_sha256.hexdigest() def quote(text): if ',' not in str(text) and '\n' not in str(text) and ':' not in str(text): return text return json.dumps(text, ensure_ascii=False) def unquote(text): if len(text) == 0 or text[0] != '"' or text[-1] != '"': return text try: return json.loads(text) except Exception: return text def unwrap_style_text_from_prompt(style_text, prompt): stripped_prompt = prompt stripped_style_text = style_text if "{prompt}" in stripped_style_text: # Work out whether the prompt is wrapped in the style text. If so, we # return True and the "inner" prompt text that isn't part of the style. try: left, right = stripped_style_text.split("{prompt}", 2) except ValueError as e: # If the style text has multple "{prompt}"s, we can't split it into # two parts. This is an error, but we can't do anything about it. print(f"Unable to compare style text to prompt:\n{style_text}") print(f"Error: {e}") return False, prompt, '' left_pos = stripped_prompt.find(left) right_pos = stripped_prompt.find(right) if 0 <= left_pos < right_pos: real_prompt = stripped_prompt[left_pos + len(left):right_pos] prompt = stripped_prompt.replace(left + real_prompt + right, '', 1) if prompt.startswith(", "): prompt = prompt[2:] if prompt.endswith(", "): prompt = prompt[:-2] return True, prompt, real_prompt else: # Work out whether the given prompt starts with the style text. If so, we # return True and the prompt text up to where the style text starts. if stripped_prompt.endswith(stripped_style_text): prompt = stripped_prompt[: len(stripped_prompt) - len(stripped_style_text)] if prompt.endswith(", "): prompt = prompt[:-2] return True, prompt, prompt return False, prompt, '' def extract_original_prompts(style, prompt, negative_prompt): if not style.prompt and not style.negative_prompt: return False, prompt, negative_prompt match_positive, extracted_positive, real_prompt = unwrap_style_text_from_prompt( style.prompt, prompt ) if not match_positive: return False, prompt, negative_prompt, '' match_negative, extracted_negative, _ = unwrap_style_text_from_prompt( style.negative_prompt, negative_prompt ) if not match_negative: return False, prompt, negative_prompt, '' return True, extracted_positive, extracted_negative, real_prompt def extract_styles_from_prompt(prompt, negative_prompt): extracted = [] applicable_styles = [] for style_name, (style_prompt, style_negative_prompt) in modules.sdxl_styles.styles.items(): applicable_styles.append(PromptStyle(name=style_name, prompt=style_prompt, negative_prompt=style_negative_prompt)) real_prompt = '' while True: found_style = None for style in applicable_styles: is_match, new_prompt, new_neg_prompt, new_real_prompt = extract_original_prompts( style, prompt, negative_prompt ) if is_match: found_style = style prompt = new_prompt negative_prompt = new_neg_prompt if real_prompt == '' and new_real_prompt != '' and new_real_prompt != prompt: real_prompt = new_real_prompt break if not found_style: break applicable_styles.remove(found_style) extracted.append(found_style.name) # add prompt expansion if not all styles could be resolved if prompt != '': if real_prompt != '': extracted.append(modules.sdxl_styles.fooocus_expansion) else: # find real_prompt when only prompt expansion is selected first_word = prompt.split(', ')[0] first_word_positions = [i for i in range(len(prompt)) if prompt.startswith(first_word, i)] if len(first_word_positions) > 1: real_prompt = prompt[:first_word_positions[-1]] extracted.append(modules.sdxl_styles.fooocus_expansion) if real_prompt.endswith(', '): real_prompt = real_prompt[:-2] return list(reversed(extracted)), real_prompt, negative_prompt class PromptStyle(NamedTuple): name: str prompt: str negative_prompt: str def is_json(data: str) -> bool: try: loaded_json = json.loads(data) assert isinstance(loaded_json, dict) except (ValueError, AssertionError): return False return True def get_filname_by_stem(lora_name, filenames: List[str]) -> str | None: for filename in filenames: path = Path(filename) if lora_name == path.stem: return filename return None def get_file_from_folder_list(name, folders): if not isinstance(folders, list): folders = [folders] for folder in folders: filename = os.path.abspath(os.path.realpath(os.path.join(folder, name))) if os.path.isfile(filename): return filename return os.path.abspath(os.path.realpath(os.path.join(folders[0], name))) def get_enabled_loras(loras: list, remove_none=True) -> list: return [(lora[1], lora[2]) for lora in loras if lora[0] and (lora[1] != 'None' if remove_none else True)] def parse_lora_references_from_prompt(prompt: str, loras: List[Tuple[AnyStr, float]], loras_limit: int = 5, skip_file_check=False, prompt_cleanup=True, deduplicate_loras=True, lora_filenames=None) -> tuple[List[Tuple[AnyStr, float]], str]: # prevent unintended side effects when returning without detection loras = loras.copy() if lora_filenames is None: lora_filenames = [] found_loras = [] prompt_without_loras = '' cleaned_prompt = '' for token in prompt.split(','): matches = LORAS_PROMPT_PATTERN.findall(token) if len(matches) == 0: prompt_without_loras += token + ', ' continue for match in matches: lora_name = match[1] + '.safetensors' if not skip_file_check: lora_name = get_filname_by_stem(match[1], lora_filenames) if lora_name is not None: found_loras.append((lora_name, float(match[2]))) token = token.replace(match[0], '') prompt_without_loras += token + ', ' if prompt_without_loras != '': cleaned_prompt = prompt_without_loras[:-2] if prompt_cleanup: cleaned_prompt = cleanup_prompt(prompt_without_loras) new_loras = [] lora_names = [lora[0] for lora in loras] for found_lora in found_loras: if deduplicate_loras and (found_lora[0] in lora_names or found_lora in new_loras): continue new_loras.append(found_lora) if len(new_loras) == 0: return loras, cleaned_prompt updated_loras = [] for lora in loras + new_loras: if lora[0] != "None": updated_loras.append(lora) return updated_loras[:loras_limit], cleaned_prompt def remove_performance_lora(filenames: list, performance: Performance | None): loras_without_performance = filenames.copy() if performance is None: return loras_without_performance performance_lora = performance.lora_filename() for filename in filenames: path = Path(filename) if performance_lora == path.name: loras_without_performance.remove(filename) return loras_without_performance def cleanup_prompt(prompt): prompt = re.sub(' +', ' ', prompt) prompt = re.sub(',+', ',', prompt) cleaned_prompt = '' for token in prompt.split(','): token = token.strip() if token == '': continue cleaned_prompt += token + ', ' return cleaned_prompt[:-2] def apply_wildcards(wildcard_text, rng, i, read_wildcards_in_order) -> str: for _ in range(modules.config.wildcards_max_bfs_depth): placeholders = re.findall(r'__([\w-]+)__', wildcard_text) if len(placeholders) == 0: return wildcard_text print(f'[Wildcards] processing: {wildcard_text}') for placeholder in placeholders: try: matches = [x for x in modules.config.wildcard_filenames if os.path.splitext(os.path.basename(x))[0] == placeholder] words = open(os.path.join(modules.config.path_wildcards, matches[0]), encoding='utf-8').read().splitlines() words = [x for x in words if x != ''] assert len(words) > 0 if read_wildcards_in_order: wildcard_text = wildcard_text.replace(f'__{placeholder}__', words[i % len(words)], 1) else: wildcard_text = wildcard_text.replace(f'__{placeholder}__', rng.choice(words), 1) except: print(f'[Wildcards] Warning: {placeholder}.txt missing or empty. ' f'Using "{placeholder}" as a normal word.') wildcard_text = wildcard_text.replace(f'__{placeholder}__', placeholder) print(f'[Wildcards] {wildcard_text}') print(f'[Wildcards] BFS stack overflow. Current text: {wildcard_text}') return wildcard_text def get_image_size_info(image: np.ndarray, aspect_ratios: list) -> str: try: image = Image.fromarray(np.uint8(image)) width, height = image.size ratio = round(width / height, 2) gcd = math.gcd(width, height) lcm_ratio = f'{width // gcd}:{height // gcd}' size_info = f'Image Size: {width} x {height}, Ratio: {ratio}, {lcm_ratio}' closest_ratio = min(aspect_ratios, key=lambda x: abs(ratio - float(x.split('*')[0]) / float(x.split('*')[1]))) recommended_width, recommended_height = map(int, closest_ratio.split('*')) recommended_ratio = round(recommended_width / recommended_height, 2) recommended_gcd = math.gcd(recommended_width, recommended_height) recommended_lcm_ratio = f'{recommended_width // recommended_gcd}:{recommended_height // recommended_gcd}' size_info = f'{width} x {height}, {ratio}, {lcm_ratio}' size_info += f'\n{recommended_width} x {recommended_height}, {recommended_ratio}, {recommended_lcm_ratio}' return size_info except Exception as e: return f'Error reading image: {e}'
--- +++ @@ -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. + 1: Resize the image to fill the specified width and height, maintaining the aspect ratio, and then center the image within the dimensions, cropping the excess. + 2: Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image within the dimensions, filling empty with data from image. + im: The image to resize. + width: The width to resize the image to. + height: The height to resize the image to. + """ im = Image.fromarray(im) @@ -174,6 +186,7 @@ def addnet_hash_safetensors(b): + """kohya-ss hash for safetensors from https://github.com/kohya-ss/sd-scripts/blob/main/library/train_util.py""" hash_sha256 = hashlib.sha256() blksize = 1024 * 1024 @@ -218,6 +231,14 @@ def unwrap_style_text_from_prompt(style_text, prompt): + """ + Checks the prompt to see if the style text is wrapped around it. If so, + returns True plus the prompt text without the style text. Otherwise, returns + False with the original prompt. + + Note that the "cleaned" version of the style text is only used for matching + purposes here. It isn't returned; the original style text is not modified. + """ stripped_prompt = prompt stripped_style_text = style_text if "{prompt}" in stripped_style_text: @@ -255,6 +276,11 @@ def extract_original_prompts(style, prompt, negative_prompt): + """ + Takes a style and compares it to the prompt and negative prompt. If the style + matches, returns True plus the prompt and negative prompt with the style text + removed. Otherwise, returns False with the original prompt and negative prompt. + """ if not style.prompt and not style.negative_prompt: return False, prompt, negative_prompt @@ -486,4 +512,4 @@ return size_info except Exception as e: - return f'Error reading image: {e}'+ return f'Error reading image: {e}'
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, list): module_list = [module_list] for module in module_list: for m in module.modules(): if isinstance(m, nn.Conv2d): init.kaiming_normal_(m.weight, **kwargs) m.weight.data *= scale if m.bias is not None: m.bias.data.fill_(bias_fill) elif isinstance(m, nn.Linear): init.kaiming_normal_(m.weight, **kwargs) m.weight.data *= scale if m.bias is not None: m.bias.data.fill_(bias_fill) elif isinstance(m, _BatchNorm): init.constant_(m.weight, 1) if m.bias is not None: m.bias.data.fill_(bias_fill) class NormStyleCode(nn.Module): def forward(self, x): return x * torch.rsqrt(torch.mean(x**2, dim=1, keepdim=True) + 1e-8) class ModulatedConv2d(nn.Module): def __init__( self, in_channels, out_channels, kernel_size, num_style_feat, demodulate=True, sample_mode=None, eps=1e-8, ): super(ModulatedConv2d, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.demodulate = demodulate self.sample_mode = sample_mode self.eps = eps # modulation inside each modulated conv self.modulation = nn.Linear(num_style_feat, in_channels, bias=True) # initialization default_init_weights( self.modulation, scale=1, bias_fill=1, a=0, mode="fan_in", nonlinearity="linear", ) self.weight = nn.Parameter( torch.randn(1, out_channels, in_channels, kernel_size, kernel_size) / math.sqrt(in_channels * kernel_size**2) ) self.padding = kernel_size // 2 def forward(self, x, style): b, c, h, w = x.shape # c = c_in # weight modulation style = self.modulation(style).view(b, 1, c, 1, 1) # self.weight: (1, c_out, c_in, k, k); style: (b, 1, c, 1, 1) weight = self.weight * style # (b, c_out, c_in, k, k) if self.demodulate: demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + self.eps) weight = weight * demod.view(b, self.out_channels, 1, 1, 1) weight = weight.view( b * self.out_channels, c, self.kernel_size, self.kernel_size ) # upsample or downsample if necessary if self.sample_mode == "upsample": x = F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=False) elif self.sample_mode == "downsample": x = F.interpolate(x, scale_factor=0.5, mode="bilinear", align_corners=False) b, c, h, w = x.shape x = x.view(1, b * c, h, w) # weight: (b*c_out, c_in, k, k), groups=b out = F.conv2d(x, weight, padding=self.padding, groups=b) out = out.view(b, self.out_channels, *out.shape[2:4]) return out def __repr__(self): return ( f"{self.__class__.__name__}(in_channels={self.in_channels}, out_channels={self.out_channels}, " f"kernel_size={self.kernel_size}, demodulate={self.demodulate}, sample_mode={self.sample_mode})" ) class StyleConv(nn.Module): def __init__( self, in_channels, out_channels, kernel_size, num_style_feat, demodulate=True, sample_mode=None, ): super(StyleConv, self).__init__() self.modulated_conv = ModulatedConv2d( in_channels, out_channels, kernel_size, num_style_feat, demodulate=demodulate, sample_mode=sample_mode, ) self.weight = nn.Parameter(torch.zeros(1)) # for noise injection self.bias = nn.Parameter(torch.zeros(1, out_channels, 1, 1)) self.activate = nn.LeakyReLU(negative_slope=0.2, inplace=True) def forward(self, x, style, noise=None): # modulate out = self.modulated_conv(x, style) * 2**0.5 # for conversion # noise injection if noise is None: b, _, h, w = out.shape noise = out.new_empty(b, 1, h, w).normal_() out = out + self.weight * noise # add bias out = out + self.bias # activation out = self.activate(out) return out class ToRGB(nn.Module): def __init__(self, in_channels, num_style_feat, upsample=True): super(ToRGB, self).__init__() self.upsample = upsample self.modulated_conv = ModulatedConv2d( in_channels, 3, kernel_size=1, num_style_feat=num_style_feat, demodulate=False, sample_mode=None, ) self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1)) def forward(self, x, style, skip=None): out = self.modulated_conv(x, style) out = out + self.bias if skip is not None: if self.upsample: skip = F.interpolate( skip, scale_factor=2, mode="bilinear", align_corners=False ) out = out + skip return out class ConstantInput(nn.Module): def __init__(self, num_channel, size): super(ConstantInput, self).__init__() self.weight = nn.Parameter(torch.randn(1, num_channel, size, size)) def forward(self, batch): out = self.weight.repeat(batch, 1, 1, 1) return out class StyleGAN2GeneratorClean(nn.Module): def __init__( self, out_size, num_style_feat=512, num_mlp=8, channel_multiplier=2, narrow=1 ): super(StyleGAN2GeneratorClean, self).__init__() # Style MLP layers self.num_style_feat = num_style_feat style_mlp_layers = [NormStyleCode()] for i in range(num_mlp): style_mlp_layers.extend( [ nn.Linear(num_style_feat, num_style_feat, bias=True), nn.LeakyReLU(negative_slope=0.2, inplace=True), ] ) self.style_mlp = nn.Sequential(*style_mlp_layers) # initialization default_init_weights( self.style_mlp, scale=1, bias_fill=0, a=0.2, mode="fan_in", nonlinearity="leaky_relu", ) # channel list channels = { "4": int(512 * narrow), "8": int(512 * narrow), "16": int(512 * narrow), "32": int(512 * narrow), "64": int(256 * channel_multiplier * narrow), "128": int(128 * channel_multiplier * narrow), "256": int(64 * channel_multiplier * narrow), "512": int(32 * channel_multiplier * narrow), "1024": int(16 * channel_multiplier * narrow), } self.channels = channels self.constant_input = ConstantInput(channels["4"], size=4) self.style_conv1 = StyleConv( channels["4"], channels["4"], kernel_size=3, num_style_feat=num_style_feat, demodulate=True, sample_mode=None, ) self.to_rgb1 = ToRGB(channels["4"], num_style_feat, upsample=False) self.log_size = int(math.log(out_size, 2)) self.num_layers = (self.log_size - 2) * 2 + 1 self.num_latent = self.log_size * 2 - 2 self.style_convs = nn.ModuleList() self.to_rgbs = nn.ModuleList() self.noises = nn.Module() in_channels = channels["4"] # noise for layer_idx in range(self.num_layers): resolution = 2 ** ((layer_idx + 5) // 2) shape = [1, 1, resolution, resolution] self.noises.register_buffer(f"noise{layer_idx}", torch.randn(*shape)) # style convs and to_rgbs for i in range(3, self.log_size + 1): out_channels = channels[f"{2**i}"] self.style_convs.append( StyleConv( in_channels, out_channels, kernel_size=3, num_style_feat=num_style_feat, demodulate=True, sample_mode="upsample", ) ) self.style_convs.append( StyleConv( out_channels, out_channels, kernel_size=3, num_style_feat=num_style_feat, demodulate=True, sample_mode=None, ) ) self.to_rgbs.append(ToRGB(out_channels, num_style_feat, upsample=True)) in_channels = out_channels def make_noise(self): device = self.constant_input.weight.device noises = [torch.randn(1, 1, 4, 4, device=device)] for i in range(3, self.log_size + 1): for _ in range(2): noises.append(torch.randn(1, 1, 2**i, 2**i, device=device)) return noises def get_latent(self, x): return self.style_mlp(x) def mean_latent(self, num_latent): latent_in = torch.randn( num_latent, self.num_style_feat, device=self.constant_input.weight.device ) latent = self.style_mlp(latent_in).mean(0, keepdim=True) return latent def forward( self, styles, input_is_latent=False, noise=None, randomize_noise=True, truncation=1, truncation_latent=None, inject_index=None, return_latents=False, ): # style codes -> latents with Style MLP layer if not input_is_latent: styles = [self.style_mlp(s) for s in styles] # noises if noise is None: if randomize_noise: noise = [None] * self.num_layers # for each style conv layer else: # use the stored noise noise = [ getattr(self.noises, f"noise{i}") for i in range(self.num_layers) ] # style truncation if truncation < 1: style_truncation = [] for style in styles: style_truncation.append( truncation_latent + truncation * (style - truncation_latent) ) styles = style_truncation # get style latents with injection if len(styles) == 1: inject_index = self.num_latent if styles[0].ndim < 3: # repeat latent code for all the layers latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1) else: # used for encoder with different latent code for each layer latent = styles[0] elif len(styles) == 2: # mixing noises if inject_index is None: inject_index = random.randint(1, self.num_latent - 1) latent1 = styles[0].unsqueeze(1).repeat(1, inject_index, 1) latent2 = ( styles[1].unsqueeze(1).repeat(1, self.num_latent - inject_index, 1) ) latent = torch.cat([latent1, latent2], 1) # main generation out = self.constant_input(latent.shape[0]) out = self.style_conv1(out, latent[:, 0], noise=noise[0]) skip = self.to_rgb1(out, latent[:, 1]) i = 1 for conv1, conv2, noise1, noise2, to_rgb in zip( self.style_convs[::2], self.style_convs[1::2], noise[1::2], noise[2::2], self.to_rgbs, ): out = conv1(out, latent[:, i], noise=noise1) out = conv2(out, latent[:, i + 1], noise=noise2) skip = to_rgb(out, latent[:, i + 2], skip) # feature back to the rgb space i += 2 image = skip if return_latents: return image, latent else: return image, None
--- +++ @@ -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 + blocks. Default: 1. + bias_fill (float): The value to fill bias. Default: 0 + kwargs (dict): Other arguments for initialization function. + """ if not isinstance(module_list, list): module_list = [module_list] for module in module_list: @@ -33,10 +41,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, dim=1, keepdim=True) + 1e-8) class ModulatedConv2d(nn.Module): + """Modulated Conv2d used in StyleGAN2. + There is no bias in ModulatedConv2d. + Args: + in_channels (int): Channel number of the input. + out_channels (int): Channel number of the output. + kernel_size (int): Size of the convolving kernel. + num_style_feat (int): Channel number of style features. + demodulate (bool): Whether to demodulate in the conv layer. Default: True. + sample_mode (str | None): Indicating 'upsample', 'downsample' or None. Default: None. + eps (float): A value added to the denominator for numerical stability. Default: 1e-8. + """ def __init__( self, @@ -75,6 +100,13 @@ self.padding = kernel_size // 2 def forward(self, x, style): + """Forward function. + Args: + x (Tensor): Tensor with shape (b, c, h, w). + style (Tensor): Tensor with shape (b, num_style_feat). + Returns: + Tensor: Modulated tensor after convolution. + """ b, c, h, w = x.shape # c = c_in # weight modulation style = self.modulation(style).view(b, 1, c, 1, 1) @@ -111,6 +143,15 @@ class StyleConv(nn.Module): + """Style conv used in StyleGAN2. + Args: + in_channels (int): Channel number of the input. + out_channels (int): Channel number of the output. + kernel_size (int): Size of the convolving kernel. + num_style_feat (int): Channel number of style features. + demodulate (bool): Whether demodulate in the conv layer. Default: True. + sample_mode (str | None): Indicating 'upsample', 'downsample' or None. Default: None. + """ def __init__( self, @@ -150,6 +191,12 @@ class ToRGB(nn.Module): + """To RGB (image space) from features. + Args: + in_channels (int): Channel number of input. + num_style_feat (int): Channel number of style features. + upsample (bool): Whether to upsample. Default: True. + """ def __init__(self, in_channels, num_style_feat, upsample=True): super(ToRGB, self).__init__() @@ -165,6 +212,14 @@ self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1)) def forward(self, x, style, skip=None): + """Forward function. + Args: + x (Tensor): Feature tensor with shape (b, c, h, w). + style (Tensor): Tensor with shape (b, num_style_feat). + skip (Tensor): Base/skip tensor. Default: None. + Returns: + Tensor: RGB images. + """ out = self.modulated_conv(x, style) out = out + self.bias if skip is not None: @@ -177,6 +232,11 @@ class ConstantInput(nn.Module): + """Constant input. + Args: + num_channel (int): Channel number of constant input. + size (int): Spatial size of constant input. + """ def __init__(self, num_channel, size): super(ConstantInput, self).__init__() @@ -188,6 +248,14 @@ class StyleGAN2GeneratorClean(nn.Module): + """Clean version of StyleGAN2 Generator. + Args: + out_size (int): The spatial size of outputs. + num_style_feat (int): Channel number of style features. Default: 512. + num_mlp (int): Layer number of MLP style layers. Default: 8. + channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2. + narrow (float): Narrow ratio for channels. Default: 1.0. + """ def __init__( self, out_size, num_style_feat=512, num_mlp=8, channel_multiplier=2, narrow=1 @@ -280,6 +348,7 @@ in_channels = out_channels def make_noise(self): + """Make noise for noise injection.""" device = self.constant_input.weight.device noises = [torch.randn(1, 1, 4, 4, device=device)] @@ -310,6 +379,17 @@ inject_index=None, return_latents=False, ): + """Forward function for StyleGAN2GeneratorClean. + Args: + styles (list[Tensor]): Sample codes of styles. + input_is_latent (bool): Whether input is latent style. Default: False. + noise (Tensor | None): Input noise or None. Default: None. + randomize_noise (bool): Randomize noise, used when 'noise' is False. Default: True. + truncation (float): The truncation ratio. Default: 1. + truncation_latent (Tensor | None): The truncation latent tensor. Default: None. + inject_index (int | None): The injection index for mixing noise. Default: None. + return_latents (bool): Whether to return style latents. Default: False. + """ # style codes -> latents with Style MLP layer if not input_is_latent: styles = [self.style_mlp(s) for s in styles] @@ -370,4 +450,4 @@ if return_latents: return image, latent else: - return image, None+ return image, None
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 = beta self.embedding = nn.Embedding(self.n_e, self.e_dim) self.embedding.weight.data.uniform_(-1.0 / self.n_e, 1.0 / self.n_e) def forward(self, z): # reshape z -> (batch, height, width, channel) and flatten z = z.permute(0, 2, 3, 1).contiguous() z_flattened = z.view(-1, self.e_dim) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z d = ( torch.sum(z_flattened**2, dim=1, keepdim=True) + torch.sum(self.embedding.weight**2, dim=1) - 2 * torch.matmul(z_flattened, self.embedding.weight.t()) ) # could possible replace this here # #\start... # find closest encodings min_value, min_encoding_indices = torch.min(d, dim=1) min_encoding_indices = min_encoding_indices.unsqueeze(1) min_encodings = torch.zeros(min_encoding_indices.shape[0], self.n_e).to(z) min_encodings.scatter_(1, min_encoding_indices, 1) # dtype min encodings: torch.float32 # min_encodings shape: torch.Size([2048, 512]) # min_encoding_indices.shape: torch.Size([2048, 1]) # get quantized latent vectors z_q = torch.matmul(min_encodings, self.embedding.weight).view(z.shape) # .........\end # with: # .........\start # min_encoding_indices = torch.argmin(d, dim=1) # z_q = self.embedding(min_encoding_indices) # ......\end......... (TODO) # compute loss for embedding loss = torch.mean((z_q.detach() - z) ** 2) + self.beta * torch.mean( (z_q - z.detach()) ** 2 ) # preserve gradients z_q = z + (z_q - z).detach() # perplexity e_mean = torch.mean(min_encodings, dim=0) perplexity = torch.exp(-torch.sum(e_mean * torch.log(e_mean + 1e-10))) # reshape back to match original input shape z_q = z_q.permute(0, 3, 1, 2).contiguous() return z_q, loss, (perplexity, min_encodings, min_encoding_indices, d) def get_codebook_entry(self, indices, shape): # shape specifying (batch, height, width, channel) # TODO: check for more easy handling with nn.Embedding min_encodings = torch.zeros(indices.shape[0], self.n_e).to(indices) min_encodings.scatter_(1, indices[:, None], 1) # get quantized latent vectors z_q = torch.matmul(min_encodings.float(), self.embedding.weight) if shape is not None: z_q = z_q.view(shape) # reshape back to match original input shape z_q = z_q.permute(0, 3, 1, 2).contiguous() return z_q # pytorch_diffusion + derived encoder decoder def nonlinearity(x): # swish return x * torch.sigmoid(x) def Normalize(in_channels): return torch.nn.GroupNorm( num_groups=32, num_channels=in_channels, eps=1e-6, affine=True ) class Upsample(nn.Module): def __init__(self, in_channels, with_conv): super().__init__() self.with_conv = with_conv if self.with_conv: self.conv = torch.nn.Conv2d( in_channels, in_channels, kernel_size=3, stride=1, padding=1 ) def forward(self, x): x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest") if self.with_conv: x = self.conv(x) return x class Downsample(nn.Module): def __init__(self, in_channels, with_conv): super().__init__() self.with_conv = with_conv if self.with_conv: # no asymmetric padding in torch conv, must do it ourselves self.conv = torch.nn.Conv2d( in_channels, in_channels, kernel_size=3, stride=2, padding=0 ) def forward(self, x): if self.with_conv: pad = (0, 1, 0, 1) x = torch.nn.functional.pad(x, pad, mode="constant", value=0) x = self.conv(x) else: x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2) return x class ResnetBlock(nn.Module): def __init__( self, *, in_channels, out_channels=None, conv_shortcut=False, dropout, temb_channels=512 ): super().__init__() self.in_channels = in_channels out_channels = in_channels if out_channels is None else out_channels self.out_channels = out_channels self.use_conv_shortcut = conv_shortcut self.norm1 = Normalize(in_channels) self.conv1 = torch.nn.Conv2d( in_channels, out_channels, kernel_size=3, stride=1, padding=1 ) if temb_channels > 0: self.temb_proj = torch.nn.Linear(temb_channels, out_channels) self.norm2 = Normalize(out_channels) self.dropout = torch.nn.Dropout(dropout) self.conv2 = torch.nn.Conv2d( out_channels, out_channels, kernel_size=3, stride=1, padding=1 ) if self.in_channels != self.out_channels: if self.use_conv_shortcut: self.conv_shortcut = torch.nn.Conv2d( in_channels, out_channels, kernel_size=3, stride=1, padding=1 ) else: self.nin_shortcut = torch.nn.Conv2d( in_channels, out_channels, kernel_size=1, stride=1, padding=0 ) def forward(self, x, temb): h = x h = self.norm1(h) h = nonlinearity(h) h = self.conv1(h) if temb is not None: h = h + self.temb_proj(nonlinearity(temb))[:, :, None, None] h = self.norm2(h) h = nonlinearity(h) h = self.dropout(h) h = self.conv2(h) if self.in_channels != self.out_channels: if self.use_conv_shortcut: x = self.conv_shortcut(x) else: x = self.nin_shortcut(x) return x + h class MultiHeadAttnBlock(nn.Module): def __init__(self, in_channels, head_size=1): super().__init__() self.in_channels = in_channels self.head_size = head_size self.att_size = in_channels // head_size assert ( in_channels % head_size == 0 ), "The size of head should be divided by the number of channels." self.norm1 = Normalize(in_channels) self.norm2 = Normalize(in_channels) self.q = torch.nn.Conv2d( in_channels, in_channels, kernel_size=1, stride=1, padding=0 ) self.k = torch.nn.Conv2d( in_channels, in_channels, kernel_size=1, stride=1, padding=0 ) self.v = torch.nn.Conv2d( in_channels, in_channels, kernel_size=1, stride=1, padding=0 ) self.proj_out = torch.nn.Conv2d( in_channels, in_channels, kernel_size=1, stride=1, padding=0 ) self.num = 0 def forward(self, x, y=None): h_ = x h_ = self.norm1(h_) if y is None: y = h_ else: y = self.norm2(y) q = self.q(y) k = self.k(h_) v = self.v(h_) # compute attention b, c, h, w = q.shape q = q.reshape(b, self.head_size, self.att_size, h * w) q = q.permute(0, 3, 1, 2) # b, hw, head, att k = k.reshape(b, self.head_size, self.att_size, h * w) k = k.permute(0, 3, 1, 2) v = v.reshape(b, self.head_size, self.att_size, h * w) v = v.permute(0, 3, 1, 2) q = q.transpose(1, 2) v = v.transpose(1, 2) k = k.transpose(1, 2).transpose(2, 3) scale = int(self.att_size) ** (-0.5) q.mul_(scale) w_ = torch.matmul(q, k) w_ = F.softmax(w_, dim=3) w_ = w_.matmul(v) w_ = w_.transpose(1, 2).contiguous() # [b, h*w, head, att] w_ = w_.view(b, h, w, -1) w_ = w_.permute(0, 3, 1, 2) w_ = self.proj_out(w_) return x + w_ class MultiHeadEncoder(nn.Module): def __init__( self, ch, out_ch, ch_mult=(1, 2, 4, 8), num_res_blocks=2, attn_resolutions=(16,), dropout=0.0, resamp_with_conv=True, in_channels=3, resolution=512, z_channels=256, double_z=True, enable_mid=True, head_size=1, **ignore_kwargs ): super().__init__() self.ch = ch self.temb_ch = 0 self.num_resolutions = len(ch_mult) self.num_res_blocks = num_res_blocks self.resolution = resolution self.in_channels = in_channels self.enable_mid = enable_mid # downsampling self.conv_in = torch.nn.Conv2d( in_channels, self.ch, kernel_size=3, stride=1, padding=1 ) curr_res = resolution in_ch_mult = (1,) + tuple(ch_mult) self.down = nn.ModuleList() for i_level in range(self.num_resolutions): block = nn.ModuleList() attn = nn.ModuleList() block_in = ch * in_ch_mult[i_level] block_out = ch * ch_mult[i_level] for i_block in range(self.num_res_blocks): block.append( ResnetBlock( in_channels=block_in, out_channels=block_out, temb_channels=self.temb_ch, dropout=dropout, ) ) block_in = block_out if curr_res in attn_resolutions: attn.append(MultiHeadAttnBlock(block_in, head_size)) down = nn.Module() down.block = block down.attn = attn if i_level != self.num_resolutions - 1: down.downsample = Downsample(block_in, resamp_with_conv) curr_res = curr_res // 2 self.down.append(down) # middle if self.enable_mid: self.mid = nn.Module() self.mid.block_1 = ResnetBlock( in_channels=block_in, out_channels=block_in, temb_channels=self.temb_ch, dropout=dropout, ) self.mid.attn_1 = MultiHeadAttnBlock(block_in, head_size) self.mid.block_2 = ResnetBlock( in_channels=block_in, out_channels=block_in, temb_channels=self.temb_ch, dropout=dropout, ) # end self.norm_out = Normalize(block_in) self.conv_out = torch.nn.Conv2d( block_in, 2 * z_channels if double_z else z_channels, kernel_size=3, stride=1, padding=1, ) def forward(self, x): hs = {} # timestep embedding temb = None # downsampling h = self.conv_in(x) hs["in"] = h for i_level in range(self.num_resolutions): for i_block in range(self.num_res_blocks): h = self.down[i_level].block[i_block](h, temb) if len(self.down[i_level].attn) > 0: h = self.down[i_level].attn[i_block](h) if i_level != self.num_resolutions - 1: # hs.append(h) hs["block_" + str(i_level)] = h h = self.down[i_level].downsample(h) # middle # h = hs[-1] if self.enable_mid: h = self.mid.block_1(h, temb) hs["block_" + str(i_level) + "_atten"] = h h = self.mid.attn_1(h) h = self.mid.block_2(h, temb) hs["mid_atten"] = h # end h = self.norm_out(h) h = nonlinearity(h) h = self.conv_out(h) # hs.append(h) hs["out"] = h return hs class MultiHeadDecoder(nn.Module): def __init__( self, ch, out_ch, ch_mult=(1, 2, 4, 8), num_res_blocks=2, attn_resolutions=(16,), dropout=0.0, resamp_with_conv=True, in_channels=3, resolution=512, z_channels=256, give_pre_end=False, enable_mid=True, head_size=1, **ignorekwargs ): super().__init__() self.ch = ch self.temb_ch = 0 self.num_resolutions = len(ch_mult) self.num_res_blocks = num_res_blocks self.resolution = resolution self.in_channels = in_channels self.give_pre_end = give_pre_end self.enable_mid = enable_mid # compute in_ch_mult, block_in and curr_res at lowest res block_in = ch * ch_mult[self.num_resolutions - 1] curr_res = resolution // 2 ** (self.num_resolutions - 1) self.z_shape = (1, z_channels, curr_res, curr_res) print( "Working with z of shape {} = {} dimensions.".format( self.z_shape, np.prod(self.z_shape) ) ) # z to block_in self.conv_in = torch.nn.Conv2d( z_channels, block_in, kernel_size=3, stride=1, padding=1 ) # middle if self.enable_mid: self.mid = nn.Module() self.mid.block_1 = ResnetBlock( in_channels=block_in, out_channels=block_in, temb_channels=self.temb_ch, dropout=dropout, ) self.mid.attn_1 = MultiHeadAttnBlock(block_in, head_size) self.mid.block_2 = ResnetBlock( in_channels=block_in, out_channels=block_in, temb_channels=self.temb_ch, dropout=dropout, ) # upsampling self.up = nn.ModuleList() for i_level in reversed(range(self.num_resolutions)): block = nn.ModuleList() attn = nn.ModuleList() block_out = ch * ch_mult[i_level] for i_block in range(self.num_res_blocks + 1): block.append( ResnetBlock( in_channels=block_in, out_channels=block_out, temb_channels=self.temb_ch, dropout=dropout, ) ) block_in = block_out if curr_res in attn_resolutions: attn.append(MultiHeadAttnBlock(block_in, head_size)) up = nn.Module() up.block = block up.attn = attn if i_level != 0: up.upsample = Upsample(block_in, resamp_with_conv) curr_res = curr_res * 2 self.up.insert(0, up) # prepend to get consistent order # end self.norm_out = Normalize(block_in) self.conv_out = torch.nn.Conv2d( block_in, out_ch, kernel_size=3, stride=1, padding=1 ) def forward(self, z): # assert z.shape[1:] == self.z_shape[1:] self.last_z_shape = z.shape # timestep embedding temb = None # z to block_in h = self.conv_in(z) # middle if self.enable_mid: h = self.mid.block_1(h, temb) h = self.mid.attn_1(h) h = self.mid.block_2(h, temb) # upsampling for i_level in reversed(range(self.num_resolutions)): for i_block in range(self.num_res_blocks + 1): h = self.up[i_level].block[i_block](h, temb) if len(self.up[i_level].attn) > 0: h = self.up[i_level].attn[i_block](h) if i_level != 0: h = self.up[i_level].upsample(h) # end if self.give_pre_end: return h h = self.norm_out(h) h = nonlinearity(h) h = self.conv_out(h) return h class MultiHeadDecoderTransformer(nn.Module): def __init__( self, ch, out_ch, ch_mult=(1, 2, 4, 8), num_res_blocks=2, attn_resolutions=(16,), dropout=0.0, resamp_with_conv=True, in_channels=3, resolution=512, z_channels=256, give_pre_end=False, enable_mid=True, head_size=1, **ignorekwargs ): super().__init__() self.ch = ch self.temb_ch = 0 self.num_resolutions = len(ch_mult) self.num_res_blocks = num_res_blocks self.resolution = resolution self.in_channels = in_channels self.give_pre_end = give_pre_end self.enable_mid = enable_mid # compute in_ch_mult, block_in and curr_res at lowest res block_in = ch * ch_mult[self.num_resolutions - 1] curr_res = resolution // 2 ** (self.num_resolutions - 1) self.z_shape = (1, z_channels, curr_res, curr_res) print( "Working with z of shape {} = {} dimensions.".format( self.z_shape, np.prod(self.z_shape) ) ) # z to block_in self.conv_in = torch.nn.Conv2d( z_channels, block_in, kernel_size=3, stride=1, padding=1 ) # middle if self.enable_mid: self.mid = nn.Module() self.mid.block_1 = ResnetBlock( in_channels=block_in, out_channels=block_in, temb_channels=self.temb_ch, dropout=dropout, ) self.mid.attn_1 = MultiHeadAttnBlock(block_in, head_size) self.mid.block_2 = ResnetBlock( in_channels=block_in, out_channels=block_in, temb_channels=self.temb_ch, dropout=dropout, ) # upsampling self.up = nn.ModuleList() for i_level in reversed(range(self.num_resolutions)): block = nn.ModuleList() attn = nn.ModuleList() block_out = ch * ch_mult[i_level] for i_block in range(self.num_res_blocks + 1): block.append( ResnetBlock( in_channels=block_in, out_channels=block_out, temb_channels=self.temb_ch, dropout=dropout, ) ) block_in = block_out if curr_res in attn_resolutions: attn.append(MultiHeadAttnBlock(block_in, head_size)) up = nn.Module() up.block = block up.attn = attn if i_level != 0: up.upsample = Upsample(block_in, resamp_with_conv) curr_res = curr_res * 2 self.up.insert(0, up) # prepend to get consistent order # end self.norm_out = Normalize(block_in) self.conv_out = torch.nn.Conv2d( block_in, out_ch, kernel_size=3, stride=1, padding=1 ) def forward(self, z, hs): # assert z.shape[1:] == self.z_shape[1:] # self.last_z_shape = z.shape # timestep embedding temb = None # z to block_in h = self.conv_in(z) # middle if self.enable_mid: h = self.mid.block_1(h, temb) h = self.mid.attn_1(h, hs["mid_atten"]) h = self.mid.block_2(h, temb) # upsampling for i_level in reversed(range(self.num_resolutions)): for i_block in range(self.num_res_blocks + 1): h = self.up[i_level].block[i_block](h, temb) if len(self.up[i_level].attn) > 0: h = self.up[i_level].attn[i_block]( h, hs["block_" + str(i_level) + "_atten"] ) # hfeature = h.clone() if i_level != 0: h = self.up[i_level].upsample(h) # end if self.give_pre_end: return h h = self.norm_out(h) h = nonlinearity(h) h = self.conv_out(h) return h class RestoreFormer(nn.Module): def __init__( self, state_dict, ): super(RestoreFormer, self).__init__() n_embed = 1024 embed_dim = 256 ch = 64 out_ch = 3 ch_mult = (1, 2, 2, 4, 4, 8) num_res_blocks = 2 attn_resolutions = (16,) dropout = 0.0 in_channels = 3 resolution = 512 z_channels = 256 double_z = False enable_mid = True fix_decoder = False fix_codebook = True fix_encoder = False head_size = 8 self.model_arch = "RestoreFormer" self.sub_type = "Face SR" self.scale = 8 self.in_nc = 3 self.out_nc = out_ch self.state = state_dict self.supports_fp16 = False self.supports_bf16 = True self.min_size_restriction = 16 self.encoder = MultiHeadEncoder( ch=ch, out_ch=out_ch, ch_mult=ch_mult, num_res_blocks=num_res_blocks, attn_resolutions=attn_resolutions, dropout=dropout, in_channels=in_channels, resolution=resolution, z_channels=z_channels, double_z=double_z, enable_mid=enable_mid, head_size=head_size, ) self.decoder = MultiHeadDecoderTransformer( ch=ch, out_ch=out_ch, ch_mult=ch_mult, num_res_blocks=num_res_blocks, attn_resolutions=attn_resolutions, dropout=dropout, in_channels=in_channels, resolution=resolution, z_channels=z_channels, enable_mid=enable_mid, head_size=head_size, ) self.quantize = VectorQuantizer(n_embed, embed_dim, beta=0.25) self.quant_conv = torch.nn.Conv2d(z_channels, embed_dim, 1) self.post_quant_conv = torch.nn.Conv2d(embed_dim, z_channels, 1) if fix_decoder: for _, param in self.decoder.named_parameters(): param.requires_grad = False for _, param in self.post_quant_conv.named_parameters(): param.requires_grad = False for _, param in self.quantize.named_parameters(): param.requires_grad = False elif fix_codebook: for _, param in self.quantize.named_parameters(): param.requires_grad = False if fix_encoder: for _, param in self.encoder.named_parameters(): param.requires_grad = False self.load_state_dict(state_dict) def encode(self, x): hs = self.encoder(x) h = self.quant_conv(hs["out"]) quant, emb_loss, info = self.quantize(h) return quant, emb_loss, info, hs def decode(self, quant, hs): quant = self.post_quant_conv(quant) dec = self.decoder(quant, hs) return dec def forward(self, input, **kwargs): quant, diff, info, hs = self.encode(input) dec = self.decode(quant, hs) return dec, None
--- +++ @@ -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/d761a999e2267766400dc646d82d3ac3657771d4/models/quantizer.py + ____________________________________________ + Discretization bottleneck part of the VQ-VAE. + Inputs: + - n_e : number of embeddings + - e_dim : dimension of embedding + - beta : commitment cost used in loss term, beta * ||z_e(x)-sg[e]||^2 + _____________________________________________ + """ def __init__(self, n_e, e_dim, beta): super(VectorQuantizer, self).__init__() @@ -18,6 +30,15 @@ self.embedding.weight.data.uniform_(-1.0 / self.n_e, 1.0 / self.n_e) def forward(self, z): + """ + Inputs the output of the encoder network z and maps it to a discrete + one-hot vector that is the index of the closest embedding vector e_j + z (continuous) -> z_q (discrete) + z.shape = (batch, channel, height, width) + quantization pipeline: + 1. get encoder input (B,C,H,W) + 2. flatten input to (B*H*W,C) + """ # reshape z -> (batch, height, width, channel) and flatten z = z.permute(0, 2, 3, 1).contiguous() z_flattened = z.view(-1, self.e_dim) @@ -752,4 +773,4 @@ quant, diff, info, hs = self.encode(input) dec = self.decode(quant, hs) - return dec, None+ return dec, None
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, convert_openai_messages_to_images, convert_pil_to_base64 ) from modules.logging_colors import logger from modules.utils import resolve_model_path llamacpp_valid_cache_types = {"fp16", "q8_0", "q4_0"} class LlamaServer: def __init__(self, model_path, server_path=None): self.model_path = model_path self.server_path = server_path self.port = self._find_available_port() self.process = None self.session = requests.Session() self.vocabulary_size = None self.n_ctx = None self.bos_token = "<s>" self.last_prompt_token_count = 0 # Start the server self._start_server() def encode(self, text, add_bos_token=False, **kwargs): if self.bos_token and text.startswith(self.bos_token): add_bos_token = False url = f"http://127.0.0.1:{self.port}/tokenize" payload = { "content": text, "add_special": add_bos_token, } response = self.session.post(url, json=payload) result = response.json() return result.get("tokens", []) def decode(self, token_ids, **kwargs): url = f"http://127.0.0.1:{self.port}/detokenize" payload = { "tokens": token_ids, } response = self.session.post(url, json=payload) result = response.json() return result.get("content", "") def prepare_payload(self, state): payload = { "temperature": state["temperature"] if not state["dynamic_temperature"] else (state["dynatemp_low"] + state["dynatemp_high"]) / 2, "dynatemp_range": 0 if not state["dynamic_temperature"] else (state["dynatemp_high"] - state["dynatemp_low"]) / 2, "dynatemp_exponent": state["dynatemp_exponent"], "top_k": state["top_k"], "top_p": state["top_p"], "min_p": state["min_p"], "top_n_sigma": state["top_n_sigma"] if state["top_n_sigma"] > 0 else -1, "adaptive_target": state["adaptive_target"] if state["adaptive_target"] > 0 else -1, "adaptive_decay": state["adaptive_decay"], "typical_p": state["typical_p"], "repeat_penalty": state["repetition_penalty"], "repeat_last_n": state["repetition_penalty_range"], "presence_penalty": state["presence_penalty"], "frequency_penalty": state["frequency_penalty"], "dry_multiplier": state["dry_multiplier"], "dry_base": state["dry_base"], "dry_allowed_length": state["dry_allowed_length"], "dry_penalty_last_n": state["repetition_penalty_range"], "xtc_probability": state["xtc_probability"], "xtc_threshold": state["xtc_threshold"], "mirostat": state["mirostat_mode"], "mirostat_tau": state["mirostat_tau"], "mirostat_eta": state["mirostat_eta"], "grammar": state["grammar_string"], "seed": state["seed"], "ignore_eos": state["ban_eos_token"], } # DRY dry_sequence_breakers = state['dry_sequence_breakers'] if not dry_sequence_breakers.startswith("["): dry_sequence_breakers = "[" + dry_sequence_breakers + "]" dry_sequence_breakers = json.loads(dry_sequence_breakers) payload["dry_sequence_breakers"] = dry_sequence_breakers # Sampler order if state["sampler_priority"]: samplers = state["sampler_priority"] samplers = samplers.split("\n") if isinstance(samplers, str) else samplers filtered_samplers = [] penalty_found = False for s in samplers: if s.strip() in ["dry", "top_k", "top_p", "top_n_sigma", "min_p", "temperature", "xtc"]: filtered_samplers.append(s.strip()) elif s.strip() == "typical_p": filtered_samplers.append("typ_p") elif not penalty_found and s.strip() == "repetition_penalty": filtered_samplers.append("penalties") penalty_found = True # Move temperature to the end if temperature_last is true and temperature exists in the list if state["temperature_last"] and "temperature" in filtered_samplers: filtered_samplers.remove("temperature") filtered_samplers.append("temperature") # adaptive-p replaces the default dist sampler; llama.cpp always # places it at the end of the chain regardless of position, so we # activate it based on the parameter value rather than sampler order. if state.get("adaptive_target", 0) > 0: filtered_samplers.append("adaptive_p") payload["samplers"] = filtered_samplers logit_bias = [] if state['custom_token_bans']: logit_bias.extend([[int(token_id.strip()), False] for token_id in state['custom_token_bans'].split(',') if token_id.strip()]) if state.get('logit_bias'): for token_id_str, bias in state['logit_bias'].items(): logit_bias.append([int(token_id_str), bias]) if logit_bias: payload["logit_bias"] = logit_bias n_probs = state.get('logprobs', 0) if n_probs and n_probs > 0: payload["n_probs"] = n_probs return payload def _process_images_for_generation(self, state: dict) -> List[Any]: pil_images = [] # Source 1: Web UI (from chatbot_wrapper) if 'image_attachments' in state and state['image_attachments']: pil_images.extend(convert_image_attachments_to_pil(state['image_attachments'])) # Source 2: Chat Completions API (/v1/chat/completions) elif 'history' in state and state.get('history', {}).get('messages'): pil_images.extend(convert_openai_messages_to_images(state['history']['messages'])) # Source 3: Legacy Completions API (/v1/completions) elif 'raw_images' in state and state['raw_images']: pil_images.extend(state.get('raw_images', [])) return pil_images def is_multimodal(self) -> bool: return shared.args.mmproj not in [None, 'None'] def generate_with_streaming(self, prompt, state): url = f"http://127.0.0.1:{self.port}/completion" payload = self.prepare_payload(state) pil_images = [] if shared.is_multimodal: pil_images = self._process_images_for_generation(state) if pil_images: # Multimodal case IMAGE_TOKEN_COST_ESTIMATE = 600 # A safe, conservative estimate per image base64_images = [convert_pil_to_base64(img) for img in pil_images] payload["prompt"] = { "prompt_string": prompt, "multimodal_data": base64_images } # Calculate an estimated token count text_tokens = self.encode(prompt, add_bos_token=state["add_bos_token"]) self.last_prompt_token_count = len(text_tokens) + (len(pil_images) * IMAGE_TOKEN_COST_ESTIMATE) else: # Text only case token_ids = self.encode(prompt, add_bos_token=state["add_bos_token"]) self.last_prompt_token_count = len(token_ids) payload["prompt"] = token_ids if state['auto_max_new_tokens']: max_new_tokens = state['truncation_length'] - self.last_prompt_token_count else: max_new_tokens = state['max_new_tokens'] payload.update({ "n_predict": max_new_tokens, "stream": True, "cache_prompt": True }) if shared.args.verbose: logger.info("GENERATE_PARAMS=") printable_payload = {k: v for k, v in payload.items() if k != "prompt"} pprint.PrettyPrinter(indent=4, sort_dicts=False).pprint(printable_payload) print() # Make the generation request response = self.session.post(url, json=payload, stream=True) try: if response.status_code == 400 and response.json().get("error", {}).get("type") == "exceed_context_size_error": logger.error("The request exceeds the available context size, try increasing it") return else: response.raise_for_status() # Raise an exception for HTTP errors full_text = "" self.last_completion_probabilities = [] # Process the streaming response stop_event = state.get('stop_event') for line in response.iter_lines(): if shared.stop_everything or (stop_event and stop_event.is_set()): break if not line: continue try: line = line.decode('utf-8') # Check if the line starts with "data: " and remove it if line.startswith('data: '): line = line[6:] # Remove the "data: " prefix # Parse the JSON data data = json.loads(line) # Extract the token content if data.get('content', ''): full_text += data['content'] yield full_text # Capture logprobs if present if 'completion_probabilities' in data: self.last_completion_probabilities.extend(data['completion_probabilities']) # Check if generation is complete if data.get('stop', False): break except json.JSONDecodeError as e: # Log the error and the problematic line print(f"JSON decode error: {e}") print(f"Problematic line: {line}") continue finally: response.close() def generate(self, prompt, state): output = "" for output in self.generate_with_streaming(prompt, state): pass return output def get_logits(self, prompt, state, n_probs=128, use_samplers=False): url = f"http://127.0.0.1:{self.port}/completion" payload = self.prepare_payload(state) payload.update({ "prompt": self.encode(prompt, add_bos_token=state["add_bos_token"]), "n_predict": 0, "logprobs": True, "n_probs": n_probs, "stream": False, "post_sampling_probs": use_samplers, }) if shared.args.verbose and use_samplers: logger.info("GENERATE_PARAMS=") printable_payload = {k: v for k, v in payload.items() if k != "prompt"} pprint.PrettyPrinter(indent=4, sort_dicts=False).pprint(printable_payload) print() for retry in range(5): response = self.session.post(url, json=payload) result = response.json() if "completion_probabilities" in result: if use_samplers: return result["completion_probabilities"][0]["top_probs"] else: return result["completion_probabilities"][0]["top_logprobs"] time.sleep(0.05) else: raise Exception(f"Unexpected response format: 'completion_probabilities' not found in {result}") def _get_vocabulary_size(self): url = f"http://127.0.0.1:{self.port}/v1/models" response = self.session.get(url).json() if "data" in response and len(response["data"]) > 0: model_info = response["data"][0] if "meta" in model_info and "n_vocab" in model_info["meta"]: self.vocabulary_size = model_info["meta"]["n_vocab"] def _get_bos_token(self): url = f"http://127.0.0.1:{self.port}/props" response = self.session.get(url).json() if "bos_token" in response: self.bos_token = response["bos_token"] # Get actual n_ctx from the server (important when --fit auto-selects it) n_ctx = response.get("default_generation_settings", {}).get("n_ctx") if n_ctx: self.n_ctx = n_ctx def _is_port_available(self, port): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: s.bind(('', port)) return True except OSError: return False def _find_available_port(self): preferred_port = shared.args.api_port + 5 if self._is_port_available(preferred_port): return preferred_port # Fall back to OS-assigned random port with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind(('', 0)) return s.getsockname()[1] def _start_server(self): # Determine the server path if self.server_path is None: self.server_path = llama_cpp_binaries.get_binary_path() # Build the command cmd = [ self.server_path, "--model", self.model_path, "--batch-size", str(shared.args.batch_size), "--ubatch-size", str(shared.args.ubatch_size), "--port", str(self.port), "--no-webui", "--flash-attn", "on", ] if shared.args.ctx_size > 0: cmd += ["--ctx-size", str(shared.args.ctx_size)] elif shared.args.gpu_layers >= 0: cmd += ["--ctx-size", "8192"] if shared.args.gpu_layers >= 0: cmd += ["--gpu-layers", str(shared.args.gpu_layers), "--fit", "off"] else: cmd += ["--fit", "on"] cmd += ["--fit-ctx", "8192"] if shared.args.fit_target: cmd += ["--fit-target", shared.args.fit_target] if shared.args.threads > 0: cmd += ["--threads", str(shared.args.threads)] if shared.args.threads_batch > 0: cmd += ["--threads-batch", str(shared.args.threads_batch)] if shared.args.cpu_moe: cmd.append("--cpu-moe") if shared.args.no_mmap: cmd.append("--no-mmap") if shared.args.mlock: cmd.append("--mlock") if shared.args.tensor_split: cmd += ["--tensor-split", shared.args.tensor_split] if shared.args.numa: cmd += ["--numa", "distribute"] if shared.args.no_kv_offload: cmd.append("--no-kv-offload") if shared.args.row_split: cmd += ["--split-mode", "row"] cache_type = "fp16" if shared.args.cache_type != "fp16" and shared.args.cache_type in llamacpp_valid_cache_types: cmd += ["--cache-type-k", shared.args.cache_type, "--cache-type-v", shared.args.cache_type] cache_type = shared.args.cache_type if shared.args.mmproj not in [None, 'None']: path = Path(shared.args.mmproj) if not path.exists(): path = shared.user_data_dir / 'mmproj' / shared.args.mmproj if path.exists(): cmd += ["--mmproj", str(path)] if shared.args.model_draft not in [None, 'None']: path = resolve_model_path(shared.args.model_draft) if path.is_file(): model_file = path else: model_file = sorted(path.glob('*.gguf'))[0] cmd += ["--model-draft", str(model_file)] if shared.args.draft_max > 0: cmd += ["--draft-max", str(shared.args.draft_max)] if shared.args.gpu_layers_draft > 0: cmd += ["--gpu-layers-draft", str(shared.args.gpu_layers_draft)] if shared.args.device_draft: cmd += ["--device-draft", shared.args.device_draft] if shared.args.ctx_size_draft > 0: cmd += ["--ctx-size-draft", str(shared.args.ctx_size_draft)] if shared.args.spec_type != 'none': cmd += ["--spec-type", shared.args.spec_type] cmd += ["--draft-max", str(shared.args.draft_max)] cmd += ["--spec-ngram-size-n", str(shared.args.spec_ngram_size_n)] cmd += ["--spec-ngram-size-m", str(shared.args.spec_ngram_size_m)] cmd += ["--spec-ngram-min-hits", str(shared.args.spec_ngram_min_hits)] cmd += ["--parallel", str(shared.args.parallel)] if shared.args.streaming_llm: cmd += ["--cache-reuse", "1"] cmd += ["--swa-full"] if shared.args.extra_flags: # Clean up the input extra_flags = shared.args.extra_flags.strip() if extra_flags.startswith('"') and extra_flags.endswith('"'): extra_flags = extra_flags[1:-1].strip() elif extra_flags.startswith("'") and extra_flags.endswith("'"): extra_flags = extra_flags[1:-1].strip() for flag_item in extra_flags.split(','): flag_item = flag_item.strip() if '=' in flag_item: flag, value = flag_item.split('=', 1) flag = flag.strip() value = value.strip() if len(flag) <= 3: cmd += [f"-{flag}", value] else: cmd += [f"--{flag}", value] else: if len(flag_item) <= 3: cmd.append(f"-{flag_item}") else: cmd.append(f"--{flag_item}") env = os.environ.copy() if os.name == 'posix': current_path = env.get('LD_LIBRARY_PATH', '') if current_path: env['LD_LIBRARY_PATH'] = f"{current_path}:{os.path.dirname(self.server_path)}" else: env['LD_LIBRARY_PATH'] = os.path.dirname(self.server_path) if shared.args.verbose: logger.info("llama-server command-line flags:") print(' '.join(str(item) for item in cmd[1:])) print() gpu_layers_str = "auto" if shared.args.gpu_layers < 0 else str(shared.args.gpu_layers) ctx_size_str = "auto" if shared.args.ctx_size == 0 and shared.args.gpu_layers < 0 else str(shared.args.ctx_size or 8192) logger.info(f"Using gpu_layers={gpu_layers_str} | ctx_size={ctx_size_str} | cache_type={cache_type}") # Start the server with pipes for output self.process = subprocess.Popen( cmd, stderr=subprocess.PIPE, bufsize=0, env=env ) threading.Thread(target=filter_stderr_with_progress, args=(self.process.stderr,), daemon=True).start() # Wait for server to be healthy health_url = f"http://127.0.0.1:{self.port}/health" while True: # Check if process is still alive if self.process.poll() is not None: # Process has terminated exit_code = self.process.poll() raise RuntimeError(f"Server process terminated unexpectedly with exit code: {exit_code}") try: response = self.session.get(health_url) if response.status_code == 200: break except Exception: pass time.sleep(1) # Server is now healthy, get model info self._get_vocabulary_size() self._get_bos_token() return self.port def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.stop() def __del__(self): self.stop() def stop(self): if self.process: self.process.terminate() try: self.process.wait(timeout=5) except subprocess.TimeoutExpired: self.process.kill() self.process.wait(timeout=5) self.process = None def filter_stderr_with_progress(process_stderr): progress_re = re.compile(r'slot update_slots: id.*progress = (\d+\.\d+)') ansi_re = re.compile(r'\x1b\[[0-9;]*[a-zA-Z]') log_prefix_re = re.compile(r'^[IWED] ') last_was_progress = False try: # Read in binary mode and decode manually buffer = b"" while True: # Read chunks aggressively to prevent buffer overflow chunk = process_stderr.read(4096) if not chunk: break buffer += chunk # Process complete lines while b'\n' in buffer: line_bytes, buffer = buffer.split(b'\n', 1) try: line = line_bytes.decode('utf-8', errors='replace').strip('\r\n') line = log_prefix_re.sub('', ansi_re.sub('', line)) if line: # Process non-empty lines match = progress_re.search(line) if match: progress = float(match.group(1)) # Extract just the part from "prompt processing" onwards prompt_processing_idx = line.find('prompt processing') if prompt_processing_idx != -1: display_line = line[prompt_processing_idx:] else: display_line = line # fallback to full line # choose carriage return for in-progress or newline at completion end_char = '\r' if progress < 1.0 else '\n' print(display_line, end=end_char, file=sys.stderr, flush=True) last_was_progress = (progress < 1.0) # skip noise lines elif not (line.startswith(('srv ', 'slot ')) or 'log_server_r: request: GET /health' in line or 'No parser definition detected' in line): # if we were in progress, finish that line first if last_was_progress: print(file=sys.stderr) print(line, file=sys.stderr, flush=True) last_was_progress = False except Exception: continue except (ValueError, IOError): pass finally: try: process_stderr.close() except Exception: pass
--- +++ @@ -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() @@ -149,6 +152,9 @@ return payload def _process_images_for_generation(self, state: dict) -> List[Any]: + """ + Process all possible image inputs and return PIL images + """ pil_images = [] # Source 1: Web UI (from chatbot_wrapper) if 'image_attachments' in state and state['image_attachments']: @@ -163,6 +169,7 @@ return pil_images def is_multimodal(self) -> bool: + """Check if this model supports multimodal input.""" return shared.args.mmproj not in [None, 'None'] def generate_with_streaming(self, prompt, state): @@ -270,6 +277,7 @@ return output def get_logits(self, prompt, state, n_probs=128, use_samplers=False): + """Get the logits/probabilities for the next token after a prompt""" url = f"http://127.0.0.1:{self.port}/completion" payload = self.prepare_payload(state) @@ -303,6 +311,7 @@ raise Exception(f"Unexpected response format: 'completion_probabilities' not found in {result}") def _get_vocabulary_size(self): + """Get and store the model's maximum context length.""" url = f"http://127.0.0.1:{self.port}/v1/models" response = self.session.get(url).json() @@ -312,6 +321,7 @@ self.vocabulary_size = model_info["meta"]["n_vocab"] def _get_bos_token(self): + """Get and store the model's BOS token and context size.""" url = f"http://127.0.0.1:{self.port}/props" response = self.session.get(url).json() if "bos_token" in response: @@ -323,6 +333,7 @@ self.n_ctx = n_ctx def _is_port_available(self, port): + """Check if a port is available for use.""" with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: s.bind(('', port)) @@ -331,6 +342,7 @@ return False def _find_available_port(self): + """Find an available port, preferring main port + 5.""" preferred_port = shared.args.api_port + 5 if self._is_port_available(preferred_port): return preferred_port @@ -341,6 +353,7 @@ return s.getsockname()[1] def _start_server(self): + """Start the llama.cpp server and wait until it's ready.""" # Determine the server path if self.server_path is None: self.server_path = llama_cpp_binaries.get_binary_path() @@ -499,15 +512,19 @@ return self.port def __enter__(self): + """Support for context manager.""" return self def __exit__(self, exc_type, exc_val, exc_tb): + """Support for context manager.""" self.stop() def __del__(self): + """Cleanup when the object is deleted.""" self.stop() def stop(self): + """Stop the server process.""" if self.process: self.process.terminate() try: @@ -520,6 +537,10 @@ def filter_stderr_with_progress(process_stderr): + """ + Reads stderr lines from a process, filters out noise, and displays progress updates + inline (overwriting the same line) until completion. + """ progress_re = re.compile(r'slot update_slots: id.*progress = (\d+\.\d+)') ansi_re = re.compile(r'\x1b\[[0-9;]*[a-zA-Z]') log_prefix_re = re.compile(r'^[IWED] ') @@ -578,4 +599,4 @@ try: process_stderr.close() except Exception: - pass+ pass
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_profiling_mode(False) # parameters which can be customized in settings.json of webui params = { 'address': 'http://127.0.0.1:7860', 'mode': 0, # modes of operation: 0 (Manual only), 1 (Immersive/Interactive - looks for words to trigger), 2 (Picturebook Adventure - Always on) 'manage_VRAM': False, 'save_img': False, 'SD_model': 'NeverEndingDream', # not used right now 'prompt_prefix': '(Masterpiece:1.1), detailed, intricate, colorful', 'negative_prompt': '(worst quality, low quality:1.3)', 'width': 512, 'height': 512, 'denoising_strength': 0.61, 'restore_faces': False, 'enable_hr': False, 'hr_upscaler': 'ESRGAN_4x', 'hr_scale': '1.0', 'seed': -1, 'sampler_name': 'DPM++ 2M', 'steps': 32, 'cfg_scale': 7, 'textgen_prefix': 'Please provide a detailed and vivid description of [subject]', 'sd_checkpoint': ' ', 'checkpoint_list': [" "], 'last_model': "" } def give_VRAM_priority(actor): global shared, params if actor == 'SD': params["last_model"] = shared.model_name unload_model() print("Requesting Auto1111 to re-load last checkpoint used...") response = requests.post(url=f'{params["address"]}/sdapi/v1/reload-checkpoint', json='') response.raise_for_status() elif actor == 'LLM': print("Requesting Auto1111 to vacate VRAM...") response = requests.post(url=f'{params["address"]}/sdapi/v1/unload-checkpoint', json='') response.raise_for_status() if params["last_model"]: shared.model, shared.tokenizer = load_model(params["last_model"]) elif actor == 'set': print("VRAM mangement activated -- requesting Auto1111 to vacate VRAM...") response = requests.post(url=f'{params["address"]}/sdapi/v1/unload-checkpoint', json='') response.raise_for_status() elif actor == 'reset': print("VRAM mangement deactivated -- requesting Auto1111 to reload checkpoint") response = requests.post(url=f'{params["address"]}/sdapi/v1/reload-checkpoint', json='') response.raise_for_status() else: raise RuntimeError(f'Managing VRAM: "{actor}" is not a known state!') response.raise_for_status() del response if params['manage_VRAM']: give_VRAM_priority('set') SD_models = ['NeverEndingDream'] # TODO: get with http://{address}}/sdapi/v1/sd-models and allow user to select picture_response = False # specifies if the next model response should appear as a picture def remove_surrounded_chars(string): # this expression matches to 'as few symbols as possible (0 upwards) between any asterisks' OR # 'as few symbols as possible (0 upwards) between an asterisk and the end of the string' return re.sub('\*[^\*]*?(\*|$)', '', string) def triggers_are_in(string): string = remove_surrounded_chars(string) # regex searches for send|main|message|me (at the end of the word) followed by # a whole word of image|pic|picture|photo|snap|snapshot|selfie|meme(s), # (?aims) are regex parser flags return bool(re.search('(?aims)(send|mail|message|me)\\b.+?\\b(image|pic(ture)?|photo|snap(shot)?|selfie|meme)s?\\b', string)) def state_modifier(state): if picture_response: state['stream'] = False return state def input_modifier(string): global params if not params['mode'] == 1: # if not in immersive/interactive mode, do nothing return string if triggers_are_in(string): # if we're in it, check for trigger words toggle_generation(True) string = string.lower() if "of" in string: subject = string.split('of', 1)[1] # subdivide the string once by the first 'of' instance and get what's coming after it string = params['textgen_prefix'].replace("[subject]", subject) else: string = params['textgen_prefix'].replace("[subject]", "your appearance, your surroundings and what you are doing right now") return string # Get and save the Stable Diffusion-generated picture def get_SD_pictures(description, character): global params if params['manage_VRAM']: give_VRAM_priority('SD') description = re.sub('<audio.*?</audio>', ' ', description) description = f"({description}:1)" payload = { "prompt": params['prompt_prefix'] + description, "seed": params['seed'], "sampler_name": params['sampler_name'], "enable_hr": params['enable_hr'], "hr_scale": params['hr_scale'], "hr_upscaler": params['hr_upscaler'], "denoising_strength": params['denoising_strength'], "steps": params['steps'], "cfg_scale": params['cfg_scale'], "width": params['width'], "height": params['height'], "restore_faces": params['restore_faces'], "override_settings_restore_afterwards": True, "negative_prompt": params['negative_prompt'] } print(f'Prompting the image generator via the API on {params["address"]}...') response = requests.post(url=f'{params["address"]}/sdapi/v1/txt2img', json=payload) response.raise_for_status() r = response.json() visible_result = "" for img_str in r['images']: if params['save_img']: img_data = base64.b64decode(img_str) variadic = f'{date.today().strftime("%Y_%m_%d")}/{character}_{int(time.time())}' output_file = Path(f'extensions/sd_api_pictures/outputs/{variadic}.png') output_file.parent.mkdir(parents=True, exist_ok=True) with open(output_file.as_posix(), 'wb') as f: f.write(img_data) visible_result = visible_result + f'<img src="/file/extensions/sd_api_pictures/outputs/{variadic}.png" alt="{description}" style="max-width: unset; max-height: unset;">\n' else: image = Image.open(io.BytesIO(base64.b64decode(img_str.split(",", 1)[0]))) # lower the resolution of received images for the chat, otherwise the log size gets out of control quickly with all the base64 values in visible history image.thumbnail((300, 300)) buffered = io.BytesIO() image.save(buffered, format="JPEG") buffered.seek(0) image_bytes = buffered.getvalue() img_str = "data:image/jpeg;base64," + base64.b64encode(image_bytes).decode() visible_result = visible_result + f'<img src="{img_str}" alt="{description}">\n' if params['manage_VRAM']: give_VRAM_priority('LLM') return visible_result # TODO: how do I make the UI history ignore the resulting pictures (I don't want HTML to appear in history) # and replace it with 'text' for the purposes of logging? def output_modifier(string, state): global picture_response, params if not picture_response: return string string = remove_surrounded_chars(string) string = string.replace('"', '') string = string.replace('“', '') string = string.replace('\n', ' ') string = string.strip() if string == '': string = 'no viable description in reply, try regenerating' return string text = "" if (params['mode'] < 2): toggle_generation(False) text = f'*Sends a picture which portrays: “{string}”*' else: text = string string = get_SD_pictures(string, state['character_menu']) + "\n" + text return string def bot_prefix_modifier(string): return string def toggle_generation(*args): global picture_response, shared if not args: picture_response = not picture_response else: picture_response = args[0] shared.processing_message = "*Is sending a picture...*" if picture_response else "*Is typing...*" def filter_address(address): address = address.strip() # address = re.sub('http(s)?:\/\/|\/$','',address) # remove starting http:// OR https:// OR trailing slash address = re.sub('\/$', '', address) # remove trailing /s if not address.startswith('http'): address = 'http://' + address return address def SD_api_address_update(address): global params msg = "✔️ SD API is found on:" address = filter_address(address) params.update({"address": address}) try: response = requests.get(url=f'{params["address"]}/sdapi/v1/sd-models') response.raise_for_status() # r = response.json() except Exception: msg = "❌ No SD API endpoint on:" return gr.Textbox.update(label=msg) def custom_css(): path_to_css = Path(__file__).parent.resolve() / 'style.css' return open(path_to_css, 'r').read() def get_checkpoints(): global params try: models = requests.get(url=f'{params["address"]}/sdapi/v1/sd-models') options = requests.get(url=f'{params["address"]}/sdapi/v1/options') options_json = options.json() params['sd_checkpoint'] = options_json['sd_model_checkpoint'] params['checkpoint_list'] = [result["title"] for result in models.json()] except Exception: params['sd_checkpoint'] = "" params['checkpoint_list'] = [] return gr.update(choices=params['checkpoint_list'], value=params['sd_checkpoint']) def load_checkpoint(checkpoint): payload = { "sd_model_checkpoint": checkpoint } try: requests.post(url=f'{params["address"]}/sdapi/v1/options', json=payload) except Exception: pass def get_samplers(): try: response = requests.get(url=f'{params["address"]}/sdapi/v1/samplers') response.raise_for_status() samplers = [x["name"] for x in response.json()] except Exception: samplers = [] return samplers def ui(): # Gradio elements # gr.Markdown('### Stable Diffusion API Pictures') # Currently the name of extension is shown as the title with gr.Accordion("Parameters", open=True, elem_classes="SDAP"): with gr.Row(): address = gr.Textbox(placeholder=params['address'], value=params['address'], label='Auto1111\'s WebUI address') modes_list = ["Manual", "Immersive/Interactive", "Picturebook/Adventure"] mode = gr.Dropdown(modes_list, value=modes_list[params['mode']], label="Mode of operation", type="index") with gr.Column(scale=1, min_width=300): manage_VRAM = gr.Checkbox(value=params['manage_VRAM'], label='Manage VRAM') save_img = gr.Checkbox(value=params['save_img'], label='Keep original images and use them in chat') force_pic = gr.Button("Force the picture response") suppr_pic = gr.Button("Suppress the picture response") with gr.Row(): checkpoint = gr.Dropdown(params['checkpoint_list'], value=params['sd_checkpoint'], label="Checkpoint", type="value") update_checkpoints = gr.Button("Get list of checkpoints") with gr.Accordion("Generation parameters", open=False): prompt_prefix = gr.Textbox(placeholder=params['prompt_prefix'], value=params['prompt_prefix'], label='Prompt Prefix (best used to describe the look of the character)') textgen_prefix = gr.Textbox(placeholder=params['textgen_prefix'], value=params['textgen_prefix'], label='textgen prefix (type [subject] where the subject should be placed)') negative_prompt = gr.Textbox(placeholder=params['negative_prompt'], value=params['negative_prompt'], label='Negative Prompt') with gr.Row(): with gr.Column(): width = gr.Slider(64, 2048, value=params['width'], step=64, label='Width') height = gr.Slider(64, 2048, value=params['height'], step=64, label='Height') with gr.Column(variant="compact", elem_id="sampler_col"): with gr.Row(elem_id="sampler_row"): sampler_name = gr.Dropdown(value=params['sampler_name'], allow_custom_value=True, label='Sampling method', elem_id="sampler_box") create_refresh_button(sampler_name, lambda: None, lambda: {'choices': get_samplers()}, 'refresh-button') steps = gr.Slider(1, 150, value=params['steps'], step=1, label="Sampling steps", elem_id="steps_box") with gr.Row(): seed = gr.Number(label="Seed", value=params['seed'], elem_id="seed_box") cfg_scale = gr.Number(label="CFG Scale", value=params['cfg_scale'], elem_id="cfg_box") with gr.Column() as hr_options: restore_faces = gr.Checkbox(value=params['restore_faces'], label='Restore faces') enable_hr = gr.Checkbox(value=params['enable_hr'], label='Hires. fix') with gr.Row(visible=params['enable_hr'], elem_classes="hires_opts") as hr_options: hr_scale = gr.Slider(1, 4, value=params['hr_scale'], step=0.1, label='Upscale by') denoising_strength = gr.Slider(0, 1, value=params['denoising_strength'], step=0.01, label='Denoising strength') hr_upscaler = gr.Textbox(placeholder=params['hr_upscaler'], value=params['hr_upscaler'], label='Upscaler') # Event functions to update the parameters in the backend address.change(lambda x: params.update({"address": filter_address(x)}), address, None) mode.select(lambda x: params.update({"mode": x}), mode, None) mode.select(lambda x: toggle_generation(x > 1), inputs=mode, outputs=None) manage_VRAM.change(lambda x: params.update({"manage_VRAM": x}), manage_VRAM, None) manage_VRAM.change(lambda x: give_VRAM_priority('set' if x else 'reset'), inputs=manage_VRAM, outputs=None) save_img.change(lambda x: params.update({"save_img": x}), save_img, None) address.submit(fn=SD_api_address_update, inputs=address, outputs=address) prompt_prefix.change(lambda x: params.update({"prompt_prefix": x}), prompt_prefix, None) textgen_prefix.change(lambda x: params.update({"textgen_prefix": x}), textgen_prefix, None) negative_prompt.change(lambda x: params.update({"negative_prompt": x}), negative_prompt, None) width.change(lambda x: params.update({"width": x}), width, None) height.change(lambda x: params.update({"height": x}), height, None) hr_scale.change(lambda x: params.update({"hr_scale": x}), hr_scale, None) denoising_strength.change(lambda x: params.update({"denoising_strength": x}), denoising_strength, None) restore_faces.change(lambda x: params.update({"restore_faces": x}), restore_faces, None) hr_upscaler.change(lambda x: params.update({"hr_upscaler": x}), hr_upscaler, None) enable_hr.change(lambda x: params.update({"enable_hr": x}), enable_hr, None) enable_hr.change(lambda x: hr_options.update(visible=params["enable_hr"]), enable_hr, hr_options) update_checkpoints.click(get_checkpoints, None, checkpoint) checkpoint.change(lambda x: params.update({"sd_checkpoint": x}), checkpoint, None) checkpoint.change(load_checkpoint, checkpoint, None) sampler_name.change(lambda x: params.update({"sampler_name": x}), sampler_name, None) steps.change(lambda x: params.update({"steps": x}), steps, None) seed.change(lambda x: params.update({"seed": x}), seed, None) cfg_scale.change(lambda x: params.update({"cfg_scale": x}), cfg_scale, None) force_pic.click(lambda x: toggle_generation(True), inputs=force_pic, outputs=None) suppr_pic.click(lambda x: toggle_generation(False), inputs=suppr_pic, outputs=None)
--- +++ @@ -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) # and replace it with 'text' for the purposes of logging? def output_modifier(string, state): + """ + This function is applied to the model outputs. + """ global picture_response, params @@ -218,6 +225,11 @@ def bot_prefix_modifier(string): + """ + This function is only applied in chat mode. It modifies + the prefix text for the Bot and can be used to bias its + behavior. + """ return string @@ -374,4 +386,4 @@ cfg_scale.change(lambda x: params.update({"cfg_scale": x}), cfg_scale, None) force_pic.click(lambda x: toggle_generation(True), inputs=force_pic, outputs=None) - suppr_pic.click(lambda x: toggle_generation(False), inputs=suppr_pic, outputs=None)+ suppr_pic.click(lambda x: toggle_generation(False), inputs=suppr_pic, outputs=None)
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): return None try: return Image.open(path) except Exception as e: logger.error(f"Failed to open image file: {path}. Reason: {e}") return None def convert_pil_to_base64(image: Image.Image) -> str: buffered = io.BytesIO() # Save image to an in-memory bytes buffer in PNG format image.save(buffered, format="PNG") # Encode the bytes to a base64 string return base64.b64encode(buffered.getvalue()).decode('utf-8') def decode_base64_image(base64_string: str) -> Image.Image: try: if base64_string.startswith('data:image/'): base64_string = base64_string.split(',', 1)[1] image_data = base64.b64decode(base64_string) image = Image.open(io.BytesIO(image_data)) return image except Exception as e: logger.error(f"Failed to decode base64 image: {e}") raise ValueError(f"Invalid base64 image data: {e}") def process_message_content(content: Any) -> Tuple[str, List[Image.Image]]: if isinstance(content, str): return content, [] if isinstance(content, list): text_parts = [] images = [] for item in content: if not isinstance(item, dict): continue item_type = item.get('type', '') if item_type == 'text': text_parts.append(item.get('text', '')) elif item_type == 'image_url': image_url_data = item.get('image_url', {}) image_url = image_url_data.get('url', '') if image_url.startswith('data:image/'): try: images.append(decode_base64_image(image_url)) except Exception as e: logger.warning(f"Failed to process a base64 image: {e}") elif image_url.startswith('http'): # Support external URLs try: import requests from urllib.parse import urljoin from modules.web_search import _validate_url _validate_url(image_url) url = image_url for _ in range(5): response = requests.get(url, timeout=10, allow_redirects=False) if response.is_redirect and 'Location' in response.headers: url = urljoin(url, response.headers['Location']) _validate_url(url) else: break response.raise_for_status() image_data = response.content image = Image.open(io.BytesIO(image_data)) images.append(image) logger.info("Successfully loaded external image from URL") except Exception as e: logger.warning(f"Failed to fetch external image: {e}") else: logger.warning(f"Unsupported image URL format: {image_url[:70]}...") return ' '.join(text_parts), images return str(content), [] def convert_image_attachments_to_pil(image_attachments: List[dict]) -> List[Image.Image]: pil_images = [] for attachment in image_attachments: if attachment.get('type') == 'image' and 'image_data' in attachment: try: image = decode_base64_image(attachment['image_data']) if image.mode != 'RGB': image = image.convert('RGB') pil_images.append(image) except Exception as e: logger.warning(f"Failed to process image attachment: {e}") return pil_images def convert_openai_messages_to_images(messages: List[dict]) -> List[Image.Image]: all_images = [] for message in messages: if isinstance(message, dict) and 'content' in message: _, images = process_message_content(message['content']) all_images.extend(images) return all_images
--- +++ @@ -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(base64_string: str) -> Image.Image: + """Decodes a base64 string to a PIL Image.""" try: if base64_string.startswith('data:image/'): base64_string = base64_string.split(',', 1)[1] @@ -45,6 +47,10 @@ def process_message_content(content: Any) -> Tuple[str, List[Image.Image]]: + """ + Processes message content that may contain text and images. + Returns: A tuple of (text_content, list_of_pil_images). + """ if isinstance(content, str): return content, [] @@ -99,6 +105,7 @@ def convert_image_attachments_to_pil(image_attachments: List[dict]) -> List[Image.Image]: + """Convert webui image_attachments format to PIL Images.""" pil_images = [] for attachment in image_attachments: if attachment.get('type') == 'image' and 'image_data' in attachment: @@ -113,9 +120,10 @@ def convert_openai_messages_to_images(messages: List[dict]) -> List[Image.Image]: + """Convert OpenAI messages format to PIL Images.""" all_images = [] for message in messages: if isinstance(message, dict) and 'content' in message: _, images = process_message_content(message['content']) all_images.extend(images) - return all_images+ return all_images
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 parameters.should_to_lower(): builder.to_lower() if parameters.should_remove_punctuation(): builder.remove_punctuation() if parameters.should_remove_specific_pos(): builder.remove_specific_pos() if parameters.should_remove_stopwords(): builder.remove_stopwords if parameters.should_lemmatize(): builder.lemmatize() if parameters.should_merge_spaces(): builder.merge_spaces if parameters.should_strip(): builder.strip() if parameters.get_num_conversion_strategy(): if parameters.get_num_conversion_strategy() == parameters.NUM_TO_WORD_METHOD: builder.num_to_word(parameters.get_min_num_length()) elif parameters.get_num_conversion_strategy() == parameters.NUM_TO_CHAR_METHOD: builder.num_to_char(parameters.get_min_num_length()) elif parameters.get_num_conversion_strategy() == parameters.NUM_TO_CHAR_LONG_METHOD: builder.num_to_char_long(parameters.get_min_num_length()) return builder.build() def preprocess_text(text) -> list[str]: important_sentences = TextSummarizer.process_long_text(text, parameters.get_min_num_sentences()) return [preprocess_text_no_summary(sent) for sent in important_sentences] def _create_chunks_with_context(corpus, chunk_len, context_left, context_right): words = re.split('(\\s+)', corpus) word_start_indices = [0] current_index = 0 for word in words: current_index += len(word) word_start_indices.append(current_index) chunks, chunk_lengths, chunk_start_indices, chunk_with_context_start_indices = [], [], [], [] current_length = 0 current_index = 0 chunk = [] for word in words: if current_length + len(word) > chunk_len: chunks.append(''.join(chunk)) chunk_lengths.append(current_length) chunk_start_indices.append(current_index - current_length) chunk = [word] current_length = len(word) else: chunk.append(word) current_length += len(word) current_index += len(word) if chunk: chunks.append(''.join(chunk)) chunk_lengths.append(current_length) chunk_start_indices.append(current_index - current_length) chunks_with_context = [] for start_index, chunk_length in zip(chunk_start_indices, chunk_lengths): context_start_index = bisect.bisect_right(word_start_indices, start_index - context_left) context_end_index = bisect.bisect_left(word_start_indices, start_index + chunk_length + context_right) # Combine all the words in the context range (before, chunk, and after) chunk_with_context = ''.join(words[context_start_index:context_end_index]) chunks_with_context.append(chunk_with_context) # Determine the start index of the chunk with context chunk_with_context_start_index = word_start_indices[context_start_index] chunk_with_context_start_indices.append(chunk_with_context_start_index) return chunks, chunks_with_context, chunk_with_context_start_indices def _clear_chunks(data_chunks, data_chunks_with_context, data_chunk_starting_indices): distinct_data_chunks = [] distinct_data_chunks_with_context = [] distinct_data_chunk_starting_indices = [] seen_chunks = dict() for chunk, context, index in zip(data_chunks, data_chunks_with_context, data_chunk_starting_indices): # Skip the chunk if it does not contain any alphanumeric characters if not any(char.isalnum() for char in chunk): continue seen_chunk_start = seen_chunks.get(chunk) if seen_chunk_start: # If we've already seen this exact chunk, and the context around it it very close to the seen chunk, then skip it. if abs(seen_chunk_start - index) < parameters.get_delta_start(): continue distinct_data_chunks.append(chunk) distinct_data_chunks_with_context.append(context) distinct_data_chunk_starting_indices.append(index) seen_chunks[chunk] = index return distinct_data_chunks, distinct_data_chunks_with_context, distinct_data_chunk_starting_indices def process_and_add_to_collector(corpus: str, collector: ChromaCollector, clear_collector_before_adding: bool, metadata: dict): # Defining variables chunk_lens = [int(len.strip()) for len in parameters.get_chunk_len().split(',')] context_len = [int(len.strip()) for len in parameters.get_context_len().split(',')] if len(context_len) >= 3: raise f"Context len has too many values: {len(context_len)}" if len(context_len) == 2: context_left = context_len[0] context_right = context_len[1] else: context_left = context_right = context_len[0] data_chunks = [] data_chunks_with_context = [] data_chunk_starting_indices = [] if parameters.get_add_date_time(): now = datetime.now() date_time_chunk = f"Current time is {now.strftime('%H:%M:%S')}. Today is {now.strftime('%A')}. The current date is {now.strftime('%Y-%m-%d')}." data_chunks.append(date_time_chunk) data_chunks_with_context.append(date_time_chunk) data_chunk_starting_indices.append(0) # Handling chunk_regex if parameters.get_chunk_regex(): if parameters.get_chunk_separator(): cumulative_length = 0 # This variable will store the length of the processed corpus sections = corpus.split(parameters.get_chunk_separator()) for section in sections: special_chunks = list(re.finditer(parameters.get_chunk_regex(), section)) for match in special_chunks: chunk = match.group(0) start_index = match.start() end_index = start_index + len(chunk) context = section[max(0, start_index - context_left):min(len(section), end_index + context_right)] data_chunks.append(chunk) data_chunks_with_context.append(context) data_chunk_starting_indices.append(cumulative_length + max(0, start_index - context_left)) cumulative_length += len(section) + len(parameters.get_chunk_separator()) # Update the length of the processed corpus else: special_chunks = list(re.finditer(parameters.get_chunk_regex(), corpus)) for match in special_chunks: chunk = match.group(0) start_index = match.start() end_index = start_index + len(chunk) context = corpus[max(0, start_index - context_left):min(len(corpus), end_index + context_right)] data_chunks.append(chunk) data_chunks_with_context.append(context) data_chunk_starting_indices.append(max(0, start_index - context_left)) for chunk_len in chunk_lens: # Breaking the data into chunks and adding those to the db if parameters.get_chunk_separator(): cumulative_length = 0 # This variable will store the length of the processed corpus sections = corpus.split(parameters.get_chunk_separator()) for section in sections: chunks, chunks_with_context, context_start_indices = _create_chunks_with_context(section, chunk_len, context_left, context_right) context_start_indices = [cumulative_length + i for i in context_start_indices] # Add the length of the processed corpus to each start index data_chunks.extend(chunks) data_chunks_with_context.extend(chunks_with_context) data_chunk_starting_indices.extend(context_start_indices) cumulative_length += len(section) + len(parameters.get_chunk_separator()) # Update the length of the processed corpus else: chunks, chunks_with_context, context_start_indices = _create_chunks_with_context(corpus, chunk_len, context_left, context_right) data_chunks.extend(chunks) data_chunks_with_context.extend(chunks_with_context) data_chunk_starting_indices.extend(context_start_indices) data_chunks = [preprocess_text_no_summary(chunk) for chunk in data_chunks] data_chunks, data_chunks_with_context, data_chunk_starting_indices = _clear_chunks( data_chunks, data_chunks_with_context, data_chunk_starting_indices ) if clear_collector_before_adding: collector.clear() collector.add(data_chunks, data_chunks_with_context, data_chunk_starting_indices, [metadata] * len(data_chunks) if metadata is not None else None)
--- +++ @@ -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 import re @@ -49,6 +54,18 @@ def _create_chunks_with_context(corpus, chunk_len, context_left, context_right): + """ + This function takes a corpus of text and splits it into chunks of a specified length, + then adds a specified amount of context to each chunk. The context is added by first + going backwards from the start of the chunk and then going forwards from the end of the + chunk, ensuring that the context includes only whole words and that the total context length + does not exceed the specified limit. This function uses binary search for efficiency. + + Returns: + chunks (list of str): The chunks of text. + chunks_with_context (list of str): The chunks of text with added context. + chunk_with_context_start_indices (list of int): The starting indices of each chunk with context in the corpus. + """ words = re.split('(\\s+)', corpus) word_start_indices = [0] current_index = 0 @@ -198,4 +215,4 @@ if clear_collector_before_adding: collector.clear() - collector.add(data_chunks, data_chunks_with_context, data_chunk_starting_indices, [metadata] * len(data_chunks) if metadata is not None else None)+ collector.add(data_chunks, data_chunks_with_context, data_chunk_starting_indices, [metadata] * len(data_chunks) if metadata is not None else None)
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': 'bn', 'Bosnian': 'bs', 'Bulgarian': 'bg', 'Catalan': 'ca', 'Cebuano': 'ceb', 'Chinese (Simplified)': 'zh-CN', 'Chinese (Traditional)': 'zh-TW', 'Corsican': 'co', 'Croatian': 'hr', 'Czech': 'cs', 'Danish': 'da', 'Dutch': 'nl', 'English': 'en', 'Esperanto': 'eo', 'Estonian': 'et', 'Finnish': 'fi', 'French': 'fr', 'Frisian': 'fy', 'Galician': 'gl', 'Georgian': 'ka', 'German': 'de', 'Greek': 'el', 'Gujarati': 'gu', 'Haitian Creole': 'ht', 'Hausa': 'ha', 'Hawaiian': 'haw', 'Hebrew': 'iw', 'Hindi': 'hi', 'Hmong': 'hmn', 'Hungarian': 'hu', 'Icelandic': 'is', 'Igbo': 'ig', 'Indonesian': 'id', 'Irish': 'ga', 'Italian': 'it', 'Japanese': 'ja', 'Javanese': 'jw', 'Kannada': 'kn', 'Kazakh': 'kk', 'Khmer': 'km', 'Korean': 'ko', 'Kurdish': 'ku', 'Kyrgyz': 'ky', 'Lao': 'lo', 'Latin': 'la', 'Latvian': 'lv', 'Lithuanian': 'lt', 'Luxembourgish': 'lb', 'Macedonian': 'mk', 'Malagasy': 'mg', 'Malay': 'ms', 'Malayalam': 'ml', 'Maltese': 'mt', 'Maori': 'mi', 'Marathi': 'mr', 'Mongolian': 'mn', 'Myanmar (Burmese)': 'my', 'Nepali': 'ne', 'Norwegian': 'no', 'Nyanja (Chichewa)': 'ny', 'Pashto': 'ps', 'Persian': 'fa', 'Polish': 'pl', 'Portuguese (Portugal, Brazil)': 'pt', 'Punjabi': 'pa', 'Romanian': 'ro', 'Russian': 'ru', 'Samoan': 'sm', 'Scots Gaelic': 'gd', 'Serbian': 'sr', 'Sesotho': 'st', 'Shona': 'sn', 'Sindhi': 'sd', 'Sinhala (Sinhalese)': 'si', 'Slovak': 'sk', 'Slovenian': 'sl', 'Somali': 'so', 'Spanish': 'es', 'Sundanese': 'su', 'Swahili': 'sw', 'Swedish': 'sv', 'Tagalog (Filipino)': 'tl', 'Tajik': 'tg', 'Tamil': 'ta', 'Telugu': 'te', 'Thai': 'th', 'Turkish': 'tr', 'Ukrainian': 'uk', 'Urdu': 'ur', 'Uzbek': 'uz', 'Vietnamese': 'vi', 'Welsh': 'cy', 'Xhosa': 'xh', 'Yiddish': 'yi', 'Yoruba': 'yo', 'Zulu': 'zu'} def input_modifier(string): if not params['activate']: return string return GoogleTranslator(source=params['language string'], target='en').translate(string) def output_modifier(string): if not params['activate']: return string translated_str = GoogleTranslator(source='en', target=params['language string']).translate(html.unescape(string)) return html.escape(translated_str) def bot_prefix_modifier(string): return string def ui(): # Finding the language name from the language code to use as the default value language_name = list(language_codes.keys())[list(language_codes.values()).index(params['language string'])] # Gradio elements with gr.Row(): activate = gr.Checkbox(value=params['activate'], label='Activate translation') with gr.Row(): language = gr.Dropdown(value=language_name, choices=[k for k in language_codes], label='Language') # Event functions to update the parameters in the backend activate.change(lambda x: params.update({"activate": x}), activate, None) language.change(lambda x: params.update({"language string": language_codes[x]}), language, None)
--- +++ @@ -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 the model outputs. + """ if not params['activate']: return string @@ -27,6 +34,11 @@ def bot_prefix_modifier(string): + """ + This function is only applied in chat mode. It modifies + the prefix text for the Bot and can be used to bias its + behavior. + """ return string @@ -44,4 +56,4 @@ # Event functions to update the parameters in the backend activate.change(lambda x: params.update({"activate": x}), activate, None) - language.change(lambda x: params.update({"language string": language_codes[x]}), language, None)+ language.change(lambda x: params.update({"language string": language_codes[x]}), language, None)
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 from modules.logging_colors import logger from modules.utils import check_model_loaded def generate_reply(*args, **kwargs): if shared.args.idle_timeout > 0 and shared.model is None and shared.model_name not in [None, 'None']: from modules.models import load_model shared.model, shared.tokenizer = load_model(shared.model_name) state = args[1] if len(args) > 1 else kwargs.get('state', {}) use_parallel = ( state.get('stop_event') is not None and shared.model.__class__.__name__ in ['Exllamav3Model', 'LlamaServer', 'TensorRTLLMModel'] and (shared.model.__class__.__name__ != 'LlamaServer' or shared.args.parallel > 1) ) if not use_parallel: shared.generation_lock.acquire() try: for result in _generate_reply(*args, **kwargs): yield result finally: models.last_generation_time = time.time() if not use_parallel: shared.generation_lock.release() def _generate_reply(question, state, stopping_strings=None, is_chat=False, escape_html=False, for_ui=False): # Find the appropriate generation function generate_func = apply_extensions('custom_generate_reply') if generate_func is None: model_is_loaded, error_message = check_model_loaded() if not model_is_loaded: yield '' return if shared.model.__class__.__name__ in ['LlamaServer', 'Exllamav3Model', 'TensorRTLLMModel']: generate_func = generate_reply_custom else: generate_func = generate_reply_HF if generate_func != generate_reply_HF and shared.args.verbose: logger.info("PROMPT=") print_prompt(question) # Prepare the input original_question = question if not is_chat: state = apply_extensions('state', state) question = apply_extensions('input', question, state) # Find the stopping strings all_stop_strings = [] for st in (stopping_strings, state['custom_stopping_strings']): if type(st) is str: st = ast.literal_eval(f"[{st}]") if type(st) is list and len(st) > 0: all_stop_strings += st shared.stop_everything = False reply = '' is_stream = state['stream'] if len(all_stop_strings) > 0 and not state['stream']: original_logits_processor = state.get('logits_processor') stop_event_ref = state.pop('stop_event', None) state = copy.deepcopy(state) if stop_event_ref is not None: state['stop_event'] = stop_event_ref if original_logits_processor is not None: state['logits_processor'] = original_logits_processor state['stream'] = True # Generate last_update = -1 latency_threshold = 1 / 1000 for reply in generate_func(question, original_question, state, stopping_strings, is_chat=is_chat): cur_time = time.monotonic() reply, stop_found = apply_stopping_strings(reply, all_stop_strings) if escape_html: reply = html.escape(reply) if is_stream: # Limit number of tokens/second to make text readable in real time if state['max_tokens_second'] > 0: diff = 1 / state['max_tokens_second'] - (cur_time - last_update) if diff > 0: time.sleep(diff) last_update = time.monotonic() yield reply # Limit updates to avoid lag in the Gradio UI # API updates are not limited else: # If 'generate_func' takes less than 0.001 seconds to yield the next token # (equivalent to more than 1000 tok/s), assume that the UI is lagging behind and skip yielding if (cur_time - last_update) > latency_threshold: yield reply last_update = time.monotonic() stop_event = state.get('stop_event') if stop_found or shared.stop_everything or (stop_event and stop_event.is_set()): break if not is_chat: reply = apply_extensions('output', reply, state) yield reply def encode(prompt, add_special_tokens=True, add_bos_token=True, truncation_length=None): if shared.tokenizer is None: raise ValueError('No tokenizer is loaded') # llama.cpp case if shared.model.__class__.__name__ == 'LlamaServer': input_ids = shared.tokenizer.encode(str(prompt), add_bos_token=add_bos_token) input_ids = np.array(input_ids).reshape(1, len(input_ids)) if truncation_length is not None: input_ids = input_ids[:, -truncation_length:] return input_ids # All other model types else: import torch from modules.torch_utils import get_device if shared.model.__class__.__name__ in ['Exllamav3Model', 'TensorRTLLMModel']: input_ids = shared.tokenizer.encode(str(prompt)) if shared.model.__class__.__name__ not in ['Exllamav3Model']: input_ids = np.array(input_ids).reshape(1, len(input_ids)) else: input_ids = shared.tokenizer.encode(str(prompt), return_tensors='pt', add_special_tokens=add_special_tokens) if hasattr(shared.tokenizer, 'bos_token_id') and shared.tokenizer.bos_token_id is not None: if add_bos_token: # Add BOS token if missing if (len(input_ids[0]) > 0 and input_ids[0][0] != shared.tokenizer.bos_token_id) or len(input_ids[0]) == 0: bos_tensor = torch.tensor([[shared.tokenizer.bos_token_id]]) input_ids = torch.cat((bos_tensor, input_ids), 1) # Always prevent double BOS tokens (regardless of add_bos_token setting) while len(input_ids[0]) > 1 and input_ids[0][0] == shared.tokenizer.bos_token_id and input_ids[0][1] == shared.tokenizer.bos_token_id: input_ids = input_ids[:, 1:] if truncation_length is not None: input_ids = input_ids[:, -truncation_length:] if shared.model.__class__.__name__ in ['Exllamav3Model', 'TensorRTLLMModel'] or shared.args.cpu: return input_ids else: device = get_device() if device: return input_ids.to(device) return input_ids def decode(output_ids, skip_special_tokens=True): if shared.tokenizer is None: raise ValueError('No tokenizer is loaded') return shared.tokenizer.decode(output_ids, skip_special_tokens=skip_special_tokens) def get_encoded_length(prompt): length_after_extensions = apply_extensions('tokenized_length', prompt) if length_after_extensions is not None: return length_after_extensions return len(encode(prompt)[0]) def get_token_ids(prompt): tokens = encode(prompt)[0] decoded_tokens = [shared.tokenizer.decode([int(i)]) for i in tokens] output = '' for row in list(zip(tokens, decoded_tokens)): output += f"{str(int(row[0])).ljust(5)} - {repr(row[1])}\n" return output def get_max_prompt_length(state): return state['truncation_length'] - state['max_new_tokens'] def generate_reply_wrapper(question, state, stopping_strings=None): reply = question if not shared.is_seq2seq else '' yield formatted_outputs(reply, shared.model_name) for reply in generate_reply(question, state, stopping_strings, is_chat=False, escape_html=True, for_ui=True): if not shared.is_seq2seq: reply = question + reply yield formatted_outputs(reply, shared.model_name) def formatted_outputs(reply, model_name): return html.unescape(reply), generate_basic_html(reply) def set_manual_seed(seed): seed = int(seed) if seed == -1: seed = random.randint(1, 2**31) if shared.args.loader != 'llama.cpp': import torch from transformers import is_torch_npu_available, is_torch_xpu_available torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) elif is_torch_xpu_available(): torch.xpu.manual_seed_all(seed) elif is_torch_npu_available(): torch.npu.manual_seed_all(seed) return seed def stop_everything_event(): shared.stop_everything = True def apply_stopping_strings(reply, all_stop_strings): stop_found = False for string in all_stop_strings: idx = reply.find(string) if idx != -1: reply = reply[:idx] stop_found = True break if not stop_found: # If something like "\nYo" is generated just before "\nYou:" # is completed, trim it for string in all_stop_strings: for j in range(len(string) - 1, 0, -1): if reply[-j:] == string[:j]: reply = reply[:-j] break else: continue break return reply, stop_found def get_reply_from_output_ids(output_ids, state=None, starting_from=0): import torch if torch.cuda.is_available(): torch.cuda.synchronize() reply = decode(output_ids[starting_from:], state['skip_special_tokens'] if state else True) # Handle tokenizers that do not add the leading space for the first token if (hasattr(shared.tokenizer, 'convert_ids_to_tokens') and len(output_ids) > starting_from) and not reply.startswith(' '): first_token = shared.tokenizer.convert_ids_to_tokens(int(output_ids[starting_from])) if isinstance(first_token, (bytes,)): # try to decode the bytes to a string # if it fails, which means it's not a string in this turn, just ignore it try: first_token = first_token.decode('utf8') except UnicodeDecodeError: first_token = '' if first_token.startswith('▁'): reply = ' ' + reply return reply def generate_reply_HF(question, original_question, state, stopping_strings=None, is_chat=False): import torch import transformers from transformers import LogitsProcessorList from modules.grammar.grammar_utils import initialize_grammar from modules.grammar.logits_process import ( GrammarConstrainedLogitsProcessor ) from modules.torch_utils import clear_torch_cache, get_device from modules.transformers_loader import ( Stream, _StopEverythingStoppingCriteria ) if shared.args.loader == 'Transformers': clear_torch_cache() seed = set_manual_seed(state['seed']) generate_params = {} for k in [ 'temperature', 'dynatemp_low', 'dynatemp_high', 'dynatemp_exponent', 'smoothing_factor', 'smoothing_curve', 'min_p', 'top_p', 'top_k', 'typical_p', 'xtc_threshold', 'xtc_probability', 'tfs', 'top_a', 'top_n_sigma', 'adaptive_target', 'adaptive_decay', 'dry_multiplier', 'dry_allowed_length', 'dry_base', 'repetition_penalty', 'frequency_penalty', 'presence_penalty', 'encoder_repetition_penalty', 'no_repeat_ngram_size', 'repetition_penalty_range', 'penalty_alpha', 'guidance_scale', 'mirostat_mode', 'mirostat_tau', 'mirostat_eta', 'max_new_tokens', 'do_sample', 'dynamic_temperature', 'temperature_last', 'dry_sequence_breakers', ]: if k in state: generate_params[k] = state[k] for k in ['epsilon_cutoff', 'eta_cutoff']: if state[k] > 0: generate_params[k] = state[k] * 1e-4 if state['prompt_lookup_num_tokens'] > 0: generate_params['prompt_lookup_num_tokens'] = state['prompt_lookup_num_tokens'] if state['ban_eos_token']: generate_params['suppress_tokens'] = [shared.tokenizer.eos_token_id] if state['static_cache']: generate_params['cache_implementation'] = 'static' if isinstance(state['sampler_priority'], list) and len(state['sampler_priority']) > 0: generate_params['sampler_priority'] = state['sampler_priority'] elif isinstance(state['sampler_priority'], str) and state['sampler_priority'].strip() != '': generate_params['sampler_priority'] = [x.strip() for x in state['sampler_priority'].replace('\n', ',').split(',') if x.strip()] if state['custom_token_bans']: to_ban = [int(x.strip()) for x in state['custom_token_bans'].split(',') if x.strip()] if len(to_ban) > 0: if generate_params.get('suppress_tokens', None): generate_params['suppress_tokens'] += to_ban else: generate_params['suppress_tokens'] = to_ban if state['negative_prompt'] != '': generate_params['negative_prompt_ids'] = encode(state['negative_prompt']) generate_params.update({'use_cache': not shared.args.no_cache}) # Encode the input input_ids = encode(question, add_bos_token=state['add_bos_token'], truncation_length=get_max_prompt_length(state)) output = input_ids[0] if state['auto_max_new_tokens']: generate_params['max_new_tokens'] = state['truncation_length'] - input_ids.shape[-1] # Add the encoded tokens to generate_params question, input_ids, inputs_embeds = apply_extensions('tokenizer', state, question, input_ids, None) original_input_ids = input_ids generate_params.update({'inputs': input_ids}) if inputs_embeds is not None: generate_params.update({'inputs_embeds': inputs_embeds}) # Stopping criteria / eos token eos_token_ids = [shared.tokenizer.eos_token_id] if shared.tokenizer.eos_token_id is not None else [] generate_params['eos_token_id'] = eos_token_ids generate_params['stopping_criteria'] = transformers.StoppingCriteriaList() generate_params['stopping_criteria'].append(_StopEverythingStoppingCriteria()) # Logits processor processor = state.get('logits_processor', LogitsProcessorList([])) if not isinstance(processor, LogitsProcessorList): processor = LogitsProcessorList([processor]) # Grammar if state['grammar_string'].strip() != '': grammar = initialize_grammar(state['grammar_string']) grammar_processor = GrammarConstrainedLogitsProcessor(grammar) processor.append(grammar_processor) apply_extensions('logits_processor', processor, input_ids) generate_params['logits_processor'] = processor if shared.args.verbose: logger.info("GENERATE_PARAMS=") filtered_params = {key: value for key, value in generate_params.items() if not isinstance(value, torch.Tensor)} pprint.PrettyPrinter(indent=4, sort_dicts=False).pprint(filtered_params) print() logger.info("PROMPT=") print_prompt(decode(input_ids[0], skip_special_tokens=False)) t0 = time.time() try: if not is_chat and not shared.is_seq2seq: yield '' # Generate the entire reply at once. if not state['stream']: with torch.no_grad(): output = shared.model.generate(**generate_params)[0] device = get_device() if device: output = output.to(device) starting_from = 0 if shared.is_seq2seq else len(input_ids[0]) yield get_reply_from_output_ids(output, state, starting_from=starting_from) # Stream the reply 1 token at a time. # This is based on the trick of using 'stopping_criteria' to create an iterator. else: def generate_with_callback(callback=None, *args, **kwargs): kwargs['stopping_criteria'].append(Stream(callback_func=callback)) with torch.no_grad(): shared.model.generate(**kwargs) def generate_with_streaming(**kwargs): return Iteratorize(generate_with_callback, [], kwargs, callback=None) with generate_with_streaming(**generate_params) as generator: cumulative_reply = '' starting_from = 0 if shared.is_seq2seq else len(input_ids[0]) for output in generator: if output[-1] in eos_token_ids: break new_content = get_reply_from_output_ids(output, state, starting_from=starting_from) # check the partial unicode character if chr(0xfffd) in new_content: continue cumulative_reply += new_content starting_from = len(output) yield cumulative_reply except Exception: traceback.print_exc() finally: t1 = time.time() original_tokens = len(original_input_ids[0]) new_tokens = len(output) - (original_tokens if not shared.is_seq2seq else 0) logger.info(f'Output generated in {(t1-t0):.2f} seconds ({new_tokens/(t1-t0):.2f} tokens/s, {new_tokens} tokens, context {original_tokens}, seed {seed})') return def generate_reply_custom(question, original_question, state, stopping_strings=None, is_chat=False): stop_event_ref = state.pop('stop_event', None) state = copy.deepcopy(state) if stop_event_ref is not None: state['stop_event'] = stop_event_ref state['seed'] = set_manual_seed(state['seed']) t0 = time.time() reply = '' try: if not is_chat: yield '' if not state['stream']: reply = shared.model.generate(question, state) yield reply else: for reply in shared.model.generate_with_streaming(question, state): yield reply except Exception: traceback.print_exc() finally: t1 = time.time() if hasattr(shared.model, 'last_prompt_token_count'): original_tokens = shared.model.last_prompt_token_count new_tokens = len(encode(reply)[0]) if reply else 0 else: original_tokens = len(encode(original_question)[0]) new_tokens = len(encode(original_question + reply)[0]) - original_tokens logger.info(f'Output generated in {(t1-t0):.2f} seconds ({new_tokens/(t1-t0):.2f} tokens/s, {new_tokens} tokens, context {original_tokens}, seed {state["seed"]})') return def print_prompt(prompt, max_chars=-1): DARK_YELLOW = "\033[38;5;3m" RESET = "\033[0m" if max_chars > 0 and len(prompt) > max_chars: half_chars = max_chars // 2 hidden_len = len(prompt[half_chars:-half_chars]) hidden_msg = f"{DARK_YELLOW}[...{hidden_len} characters hidden...]{RESET}" print(prompt[:half_chars] + hidden_msg + prompt[-half_chars:]) else: print(prompt) print()
--- +++ @@ -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_custom(question, original_question, state, stopping_strings=None, is_chat=False): + """ + For models that do not use the transformers library for sampling + """ stop_event_ref = state.pop('stop_event', None) state = copy.deepcopy(state) @@ -531,4 +537,4 @@ else: print(prompt) - print()+ print()
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 DiffusersBnBConfig from diffusers import TorchAoConfig from diffusers.quantizers import PipelineQuantizationConfig from transformers import BitsAndBytesConfig as TransformersBnBConfig if quant_method == 'none' or not quant_method: return None # Bitsandbytes 8-bit quantization elif quant_method == 'bnb-8bit': return PipelineQuantizationConfig( quant_mapping={ "transformer": DiffusersBnBConfig( load_in_8bit=True ), "text_encoder": TransformersBnBConfig( load_in_8bit=True ) } ) # Bitsandbytes 4-bit quantization elif quant_method == 'bnb-4bit': return PipelineQuantizationConfig( quant_mapping={ "transformer": DiffusersBnBConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True ), "text_encoder": TransformersBnBConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True ) } ) # torchao int8 weight-only elif quant_method == 'torchao-int8wo': return PipelineQuantizationConfig( quant_mapping={ "transformer": TorchAoConfig("int8wo"), "text_encoder": TorchAoConfig("int8wo") } ) # torchao fp4 (e2m1) elif quant_method == 'torchao-fp4': return PipelineQuantizationConfig( quant_mapping={ "transformer": TorchAoConfig("fp4_e2m1"), "text_encoder": TorchAoConfig("fp4_e2m1") } ) # torchao float8 weight-only elif quant_method == 'torchao-float8wo': return PipelineQuantizationConfig( quant_mapping={ "transformer": TorchAoConfig("float8wo"), "text_encoder": TorchAoConfig("float8wo") } ) else: logger.warning(f"Unknown quantization method: {quant_method}. Loading without quantization.") return None def get_pipeline_type(pipe): class_name = pipe.__class__.__name__ if class_name == 'ZImagePipeline': return 'zimage' elif class_name == 'QwenImagePipeline': return 'qwenimage' else: return 'unknown' def load_image_model(model_name, dtype='bfloat16', attn_backend='sdpa', cpu_offload=False, compile_model=False, quant_method='none'): import torch from diffusers import DiffusionPipeline from modules.torch_utils import get_device logger.info(f"Loading image model \"{model_name}\" with quantization: {quant_method}") t0 = time.time() dtype_map = {"bfloat16": torch.bfloat16, "float16": torch.float16} target_dtype = dtype_map.get(dtype, torch.bfloat16) model_path = resolve_model_path(model_name, image_model=True) try: # Get quantization config based on selected method pipeline_quant_config = get_quantization_config(quant_method) # Load the pipeline load_kwargs = { "torch_dtype": target_dtype, "low_cpu_mem_usage": True, } if pipeline_quant_config is not None: load_kwargs["quantization_config"] = pipeline_quant_config # Use DiffusionPipeline for automatic pipeline detection # This handles both ZImagePipeline and QwenImagePipeline pipe = DiffusionPipeline.from_pretrained( str(model_path), **load_kwargs ) pipeline_type = get_pipeline_type(pipe) if not cpu_offload: pipe.to(get_device()) modules = ["transformer", "unet"] # Set attention backend if attn_backend == 'flash_attention_2': for name in modules: mod = getattr(pipe, name, None) if hasattr(mod, "set_attention_backend"): mod.set_attention_backend("flash") break # Compile model if compile_model: for name in modules: mod = getattr(pipe, name, None) if hasattr(mod, "compile"): logger.info("Compiling model (first run will be slow)...") mod.compile() break if cpu_offload: pipe.enable_model_cpu_offload() shared.image_model = pipe shared.image_model_name = model_name shared.image_pipeline_type = pipeline_type logger.info(f"Loaded image model \"{model_name}\" in {(time.time() - t0):.2f} seconds.") return pipe except Exception as e: logger.error(f"Failed to load image model: {str(e)}") return None def unload_image_model(): if shared.image_model is None: return del shared.image_model shared.image_model = None shared.image_model_name = 'None' shared.image_pipeline_type = None from modules.torch_utils import clear_torch_cache clear_torch_cache() logger.info("Image model unloaded.")
--- +++ @@ -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 from diffusers import BitsAndBytesConfig as DiffusersBnBConfig @@ -81,6 +85,12 @@ def get_pipeline_type(pipe): + """ + Detect the pipeline type based on the loaded pipeline class. + + Returns: + str: 'zimage', 'qwenimage', or 'unknown' + """ class_name = pipe.__class__.__name__ if class_name == 'ZImagePipeline': return 'zimage' @@ -91,6 +101,17 @@ def load_image_model(model_name, dtype='bfloat16', attn_backend='sdpa', cpu_offload=False, compile_model=False, quant_method='none'): + """ + Load a diffusers image generation model. + + Args: + model_name: Name of the model directory + dtype: 'bfloat16' or 'float16' + attn_backend: 'sdpa' or 'flash_attention_2' + cpu_offload: Enable CPU offloading for low VRAM + compile_model: Compile the model for faster inference (slow first run) + quant_method: 'none', 'bnb-8bit', 'bnb-4bit', or torchao options (int8wo, fp4, float8wo) + """ import torch from diffusers import DiffusionPipeline @@ -164,6 +185,7 @@ def unload_image_model(): + """Unload the current image model and free VRAM.""" if shared.image_model is None: return @@ -175,4 +197,4 @@ from modules.torch_utils import clear_torch_cache clear_torch_cache() - logger.info("Image model unloaded.")+ logger.info("Image model unloaded.")
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.generator.filter import Filter from exllamav3.generator.sampler import ( CustomSampler, SS_AdaptiveP, SS_Argmax, SS_MinP, SS_PresFreqP, SS_RepP, SS_Sample, SS_Temperature, SS_TopK, SS_TopP ) from modules import shared from modules.image_utils import ( convert_image_attachments_to_pil, convert_openai_messages_to_images ) from modules.logging_colors import logger from modules.text_generation import get_max_prompt_length try: import flash_attn except Exception: logger.warning('Failed to load flash-attention due to the following error:\n') traceback.print_exc() class LogitBiasFilter(Filter): def __init__(self, tokenizer, logit_bias_dict): super().__init__(tokenizer=tokenizer, trigger_token=None, prefix_str=None, eos_after_completed=False) self.logit_bias_dict = logit_bias_dict self._mask = None def reset(self): pass def accept_token(self, token): pass def is_completed(self): return False def use_background_worker(self): return False def get_next_logit_mask(self): if self._mask is None: self._mask = torch.zeros((1, self.vocab_size), dtype=self.logits_dtype) for token_id_str, bias in self.logit_bias_dict.items(): token_id = int(token_id_str) if 0 <= token_id < self.vocab_size: self._mask[0, token_id] = bias return self._mask class ConcurrentGenerator: def __init__(self, generator): self.generator = generator self.lock = threading.Lock() self.job_queues = {} self.active = True self.has_jobs = threading.Event() self.thread = threading.Thread(target=self._iterate_loop, daemon=True) self.thread.start() def _iterate_loop(self): while self.active: self.has_jobs.wait(timeout=0.5) with self.lock: if not self.job_queues: self.has_jobs.clear() continue try: results = self.generator.iterate() except Exception: logger.error("Exception in ConcurrentGenerator iterate loop:\n" + traceback.format_exc()) for q in self.job_queues.values(): q.put(None) self.job_queues.clear() self.generator.clear_queue() self.has_jobs.clear() continue for result in results: job = result["job"] q = self.job_queues.get(job) if q: q.put(result) if result.get("eos"): self.job_queues.pop(job, None) if not self.job_queues: self.has_jobs.clear() def submit(self, job) -> queue.Queue: q = queue.Queue() with self.lock: self.job_queues[job] = q self.generator.enqueue(job) self.has_jobs.set() return q def cancel(self, job): with self.lock: if job in self.job_queues: self.generator.cancel(job) self.job_queues[job].put(None) del self.job_queues[job] def stop(self): self.active = False self.has_jobs.set() self.thread.join(timeout=5) class Exllamav3Model: def __init__(self): pass @property def device(self) -> torch.device: return torch.device(0) @classmethod def from_pretrained(cls, path_to_model): path_to_model = Path(f'{shared.args.model_dir}') / Path(path_to_model) # Reset global MMTokenAllocator to prevent token ID corruption when switching models from exllamav3.tokenizer.mm_embedding import ( FIRST_MM_EMBEDDING_INDEX, global_allocator ) global_allocator.next_token_index = FIRST_MM_EMBEDDING_INDEX config = Config.from_directory(str(path_to_model)) model = Model.from_config(config) # Calculate the closest multiple of 256 at or above the chosen value max_tokens = shared.args.ctx_size if max_tokens % 256 != 0: adjusted_tokens = ((max_tokens // 256) + 1) * 256 logger.warning(f"max_num_tokens must be a multiple of 256. Adjusting from {max_tokens} to {adjusted_tokens}") max_tokens = adjusted_tokens # Parse cache type cache_type = shared.args.cache_type.lower() cache_kwargs = {} if cache_type == 'fp16': layer_type = CacheLayer_fp16 elif cache_type.startswith('q'): layer_type = CacheLayer_quant if '_' in cache_type: # Different bits for k and v (e.g., q4_q8) k_part, v_part = cache_type.split('_') k_bits = int(k_part[1:]) v_bits = int(v_part[1:]) else: # Same bits for k and v (e.g., q4) k_bits = v_bits = int(cache_type[1:]) # Validate bit ranges if not (2 <= k_bits <= 8 and 2 <= v_bits <= 8): logger.warning(f"Invalid quantization bits: k_bits={k_bits}, v_bits={v_bits}. Must be between 2 and 8. Falling back to fp16.") layer_type = CacheLayer_fp16 else: cache_kwargs = {'k_bits': k_bits, 'v_bits': v_bits} else: logger.warning(f"Unrecognized cache type: {cache_type}. Falling back to fp16.") layer_type = CacheLayer_fp16 cache = Cache(model, max_num_tokens=max_tokens, layer_type=layer_type, **cache_kwargs) load_params = {'progressbar': True} split = None if shared.args.gpu_split: split = [float(alloc) for alloc in shared.args.gpu_split.split(",")] load_params['use_per_device'] = split # Tensor-parallelism if shared.args.enable_tp: load_params['tensor_p'] = True load_params['tp_backend'] = shared.args.tp_backend # Load vision and draft before the main model so autosplit # accounts for their VRAM usage. # Load vision model component (ExLlamaV3 native) vision_model = None if "vision_config" in config.config_dict: logger.info("Vision component detected in model config. Attempting to load...") try: vision_model = Model.from_config(config, component="vision") vision_model.load(progressbar=True) logger.info("Vision model loaded successfully.") except Exception as e: logger.warning(f"Vision model loading failed (multimodal disabled): {e}") else: logger.info("No vision component in model config. Skipping multimodal setup.") # Initialize draft model for speculative decoding draft_model = None draft_cache = None if shared.args.model_draft and shared.args.model_draft.lower() not in ["", "none"]: logger.info(f"Loading draft model for speculative decoding: {shared.args.model_draft}") draft_path = Path(shared.args.model_draft) if not draft_path.is_dir(): draft_path = Path(f'{shared.args.model_dir}') / Path(shared.args.model_draft) if not draft_path.is_dir(): logger.warning(f"Draft model not found at {draft_path}, speculative decoding disabled.") else: draft_config = Config.from_directory(str(draft_path)) draft_model = Model.from_config(draft_config) draft_cache = Cache(draft_model, max_num_tokens=max_tokens, layer_type=layer_type, **cache_kwargs) draft_load_params = {'progressbar': True} if split: draft_load_params['use_per_device'] = split draft_model.load(**draft_load_params) logger.info(f"Draft model loaded successfully. Max speculative tokens: {shared.args.draft_max}") # Load main model last model.load(**load_params) tokenizer = Tokenizer.from_config(config) generator = Generator( model=model, cache=cache, tokenizer=tokenizer, draft_model=draft_model, draft_cache=draft_cache, num_draft_tokens=shared.args.draft_max if draft_model is not None else 0, ) result = cls() result.model = model result.cache = cache result.tokenizer = tokenizer result.generator = generator result.parallel_generator = ConcurrentGenerator(generator) result.config = config result.max_tokens = max_tokens result.vision_model = vision_model result.draft_model = draft_model result.draft_cache = draft_cache return result, result def is_multimodal(self) -> bool: return hasattr(self, 'vision_model') and self.vision_model is not None def _process_images_for_generation(self, prompt: str, state: dict) -> Tuple[str, List[Any]]: # Collect images from various sources using shared utilities pil_images = [] # From webui image_attachments (preferred format) if 'image_attachments' in state and state['image_attachments']: pil_images.extend(convert_image_attachments_to_pil(state['image_attachments'])) # From OpenAI API raw_images elif 'raw_images' in state and state['raw_images']: pil_images.extend(state['raw_images']) # From OpenAI API messages format elif 'messages' in state and state['messages']: pil_images.extend(convert_openai_messages_to_images(state['messages'])) if not pil_images: return prompt, [] # ExLlamaV3-specific: Generate embeddings try: # Use pre-computed embeddings if available (proper MMEmbedding lifetime) if 'image_embeddings' in state and state['image_embeddings']: # Use existing embeddings - this preserves MMEmbedding lifetime image_embeddings = state['image_embeddings'] else: # Do not reset the cache/allocator index; it causes token ID conflicts during generation. logger.info(f"Processing {len(pil_images)} image(s) with ExLlamaV3 vision model") image_embeddings = [ self.vision_model.get_image_embeddings(tokenizer=self.tokenizer, image=img) for img in pil_images ] # ExLlamaV3-specific: Handle prompt processing with placeholders placeholders = [ie.text_alias for ie in image_embeddings] if '<__media__>' in prompt: # Web chat: Replace <__media__> placeholders for alias in placeholders: prompt = prompt.replace('<__media__>', alias, 1) logger.info(f"Replaced {len(placeholders)} <__media__> placeholder(s)") else: # API: Prepend embedding aliases combined_placeholders = "\n".join(placeholders) prompt = combined_placeholders + "\n" + prompt logger.info(f"Prepended {len(placeholders)} embedding(s) to prompt") return prompt, image_embeddings except Exception as e: logger.error(f"Failed to process images: {e}") return prompt, [] def generate_with_streaming(self, prompt, state): if shared.is_multimodal: # Process images and modify prompt (ExLlamaV3-specific) prompt, image_embeddings = self._process_images_for_generation(prompt, state) else: image_embeddings = [] # Greedy decoding is a special case if state['temperature'] == 0: sampler = CustomSampler([SS_Argmax()]) else: # 1. Create a list of all active, unordered samplers unordered_samplers = [] # Penalties penalty_range = state['repetition_penalty_range'] if penalty_range <= 0: penalty_range = int(10e7) # Use large number for "full context" rep_decay = 0 # Not a configurable parameter # Add penalty samplers if they are active if state['repetition_penalty'] != 1.0: unordered_samplers.append(SS_RepP(state['repetition_penalty'], penalty_range, rep_decay)) if state['presence_penalty'] != 0.0 or state['frequency_penalty'] != 0.0: unordered_samplers.append(SS_PresFreqP(state['presence_penalty'], state['frequency_penalty'], penalty_range, rep_decay)) # Standard samplers if state['top_k'] > 0: unordered_samplers.append(SS_TopK(state['top_k'])) if state['top_p'] < 1.0: unordered_samplers.append(SS_TopP(state['top_p'])) if state['min_p'] > 0.0: unordered_samplers.append(SS_MinP(state['min_p'])) # Temperature (SS_NoOp is returned if temp is 1.0) unordered_samplers.append(SS_Temperature(state['temperature'])) # 2. Define the mapping from class names to the priority list keys class_name_to_nickname = { 'SS_RepP': 'repetition_penalty', 'SS_PresFreqP': 'presence_frequency_penalty', 'SS_TopK': 'top_k', 'SS_TopP': 'top_p', 'SS_MinP': 'min_p', 'SS_Temperature': 'temperature', } # 3. Get the priority list and handle temperature_last default_priority = ['repetition_penalty', 'presence_frequency_penalty', 'top_k', 'top_p', 'min_p', 'temperature'] sampler_priority = list(state.get('sampler_priority') or default_priority) if state['temperature_last'] and 'temperature' in sampler_priority: sampler_priority.append(sampler_priority.pop(sampler_priority.index('temperature'))) # The preset system uses separate 'presence_penalty' and # 'frequency_penalty', but ExLlamaV3 has a single combined # SS_PresFreqP sampler. Normalize to the combined name. sampler_priority = ['presence_frequency_penalty' if x in ('presence_penalty', 'frequency_penalty') else x for x in sampler_priority] # 4. Sort the unordered list based on the priority list def custom_sort_key(sampler_obj): class_name = sampler_obj.__class__.__name__ nickname = class_name_to_nickname.get(class_name) if nickname and nickname in sampler_priority: return sampler_priority.index(nickname) return -1 ordered_samplers = sorted(unordered_samplers, key=custom_sort_key) # 5. Add the final sampling stage and build the sampler if state.get('adaptive_target', 0) > 0: ordered_samplers.append(SS_AdaptiveP(state['adaptive_target'], state['adaptive_decay'])) else: ordered_samplers.append(SS_Sample()) sampler = CustomSampler(ordered_samplers) # Encode prompt with embeddings (ExLlamaV3-specific) input_ids = self.tokenizer.encode( prompt, add_bos=state['add_bos_token'], encode_special_tokens=True, embeddings=image_embeddings, ) input_ids = input_ids[:, -get_max_prompt_length(state):] self._last_prompt_token_count = input_ids.shape[-1] # Determine max_new_tokens if state['auto_max_new_tokens']: max_new_tokens = state['truncation_length'] - self._last_prompt_token_count else: max_new_tokens = state['max_new_tokens'] # Use full EOS token list from config (may contain multiple IDs) stop_conditions = [] if not state['ban_eos_token']: for eos_id in self.config.eos_token_id_list: if eos_id is not None: stop_conditions.append(eos_id) # Build filters for logit_bias (OpenAI API) filters = [] logit_bias = state.get('logit_bias') if logit_bias: filters.append(LogitBiasFilter(self.tokenizer, logit_bias)) # Logprobs support (OpenAI API) logprobs = state.get('logprobs', 0) or 0 return_top_tokens = logprobs if logprobs > 0 else 0 seed = state.get('seed', -1) job = Job( input_ids=input_ids, max_new_tokens=max_new_tokens, decode_special_tokens=not state['skip_special_tokens'], embeddings=image_embeddings if image_embeddings else None, sampler=sampler, seed=seed if seed >= 0 else None, stop_conditions=stop_conditions if stop_conditions else None, filters=filters if filters else None, return_top_tokens=return_top_tokens, return_probs=return_top_tokens > 0, ) # Stream generation response_text = "" stop_event = state.get('stop_event') self.last_completion_probabilities = [] result_queue = self.parallel_generator.submit(job) try: while True: if shared.stop_everything or (stop_event and stop_event.is_set()): break try: result = result_queue.get(timeout=0.1) except queue.Empty: continue if result is None or result.get("eos"): # Capture logprobs from the final eos result too if result is not None and return_top_tokens > 0: self._capture_logprobs(result) break chunk = result.get("text", "") # Capture logprobs from streaming results if return_top_tokens > 0: self._capture_logprobs(result) if chunk: response_text += chunk yield response_text finally: self.parallel_generator.cancel(job) def _capture_logprobs(self, result): top_k_tokens = result.get("top_k_tokens") top_k_probs = result.get("top_k_probs") if top_k_tokens is None or top_k_probs is None: return id_to_piece = self.tokenizer.get_id_to_piece_list(True) # top_k_tokens shape: (batch, seq_len, k), top_k_probs same for seq_idx in range(top_k_tokens.shape[1]): entry = {"top_logprobs": []} for k_idx in range(top_k_tokens.shape[2]): token_id = top_k_tokens[0, seq_idx, k_idx].item() prob = top_k_probs[0, seq_idx, k_idx].item() token_str = id_to_piece[token_id] if token_id < len(id_to_piece) else f"<{token_id}>" logprob = math.log(prob) if prob > 0 else float("-inf") entry["top_logprobs"].append({"token": token_str, "logprob": logprob}) self.last_completion_probabilities.append(entry) def generate(self, prompt, state): output = "" for chunk in self.generate_with_streaming(prompt, state): output = chunk return output def get_logits(self, token_ids, **kwargs): # Initialize a single params dictionary that will be updated in-place params = { "cache": self.cache, "reconstruct": False, "attn_mode": "flash_attn", "batch_shape": (1, self.max_tokens), "past_len": 0 } params.update(kwargs) # Process prefix tokens to fill the cache and generate recurrent state if token_ids.shape[-1] > 1: prefix_ids = token_ids[:, :-1] # This forward call updates the 'params' dict with the recurrent state self.model.forward( input_ids=prefix_ids, params=params ) # Update past_len for the next call params["past_len"] = prefix_ids.shape[-1] # Process the last token, now using the state-filled 'params' dict last_token_ids = token_ids[:, -1:] logits = self.model.forward( input_ids=last_token_ids, params=params ) return logits.float().cpu() def encode(self, string, **kwargs): add_bos = kwargs.pop('add_bos', True) return self.tokenizer.encode(string, add_bos=add_bos, **kwargs) def decode(self, ids, **kwargs): if isinstance(ids, torch.Tensor) and ids.dim() == 0: ids = ids.view(1) return self.tokenizer.decode(ids, **kwargs) @property def last_prompt_token_count(self): return getattr(self, '_last_prompt_token_count', 0) def unload(self): logger.info("Unloading ExLlamaV3 model components...") if hasattr(self, 'parallel_generator') and self.parallel_generator is not None: try: self.parallel_generator.stop() except Exception as e: logger.warning(f"Error stopping parallel generator: {e}") self.parallel_generator = None if hasattr(self, 'vision_model') and self.vision_model is not None: try: del self.vision_model except Exception as e: logger.warning(f"Error unloading vision model: {e}") self.vision_model = None if hasattr(self, 'draft_model') and self.draft_model is not None: try: self.draft_model.unload() del self.draft_model except Exception as e: logger.warning(f"Error unloading draft model: {e}") self.draft_model = None if hasattr(self, 'draft_cache') and self.draft_cache is not None: self.draft_cache = None if hasattr(self, 'model') and self.model is not None: try: self.model.unload() del self.model except Exception as e: logger.warning(f"Error unloading main model: {e}") self.model = None if hasattr(self, 'cache') and self.cache is not None: self.cache = None if hasattr(self, 'generator') and self.generator is not None: self.generator = None if hasattr(self, 'tokenizer') and self.tokenizer is not None: self.tokenizer = None
--- +++ @@ -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 @@ return result, result def is_multimodal(self) -> bool: + """Check if this model supports multimodal input.""" return hasattr(self, 'vision_model') and self.vision_model is not None def _process_images_for_generation(self, prompt: str, state: dict) -> Tuple[str, List[Any]]: + """ + Process all possible image inputs and return modified prompt + embeddings. + Returns: (processed_prompt, image_embeddings) + """ # Collect images from various sources using shared utilities pil_images = [] @@ -308,6 +314,9 @@ return prompt, [] def generate_with_streaming(self, prompt, state): + """ + Generate text with streaming using native ExLlamaV3 API + """ if shared.is_multimodal: # Process images and modify prompt (ExLlamaV3-specific) @@ -466,6 +475,7 @@ self.parallel_generator.cancel(job) def _capture_logprobs(self, result): + """Convert ExLlamav3 top-k token data to the shared logprobs format.""" top_k_tokens = result.get("top_k_tokens") top_k_probs = result.get("top_k_probs") if top_k_tokens is None or top_k_probs is None: @@ -491,6 +501,10 @@ return output def get_logits(self, token_ids, **kwargs): + """ + Process a batch of token_ids and return the logits for the last token. + This will reset and overwrite the model's cache. + """ # Initialize a single params dictionary that will be updated in-place params = { "cache": self.cache, @@ -581,4 +595,4 @@ self.generator = None if hasattr(self, 'tokenizer') and self.tokenizer is not None: - self.tokenizer = None+ self.tokenizer = None
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://achinghead.com) # All changes Copyright 2011-2014 The Python Markdown Project # License: [BSD](https://opensource.org/licenses/bsd-license.php) from __future__ import annotations import re import xml.etree.ElementTree as etree from typing import TYPE_CHECKING from markdown import Extension from markdown.blockparser import BlockParser from markdown.blockprocessors import ( ListIndentProcessor, OListProcessor, ParagraphProcessor ) if TYPE_CHECKING: # pragma: no cover from markdown import blockparser # The min. number of added leading spaces needed to start a nested list MIN_NESTED_LIST_INDENT = 2 assert MIN_NESTED_LIST_INDENT > 1, "'MIN_NESTED_LIST_INDENT' must be > 1" class SaneListIndentProcessor(ListIndentProcessor): def __init__(self, *args): super().__init__(*args) self.INDENT_RE = re.compile(r'^(([ ])+)') def test(self, parent: etree.Element, block: str) -> bool: return block.startswith(' ' * MIN_NESTED_LIST_INDENT) and \ not self.parser.state.isstate('detabbed') and \ (parent.tag in self.ITEM_TYPES or (len(parent) and parent[-1] is not None and (parent[-1].tag in self.LIST_TYPES))) def get_level(self, parent: etree.Element, block: str) -> tuple[int, etree.Element]: # Get indent level m = self.INDENT_RE.match(block) if m: indent_level = len(m.group(1)) / MIN_NESTED_LIST_INDENT else: indent_level = 0 if self.parser.state.isstate('list'): # We're in a tight-list - so we already are at correct parent. level = 1 else: # We're in a loose-list - so we need to find parent. level = 0 # Step through children of tree to find matching indent level. while indent_level > level: child = self.lastChild(parent) if child is not None and (child.tag in self.LIST_TYPES or child.tag in self.ITEM_TYPES): if child.tag in self.LIST_TYPES: level += 1 parent = child else: # No more child levels. If we're short of `indent_level`, # we have a code block. So we stop here. break return level, parent def detab(self, text: str, length: int | None = None) -> tuple[str, str]: if length is None: length = MIN_NESTED_LIST_INDENT newtext = [] lines = text.split('\n') for line in lines: if line.startswith(' ' * length): newtext.append(line[length:]) elif not line.strip(): newtext.append('') else: break return '\n'.join(newtext), '\n'.join(lines[len(newtext):]) def looseDetab(self, text: str, level: int = 1) -> str: lines = text.split('\n') for i in range(len(lines)): if lines[i].startswith(' ' * MIN_NESTED_LIST_INDENT * level): lines[i] = lines[i][MIN_NESTED_LIST_INDENT * level:] return '\n'.join(lines) class SaneOListProcessor(OListProcessor): SIBLING_TAGS = ['ol'] """ Exclude `ul` from list of siblings. """ LAZY_OL = False """ Disable lazy list behavior. """ def __init__(self, parser: blockparser.BlockParser): super().__init__(parser) max_list_start_indent = self.tab_length # Detect an item (e.g., `1. item`) self.RE = re.compile(r'^[ ]{0,%d}[\*_]{0,2}\d+\.[ ]+(.*)' % max_list_start_indent) # Detect items on secondary lines. they can be of either list type. self.CHILD_RE = re.compile(r'^[ ]{0,%d}([\*_]{0,2})((\d+\.))[ ]+(.*)' % (MIN_NESTED_LIST_INDENT - 1)) # Detect indented (nested) items of either type self.INDENT_RE = re.compile(r'^[ ]{%d,%d}[\*_]{0,2}((\d+\.)|[*+-])[ ]+.*' % (MIN_NESTED_LIST_INDENT, self.tab_length * 2)) def run(self, parent: etree.Element, blocks: list[str]) -> None: # Check for multiple items in one block. items = self.get_items(blocks.pop(0)) sibling = self.lastChild(parent) if sibling is not None and sibling.tag in self.SIBLING_TAGS: # Previous block was a list item, so set that as parent lst = sibling # make sure previous item is in a `p` - if the item has text, # then it isn't in a `p` if lst[-1].text: # since it's possible there are other children for this # sibling, we can't just `SubElement` the `p`, we need to # insert it as the first item. p = etree.Element('p') p.text = lst[-1].text lst[-1].text = '' lst[-1].insert(0, p) # if the last item has a tail, then the tail needs to be put in a `p` # likely only when a header is not followed by a blank line lch = self.lastChild(lst[-1]) if lch is not None and lch.tail: p = etree.SubElement(lst[-1], 'p') p.text = lch.tail.lstrip() lch.tail = '' # parse first block differently as it gets wrapped in a `p`. li = etree.SubElement(lst, 'li') self.parser.state.set('looselist') firstitem = items.pop(0) self.parser.parseBlocks(li, [firstitem]) self.parser.state.reset() elif parent.tag in ['ol', 'ul']: # this catches the edge case of a multi-item indented list whose # first item is in a blank parent-list item: # * * subitem1 # * subitem2 # see also `ListIndentProcessor` lst = parent else: # This is a new list so create parent with appropriate tag. lst = etree.SubElement(parent, self.TAG) # Check if a custom start integer is set if not self.LAZY_OL and self.STARTSWITH != '1': lst.attrib['start'] = self.STARTSWITH self.parser.state.set('list') # Loop through items in block, recursively parsing each with the # appropriate parent. for item in items: if item.startswith(" " * MIN_NESTED_LIST_INDENT): # Item is indented. Parse with last item as parent self.parser.parseBlocks(lst[-1], [item]) else: # New item. Create `li` and parse with it as parent li = etree.SubElement(lst, 'li') self.parser.parseBlocks(li, [item]) self.parser.state.reset() def looseDetab(self, text: str, indent_length: int, level: int = 1) -> str: lines = text.split('\n') for i in range(len(lines)): if lines[i].startswith(' ' * indent_length * level): lines[i] = lines[i][indent_length * level:] return '\n'.join(lines) def get_items(self, block: str) -> list[str]: # If first level of list is indented, remove that indentation if (indent_len := len(block) - len(block.lstrip())) > 0: block = self.looseDetab(block, indent_len) items = [] for line in block.split('\n'): m = self.CHILD_RE.match(line) if m: # This is a new list item # Check first item for the start index if not items: # Detect the integer value of first list item INTEGER_RE = re.compile(r'(\d+)') self.STARTSWITH = INTEGER_RE.match(m.group(2)).group() # Append to the list items.append(m.group(1) + m.group(4)) elif self.INDENT_RE.match(line): # This is an indented (possibly nested) item. if items[-1].startswith(' ' * MIN_NESTED_LIST_INDENT): # Previous item was indented. Append to that item. items[-1] = '{}\n{}'.format(items[-1], line) else: items.append(line) else: # This is another line of previous item. Append to that item. items[-1] = '{}\n{}'.format(items[-1], line) return items class SaneUListProcessor(SaneOListProcessor): TAG: str = 'ul' SIBLING_TAGS = ['ul'] """ Exclude `ol` from list of siblings. """ def __init__(self, parser: blockparser.BlockParser): super().__init__(parser) # Detect an item (e.g., `- item` or `+ item` or `* item`). max_list_start_indent = self.tab_length self.RE = re.compile(r'^[ ]{0,%d}[*+-][ ]+(.*)' % max_list_start_indent) self.CHILD_RE = re.compile(r'^[ ]{0,%d}(([*+-]))[ ]+(.*)' % (MIN_NESTED_LIST_INDENT - 1)) def get_items(self, block: str) -> list[str]: # If first level of list is indented, remove that indentation if (indent_len := len(block) - len(block.lstrip())) > 0: block = self.looseDetab(block, indent_len) items = [] for line in block.split('\n'): m = self.CHILD_RE.match(line) if m: # Append to the list items.append(m.group(3)) elif self.INDENT_RE.match(line): # This is an indented (possibly nested) item. if items[-1].startswith(' ' * MIN_NESTED_LIST_INDENT): # Previous item was indented. Append to that item. items[-1] = '{}\n{}'.format(items[-1], line) else: items.append(line) else: # This is another line of previous item. Append to that item. items[-1] = '{}\n{}'.format(items[-1], line) return items class SaneParagraphProcessor(ParagraphProcessor): def __init__(self, parser: BlockParser): super().__init__(parser) max_list_start_indent = self.tab_length self.LIST_RE = re.compile(r"\s{2}\n(\s{0,%d}[\d+*-])" % max_list_start_indent) def run(self, parent: etree.Element, blocks: list[str]) -> None: block = blocks.pop(0) if block.strip(): # Not a blank block. Add to parent, otherwise throw it away. if self.parser.state.isstate('list'): # The parent is a tight-list. # # Check for any children. This will likely only happen in a # tight-list when a header isn't followed by a blank line. # For example: # # * # Header # Line 2 of list item - not part of header. sibling = self.lastChild(parent) if sibling is not None: # Insert after sibling. if sibling.tail: sibling.tail = '{}\n{}'.format(sibling.tail, block) else: sibling.tail = '\n%s' % block else: # Append to parent.text if parent.text: parent.text = '{}\n{}'.format(parent.text, block) else: parent.text = block.lstrip() else: # Check if paragraph contains a list next_list_block = None if list_match := self.LIST_RE.search(block): list_start = list_match.end() - len(list_match.group(1)) next_list_block = block[list_start:] block = block[:list_start] # Create a regular paragraph p = etree.SubElement(parent, 'p') p.text = block.lstrip() # If a list was found, parse its block separately with the paragraph as the parent if next_list_block: self.parser.parseBlocks(p, [next_list_block]) class SaneListExtension(Extension): def extendMarkdown(self, md): md.parser.blockprocessors.register(SaneListIndentProcessor(md.parser), 'indent', 90) md.parser.blockprocessors.register(SaneOListProcessor(md.parser), 'olist', 40) md.parser.blockprocessors.register(SaneUListProcessor(md.parser), 'ulist', 30) md.parser.blockprocessors.register(SaneParagraphProcessor(md.parser), 'paragraph', 10) # Disable uncommon indented codeblocks (as opposed to fenced codeblocks delimited by "```") md.parser.blockprocessors.deregister('code') def makeExtension(**kwargs): # pragma: no cover return SaneListExtension(**kwargs)
--- +++ @@ -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 of list items. + + Example + + * a list item + process this part + + or this part + + """ def __init__(self, *args): super().__init__(*args) @@ -49,6 +62,7 @@ self.LIST_TYPES))) def get_level(self, parent: etree.Element, block: str) -> tuple[int, etree.Element]: + """ Get level of indentation based on list level. """ # Get indent level m = self.INDENT_RE.match(block) if m: @@ -75,6 +89,7 @@ return level, parent def detab(self, text: str, length: int | None = None) -> tuple[str, str]: + """ Remove a tab from the front of each line of the given text. """ if length is None: length = MIN_NESTED_LIST_INDENT newtext = [] @@ -89,6 +104,7 @@ return '\n'.join(newtext), '\n'.join(lines[len(newtext):]) def looseDetab(self, text: str, level: int = 1) -> str: + """ Remove indentation from front of lines but allowing dedented lines. """ lines = text.split('\n') for i in range(len(lines)): if lines[i].startswith(' ' * MIN_NESTED_LIST_INDENT * level): @@ -97,6 +113,7 @@ class SaneOListProcessor(OListProcessor): + """ Override `SIBLING_TAGS` to not include `ul` and set `LAZY_OL` to `False`. """ SIBLING_TAGS = ['ol'] """ Exclude `ul` from list of siblings. """ @@ -174,6 +191,7 @@ self.parser.state.reset() def looseDetab(self, text: str, indent_length: int, level: int = 1) -> str: + """ Remove indentation from front of lines but allowing dedented lines. """ lines = text.split('\n') for i in range(len(lines)): if lines[i].startswith(' ' * indent_length * level): @@ -181,6 +199,7 @@ return '\n'.join(lines) def get_items(self, block: str) -> list[str]: + """ Break a block into list items. """ # If first level of list is indented, remove that indentation if (indent_len := len(block) - len(block.lstrip())) > 0: block = self.looseDetab(block, indent_len) @@ -210,6 +229,7 @@ class SaneUListProcessor(SaneOListProcessor): + """ Override `SIBLING_TAGS` to not include `ol`. """ TAG: str = 'ul' SIBLING_TAGS = ['ul'] @@ -223,6 +243,7 @@ self.CHILD_RE = re.compile(r'^[ ]{0,%d}(([*+-]))[ ]+(.*)' % (MIN_NESTED_LIST_INDENT - 1)) def get_items(self, block: str) -> list[str]: + """ Break a block into list items. """ # If first level of list is indented, remove that indentation if (indent_len := len(block) - len(block.lstrip())) > 0: block = self.looseDetab(block, indent_len) @@ -246,6 +267,7 @@ class SaneParagraphProcessor(ParagraphProcessor): + """ Process Paragraph blocks. """ def __init__(self, parser: BlockParser): super().__init__(parser) @@ -296,8 +318,10 @@ class SaneListExtension(Extension): + """ Add sane lists to Markdown. """ def extendMarkdown(self, md): + """ Override existing Processors. """ md.parser.blockprocessors.register(SaneListIndentProcessor(md.parser), 'indent', 90) md.parser.blockprocessors.register(SaneOListProcessor(md.parser), 'olist', 40) md.parser.blockprocessors.register(SaneUListProcessor(md.parser), 'ulist', 30) @@ -308,4 +332,4 @@ def makeExtension(**kwargs): # pragma: no cover - return SaneListExtension(**kwargs)+ return SaneListExtension(**kwargs)
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_save_timer = None _auto_save_lock = threading.Lock() _last_interface_state = None _last_preset = None _last_extensions = None _last_show_controls = None _last_theme_state = None with open(Path(__file__).resolve().parent / '../css/NotoSans/stylesheet.css', 'r', encoding='utf-8') as f: css = f.read() with open(Path(__file__).resolve().parent / '../css/main.css', 'r', encoding='utf-8') as f: css += f.read() with open(Path(__file__).resolve().parent / '../css/katex/katex.min.css', 'r', encoding='utf-8') as f: css += f.read() with open(Path(__file__).resolve().parent / '../css/highlightjs/highlightjs-copy.min.css', 'r', encoding='utf-8') as f: css += f.read() with open(Path(__file__).resolve().parent / '../js/main.js', 'r', encoding='utf-8') as f: js = f.read() with open(Path(__file__).resolve().parent / '../js/global_scope_js.js', 'r', encoding='utf-8') as f: global_scope_js = f.read() with open(Path(__file__).resolve().parent / '../js/save_files.js', 'r', encoding='utf-8') as f: save_files_js = f.read() with open(Path(__file__).resolve().parent / '../js/switch_tabs.js', 'r', encoding='utf-8') as f: switch_tabs_js = f.read() with open(Path(__file__).resolve().parent / '../js/show_controls.js', 'r', encoding='utf-8') as f: show_controls_js = f.read() with open(Path(__file__).resolve().parent / '../js/update_big_picture.js', 'r', encoding='utf-8') as f: update_big_picture_js = f.read() with open(Path(__file__).resolve().parent / '../js/dark_theme.js', 'r', encoding='utf-8') as f: dark_theme_js = f.read() refresh_symbol = '🔄' delete_symbol = '🗑️' save_symbol = '💾' theme = gr.themes.Default( font=['Noto Sans', 'Helvetica', 'ui-sans-serif', 'system-ui', 'sans-serif'], font_mono=['IBM Plex Mono', 'ui-monospace', 'Consolas', 'monospace'], ).set( border_color_primary='#c5c5d2', button_large_padding='6px 12px', body_text_color_subdued='#484848', background_fill_secondary='#eaeaea', background_fill_primary='var(--neutral-50)', body_background_fill="white", block_background_fill="#f4f4f4", body_text_color="#333", button_secondary_background_fill="#f4f4f4", button_secondary_border_color="var(--border-color-primary)" ) if not shared.args.old_colors: theme = theme.set( # General Colors border_color_primary='#c5c5d2', body_text_color_subdued='#484848', background_fill_secondary='#eaeaea', background_fill_secondary_dark='var(--selected-item-color-dark, #282930)', background_fill_primary='var(--neutral-50)', background_fill_primary_dark='var(--darker-gray, #1C1C1D)', body_background_fill="white", block_background_fill="transparent", body_text_color='rgb(64, 64, 64)', button_secondary_background_fill="white", button_secondary_border_color="var(--border-color-primary)", input_shadow="none", button_shadow_hover="none", # Dark Mode Colors input_background_fill_dark='var(--darker-gray, #1C1C1D)', checkbox_background_color_dark='var(--darker-gray, #1C1C1D)', block_background_fill_dark='transparent', block_border_color_dark='transparent', input_border_color_dark='var(--border-color-dark, #525252)', input_border_color_focus_dark='var(--border-color-dark, #525252)', checkbox_border_color_dark='var(--border-color-dark, #525252)', border_color_primary_dark='var(--border-color-dark, #525252)', button_secondary_border_color_dark='var(--border-color-dark, #525252)', body_background_fill_dark='var(--dark-gray, #212125)', button_primary_background_fill_dark='transparent', button_secondary_background_fill_dark='transparent', checkbox_label_background_fill_dark='transparent', button_cancel_background_fill_dark='transparent', button_secondary_background_fill_hover_dark='var(--selected-item-color-dark, #282930)', checkbox_label_background_fill_hover_dark='var(--selected-item-color-dark, #282930)', table_even_background_fill_dark='var(--darker-gray, #1C1C1D)', table_odd_background_fill_dark='var(--selected-item-color-dark, #282930)', code_background_fill_dark='var(--darker-gray, #1C1C1D)', # Shadows and Radius checkbox_label_shadow='none', block_shadow='none', block_shadow_dark='none', input_shadow_focus='none', input_shadow_focus_dark='none', button_large_radius='0.375rem', button_large_padding='6px 12px', input_radius='0.375rem', block_radius='0', ) if (shared.user_data_dir / "notification.mp3").exists(): audio_notification_js = "document.querySelector('#audio_notification audio')?.play();" else: audio_notification_js = "" def list_model_elements(): from modules.loaders import list_model_elements return list_model_elements() def list_interface_input_elements(): elements = [ 'temperature', 'dynatemp_low', 'dynatemp_high', 'dynatemp_exponent', 'smoothing_factor', 'smoothing_curve', 'min_p', 'top_p', 'top_k', 'typical_p', 'xtc_threshold', 'xtc_probability', 'epsilon_cutoff', 'eta_cutoff', 'tfs', 'top_a', 'top_n_sigma', 'adaptive_target', 'adaptive_decay', 'dry_multiplier', 'dry_allowed_length', 'dry_base', 'repetition_penalty', 'frequency_penalty', 'presence_penalty', 'encoder_repetition_penalty', 'no_repeat_ngram_size', 'repetition_penalty_range', 'penalty_alpha', 'guidance_scale', 'mirostat_mode', 'mirostat_tau', 'mirostat_eta', 'max_new_tokens', 'prompt_lookup_num_tokens', 'max_tokens_second', 'do_sample', 'dynamic_temperature', 'temperature_last', 'auto_max_new_tokens', 'ban_eos_token', 'add_bos_token', 'enable_thinking', 'reasoning_effort', 'skip_special_tokens', 'stream', 'static_cache', 'truncation_length', 'seed', 'sampler_priority', 'custom_stopping_strings', 'custom_token_bans', 'negative_prompt', 'dry_sequence_breakers', 'grammar_string', 'navigate_message_index', 'navigate_direction', 'navigate_message_role', 'edit_message_index', 'edit_message_text', 'edit_message_role', 'branch_index', 'enable_web_search', 'web_search_pages', ] # Chat elements elements += [ 'history', 'search_chat', 'unique_id', 'textbox', 'start_with', 'selected_tools', 'mode', 'chat_style', 'chat-instruct_command', 'character_menu', 'user_menu', 'name2', 'context', 'greeting', 'name1', 'user_bio', 'custom_system_message', 'instruction_template_str', 'chat_template_str', ] # Notebook/default elements elements += [ 'textbox-default', 'textbox-notebook', 'prompt_menu-default', 'prompt_menu-notebook', 'output_textbox', ] # Model elements elements += list_model_elements() # Other elements elements += [ 'show_two_notebook_columns', 'paste_to_attachment', 'include_past_attachments', ] if not shared.args.portable: # Image generation elements elements += [ 'image_prompt', 'image_neg_prompt', 'image_width', 'image_height', 'image_aspect_ratio', 'image_steps', 'image_cfg_scale', 'image_seed', 'image_batch_size', 'image_batch_count', 'image_llm_variations', 'image_llm_variations_prompt', 'image_model_menu', 'image_dtype', 'image_attn_backend', 'image_compile', 'image_cpu_offload', 'image_quant', ] return elements def gather_interface_values(*args): interface_elements = list_interface_input_elements() output = {} for element, value in zip(interface_elements, args): output[element] = value if not shared.args.multi_user: shared.persistent_interface_state = output # Remove the chat input, as it gets cleared after this function call shared.persistent_interface_state.pop('textbox') # Prevent history loss if backend is restarted but UI is not refreshed if (output['history'] is None or (len(output['history'].get('visible', [])) == 0 and len(output['history'].get('internal', [])) == 0)) and output['unique_id'] is not None: output['history'] = load_history(output['unique_id'], output['character_menu'], output['mode']) return output def apply_interface_values(state, use_persistent=False): if use_persistent: state = shared.persistent_interface_state if 'textbox-default' in state and 'prompt_menu-default' in state: state.pop('prompt_menu-default') if 'textbox-notebook' in state and 'prompt_menu-notebook' in state: state.pop('prompt_menu-notebook') elements = list_interface_input_elements() if len(state) == 0: return [gr.update() for k in elements] # Dummy, do nothing else: return [state[k] if k in state else gr.update() for k in elements] def save_settings(state, preset, extensions_list, show_controls, theme_state, manual_save=False): output = copy.deepcopy(shared.settings) exclude = [] for k in state: if k in shared.settings and k not in exclude: output[k] = state[k] if preset: output['preset'] = preset output['prompt-notebook'] = state['prompt_menu-default'] if state['show_two_notebook_columns'] else state['prompt_menu-notebook'] if state.get('character_menu'): output['character'] = state['character_menu'] if state.get('user_menu'): output['user'] = state['user_menu'] output['seed'] = int(output['seed']) output['custom_stopping_strings'] = output.get('custom_stopping_strings') or '' output['custom_token_bans'] = output.get('custom_token_bans') or '' output['show_controls'] = show_controls output['dark_theme'] = True if theme_state == 'dark' else False output.pop('instruction_template_str') output.pop('truncation_length') # Handle extensions and extension parameters if manual_save: # Save current extensions and their parameter values output['default_extensions'] = extensions_list for extension_name in extensions_list: extension = getattr(extensions, extension_name, None) if extension: extension = extension.script if hasattr(extension, 'params'): params = getattr(extension, 'params') for param in params: _id = f"{extension_name}-{param}" # Only save if different from default value if param not in shared.default_settings or params[param] != shared.default_settings[param]: output[_id] = params[param] else: # Preserve existing extensions and extension parameters during autosave settings_path = shared.user_data_dir / 'settings.yaml' if settings_path.exists(): try: with open(settings_path, 'r', encoding='utf-8') as f: existing_settings = yaml.safe_load(f.read()) or {} # Preserve default_extensions if 'default_extensions' in existing_settings: output['default_extensions'] = existing_settings['default_extensions'] # Preserve extension parameter values for key, value in existing_settings.items(): if any(key.startswith(f"{ext_name}-") for ext_name in extensions_module.available_extensions): output[key] = value except Exception: pass # If we can't read the file, just don't modify extensions # Do not save unchanged settings for key in list(output.keys()): if key in shared.default_settings and output[key] == shared.default_settings[key]: output.pop(key) return yaml.dump(output, sort_keys=False, width=float("inf"), allow_unicode=True) def store_current_state_and_debounce(interface_state, preset, extensions, show_controls, theme_state): global _auto_save_timer, _last_interface_state, _last_preset, _last_extensions, _last_show_controls, _last_theme_state if shared.args.multi_user: return # Store the current state in global variables _last_interface_state = interface_state _last_preset = preset _last_extensions = extensions _last_show_controls = show_controls _last_theme_state = theme_state # Reset the debounce timer with _auto_save_lock: if _auto_save_timer is not None: _auto_save_timer.cancel() _auto_save_timer = threading.Timer(1.0, _perform_debounced_save) _auto_save_timer.start() def _perform_debounced_save(): global _auto_save_timer try: if _last_interface_state is not None: contents = save_settings(_last_interface_state, _last_preset, _last_extensions, _last_show_controls, _last_theme_state, manual_save=False) settings_path = shared.user_data_dir / 'settings.yaml' settings_path.parent.mkdir(exist_ok=True) with open(settings_path, 'w', encoding='utf-8') as f: f.write(contents) except Exception as e: print(f"Auto-save failed: {e}") finally: with _auto_save_lock: _auto_save_timer = None def setup_auto_save(): if shared.args.multi_user: return change_elements = [ # Chat tab (ui_chat.py) 'start_with', 'enable_web_search', 'web_search_pages', 'mode', 'chat_style', 'chat-instruct_command', 'character_menu', 'user_menu', 'name1', 'name2', 'context', 'greeting', 'user_bio', 'custom_system_message', 'chat_template_str', 'selected_tools', # Parameters tab (ui_parameters.py) - Generation parameters 'preset_menu', 'temperature', 'dynatemp_low', 'dynatemp_high', 'dynatemp_exponent', 'smoothing_factor', 'smoothing_curve', 'min_p', 'top_p', 'top_k', 'typical_p', 'xtc_threshold', 'xtc_probability', 'epsilon_cutoff', 'eta_cutoff', 'tfs', 'top_a', 'top_n_sigma', 'adaptive_target', 'adaptive_decay', 'dry_multiplier', 'dry_allowed_length', 'dry_base', 'repetition_penalty', 'frequency_penalty', 'presence_penalty', 'encoder_repetition_penalty', 'no_repeat_ngram_size', 'repetition_penalty_range', 'penalty_alpha', 'guidance_scale', 'mirostat_mode', 'mirostat_tau', 'mirostat_eta', 'max_new_tokens', 'prompt_lookup_num_tokens', 'max_tokens_second', 'do_sample', 'dynamic_temperature', 'temperature_last', 'auto_max_new_tokens', 'ban_eos_token', 'add_bos_token', 'enable_thinking', 'reasoning_effort', 'skip_special_tokens', 'stream', 'static_cache', 'seed', 'sampler_priority', 'custom_stopping_strings', 'custom_token_bans', 'negative_prompt', 'dry_sequence_breakers', 'grammar_string', # Default tab (ui_default.py) 'prompt_menu-default', # Notebook tab (ui_notebook.py) 'prompt_menu-notebook', # Session tab (ui_session.py) 'show_controls', 'theme_state', 'show_two_notebook_columns', 'paste_to_attachment', 'include_past_attachments', ] if not shared.args.portable: # Image generation tab (ui_image_generation.py) change_elements += [ 'image_prompt', 'image_neg_prompt', 'image_width', 'image_height', 'image_aspect_ratio', 'image_steps', 'image_cfg_scale', 'image_seed', 'image_batch_size', 'image_batch_count', 'image_llm_variations', 'image_llm_variations_prompt', 'image_model_menu', 'image_dtype', 'image_attn_backend', 'image_compile', 'image_cpu_offload', 'image_quant', ] for element_name in change_elements: if element_name in shared.gradio: shared.gradio[element_name].change( gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then( store_current_state_and_debounce, gradio('interface_state', 'preset_menu', 'extensions_menu', 'show_controls', 'theme_state'), None, show_progress=False) def create_refresh_button(refresh_component, refresh_method, refreshed_args, elem_class, interactive=True): def refresh(): refresh_method() args = refreshed_args() if callable(refreshed_args) else refreshed_args return gr.update(**(args or {})) refresh_button = gr.Button(refresh_symbol, elem_classes=elem_class, interactive=interactive) refresh_button.click( fn=lambda: {k: tuple(v) if type(k) is list else v for k, v in refresh().items()}, inputs=[], outputs=[refresh_component] ) return refresh_button
--- +++ @@ -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 if shared.args.multi_user: @@ -385,6 +386,7 @@ def _perform_debounced_save(): + """Actually perform the save using the stored state""" global _auto_save_timer try: @@ -402,6 +404,7 @@ def setup_auto_save(): + """Attach auto-save to key UI elements""" if shared.args.multi_user: return @@ -527,6 +530,9 @@ def create_refresh_button(refresh_component, refresh_method, refreshed_args, elem_class, interactive=True): + """ + Copied from https://github.com/AUTOMATIC1111/stable-diffusion-webui + """ def refresh(): refresh_method() args = refreshed_args() if callable(refreshed_args) else refreshed_args @@ -540,4 +546,4 @@ outputs=[refresh_component] ) - return refresh_button+ return refresh_button
https://raw.githubusercontent.com/oobabooga/text-generation-webui/HEAD/modules/ui.py