71 lines
2.2 KiB
Python
71 lines
2.2 KiB
Python
"""Common utilities shared between img2typ and solve scripts."""
|
|
|
|
import logging
|
|
import os
|
|
from pathlib import Path
|
|
|
|
from dotenv import load_dotenv
|
|
from rich.console import Console
|
|
from rich.logging import RichHandler
|
|
from rich.theme import Theme
|
|
|
|
console = Console(
|
|
theme=Theme({"info": "cyan", "warning": "yellow", "error": "bold red"})
|
|
)
|
|
|
|
SCRIPT_DIR = Path(__file__).parent
|
|
DATA_DIR = SCRIPT_DIR.parent / "data"
|
|
ENV_FILE = SCRIPT_DIR / ".env"
|
|
|
|
|
|
def setup_logging(name: str, verbose: bool) -> logging.Logger:
|
|
"""Setup logging with rich handler."""
|
|
level = logging.DEBUG if verbose else logging.INFO
|
|
logging.basicConfig(
|
|
level=level,
|
|
format="%(message)s",
|
|
datefmt="[%X]",
|
|
handlers=[RichHandler(console=console, rich_tracebacks=True)],
|
|
)
|
|
return logging.getLogger(name)
|
|
|
|
|
|
def load_env() -> dict[str, str]:
|
|
"""Load environment variables from .env file."""
|
|
if ENV_FILE.exists():
|
|
load_dotenv(ENV_FILE)
|
|
else:
|
|
console.print(f"[yellow]Warning: .env file not found at {ENV_FILE}[/yellow]")
|
|
|
|
api_endpoint = os.environ.get("IMG2TYP_API_ENDPOINT", "")
|
|
api_key = os.environ.get("IMG2TYP_API_KEY", "")
|
|
api_model = os.environ.get("IMG2TYP_MODEL", "qwen-vl-plus")
|
|
|
|
if not api_endpoint:
|
|
console.print("[yellow]Warning: IMG2TYP_API_ENDPOINT not set[/yellow]")
|
|
if not api_key:
|
|
console.print("[yellow]Warning: IMG2TYP_API_KEY not set[/yellow]")
|
|
|
|
return {"endpoint": api_endpoint, "key": api_key, "model": api_model}
|
|
|
|
|
|
def load_prompt(filename: str) -> str:
|
|
"""Load a prompt template from file."""
|
|
prompt_path = SCRIPT_DIR / filename
|
|
if not prompt_path.exists():
|
|
console.print(
|
|
f"[yellow]Warning: Prompt file not found at {prompt_path}[/yellow]"
|
|
)
|
|
return ""
|
|
return prompt_path.read_text(encoding="utf-8")
|
|
|
|
|
|
def find_attachments(question: str) -> list[str]:
|
|
"""Find all attachment files for a given question."""
|
|
attachments = []
|
|
question_prefix = question + "_"
|
|
for file_path in DATA_DIR.iterdir():
|
|
if file_path.is_file() and file_path.name.startswith(question_prefix):
|
|
attachments.append(file_path.name)
|
|
return sorted(attachments)
|