File size: 9,913 Bytes
f368481
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
"""
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()