agent-iot / modules /paper_printer /paper_agent.py
ASown's picture
Consolidate project history under ASown
f368481
Raw History Blame Contribute Delete
9.91 kB
"""
Paper-printer agent for the Brother MFC-L3750CDW.
Request -> an image -> print on A4 paper (over IPP). The image comes from:
- a local image path,
- an http(s) image URL (downloaded),
- otherwise: generated from the text with Pollinations (free, keyless),
optionally translated to a clean English prompt via Groq if GROQ_API_KEY is set.
Self-contained: only needs requests + Pillow (+ paper_print.py here).
"""
from __future__ import annotations
import io
import os
import re
import shlex
import ssl
import sys
import urllib.parse
import urllib.request
from pathlib import Path
try:
sys.stdout.reconfigure(encoding="utf-8")
sys.stdin.reconfigure(encoding="utf-8") # read typed Vietnamese correctly
except Exception:
pass
import requests
from PIL import Image
import paper_print
import file_finder
IMG_DIR = Path(__file__).resolve().parent / "images"
IMG_DIR.mkdir(exist_ok=True)
IMG_EXT = (".png", ".jpg", ".jpeg", ".webp", ".bmp")
POLLI = "https://image.pollinations.ai/prompt/"
GROQ_KEY = os.getenv("GROQ_API_KEY", "")
TRANS_MODEL = os.getenv("OUTLINE_MODEL_NAME", "groq:openai/gpt-oss-120b").split(":", 1)[-1]
_SSL = ssl.create_default_context()
_UA = {"User-Agent": "paper-demo/1.0"}
def _slug(s: str) -> str:
return re.sub(r"[^a-z0-9]+", "_", s.lower()).strip("_")[:40] or "image"
def translate_to_prompt(request: str) -> str:
"""Best-effort VN/any -> short English image prompt via Groq; else pass through."""
if not GROQ_KEY:
return request
try:
r = requests.post(
"https://api.groq.com/openai/v1/chat/completions",
headers={"Authorization": f"Bearer {GROQ_KEY}"},
json={"model": TRANS_MODEL, "temperature": 0.3, "messages": [
{"role": "system", "content":
"Turn the user's request into a short English image-generation "
"prompt for a single clear subject on a plain background. "
"Reply with ONLY the prompt, no quotes."},
{"role": "user", "content": request}]},
timeout=30)
if r.ok:
return r.json()["choices"][0]["message"]["content"].strip() or request
except Exception:
pass
return request
def generate_image(prompt: str, dest: Path) -> Path:
url = (POLLI + urllib.parse.quote(prompt)
+ "?width=768&height=1024&nologo=true&model=flux")
data = urllib.request.urlopen(urllib.request.Request(url, headers=_UA),
timeout=90, context=_SSL).read()
if len(data) < 1000:
raise RuntimeError("image generator returned nothing")
dest.write_bytes(data)
return dest
def _download(url: str, dest: Path) -> Path:
data = urllib.request.urlopen(urllib.request.Request(url, headers=_UA),
timeout=60, context=_SSL).read()
Image.open(io.BytesIO(data)).convert("RGB").save(dest)
return dest
def _choose(matches: list[Path], interactive: bool) -> Path:
if len(matches) == 1 or not interactive:
return matches[0]
print(" Tìm thấy nhiều file:")
for i, m in enumerate(matches, 1):
print(f" {i}. {m}")
sel = input(" Chọn số (Enter = 1): ").strip()
if sel.isdigit() and 1 <= int(sel) <= len(matches):
return matches[int(sel) - 1]
return matches[0]
def resolve_source(request: str, interactive: bool = False) -> tuple[Path, str]:
"""Turn a request into a printable file:
URL -> download; existing path -> use; a filename (or 'tìm <name>') ->
SEARCH the PC; otherwise -> generate an image."""
a = request.strip().strip('"').strip("'")
low = a.lower()
# 1. image URL
if low.startswith(("http://", "https://")) and low.split("?")[0].endswith(IMG_EXT):
dest = IMG_DIR / f"src_{_slug(Path(urllib.parse.urlparse(a).path).stem)}.jpg"
return _download(a, dest), f"url:{a[:50]}"
# 2. an existing path (image or pdf)
p = Path(a)
if p.exists() and p.suffix.lower() in file_finder.PRINTABLE:
return p, f"file:{p}"
# 3. find a file on the PC: explicit "tìm/find ...", or a bare filename
find_q = None
for kw in ("tìm ", "tim ", "find "):
if low.startswith(kw):
find_q = a[len(kw):].strip()
break
if find_q is None and p.suffix.lower() in file_finder.PRINTABLE:
find_q = a
if find_q:
print(f" 🔎 Đang tìm '{find_q}' trong máy...")
matches = file_finder.find_files(find_q)
if not matches:
raise RuntimeError(f"Không tìm thấy file '{find_q}' trong máy.")
chosen = _choose(matches, interactive)
return chosen, f"found:{chosen}"
# 4. otherwise: generate an image from the description
prompt = translate_to_prompt(a)
dest = IMG_DIR / f"gen_{_slug(a)}.png"
generate_image(prompt, dest)
return dest, f"generated:'{prompt[:60]}'"
def print_path(path: Path, size_opts: dict) -> dict:
"""Print a file by type: image -> direct; pdf -> rasterize each page."""
ext = Path(path).suffix.lower()
if ext == ".pdf":
try:
import fitz # PyMuPDF
except ImportError:
return {"ok": False, "error": "PDF cần PyMuPDF: pip install pymupdf"}
doc = fitz.open(str(path))
results = []
for i, page in enumerate(doc):
pix = page.get_pixmap(dpi=int(size_opts.get("dpi", 150)))
tmp = IMG_DIR / f"pdf_{_slug(Path(path).stem)}_p{i + 1}.png"
pix.save(str(tmp))
results.append(paper_print.print_image(str(tmp), **size_opts))
return {"ok": all(r.get("ok") for r in results), "pages": len(results),
"placed_mm": results[0].get("placed_mm") if results else None,
"printer": results[0].get("printer") if results else None}
return paper_print.print_image(str(path), **size_opts)
def parse_args(argv: list[str]) -> tuple[str, dict]:
"""Pull size flags out of argv; the rest is the request text.
--size WxH (mm) --w N --h N --margin N --dpi N --stretch --align X
"""
opts: dict = {}
rest: list[str] = []
i = 0
while i < len(argv):
a = argv[i].lower()
nxt = argv[i + 1] if i + 1 < len(argv) else None
if a in ("--size", "-s") and nxt:
m = re.match(r"(\d+(?:\.\d+)?)\s*[xX*]\s*(\d+(?:\.\d+)?)", nxt)
if m:
opts["width_mm"] = float(m.group(1)); opts["height_mm"] = float(m.group(2))
i += 2; continue
if a in ("--w", "--width") and nxt:
opts["width_mm"] = float(nxt); i += 2; continue
if a in ("--h", "--height") and nxt:
opts["height_mm"] = float(nxt); i += 2; continue
if a == "--margin" and nxt:
opts["margin_mm"] = float(nxt); i += 2; continue
if a == "--dpi" and nxt:
opts["dpi"] = int(nxt); i += 2; continue
if a == "--align" and nxt:
opts["align"] = nxt; i += 2; continue
if a == "--stretch":
opts["stretch"] = True; i += 1; continue
rest.append(argv[i]); i += 1
return " ".join(rest).strip(), opts
def connect_or_report() -> Optional[str]:
"""Auto-discover the printer. Return its host if found, else report & None."""
print("🔎 Đang dò tìm máy in trên mạng WiFi...")
try:
host = paper_print.resolve_host()
except Exception as e:
print(f"❌ KHÔNG tìm thấy máy in nào trên mạng. ({e})")
print(" - Kiểm tra máy in đã bật và nối cùng WiFi với máy tính chưa.")
return None
info = paper_print.get_attributes(host) or {}
model = info.get("model", "printer")
print(f"✅ Đã kết nối: {model} @ {host}")
return host
def print_one(request: str, size_opts: dict, interactive: bool = False) -> None:
path, how = resolve_source(request, interactive=interactive)
print(f" nguồn: {how}")
result = print_path(Path(path), size_opts)
if result.get("ok"):
pages = f", {result['pages']} trang" if result.get("pages") else ""
print(f" 🖨 Đã gửi in ({result.get('placed_mm')}{pages}). Kiểm tra khay giấy.")
else:
print(f" ⚠️ In thất bại: {result}")
def interactive() -> None:
"""Discover -> connect (or report) -> keep asking what to print."""
if connect_or_report() is None:
return
print("\nNhập nội dung cần in:")
print(" • mô tả để tạo ảnh (VD: con mèo)")
print(" • TÊN FILE trong máy (VD: baocao.pdf | tìm meocon.jpg)")
print(" • đường dẫn hoặc URL ảnh")
print("Kèm kích thước nếu muốn, VD: baocao.pdf --size 100x150")
print("Gõ 'thoát' để dừng.\n")
while True:
try:
line = input("🖨 Bạn muốn in gì? > ").strip()
except (EOFError, KeyboardInterrupt):
print("\nKết thúc."); return
if not line:
continue
if line.lower() in ("thoát", "thoat", "quit", "exit", "q"):
print("Kết thúc."); return
request, size_opts = parse_args(shlex.split(line))
if not request:
print(" (chưa có nội dung — nhập mô tả/đường dẫn/tên file)"); continue
try:
print_one(request, size_opts, interactive=True)
except Exception as e:
print(f" ⚠️ Lỗi: {e}")
def main() -> None:
argv = sys.argv[1:]
if not argv: # no args -> interactive: discover then ask
interactive()
return
# one-shot mode
request, size_opts = parse_args(argv)
if connect_or_report() is None:
return
print("Request :", request or "(mặc định)")
print_one(request or "một con mèo", size_opts)
if __name__ == "__main__":
main()