File size: 5,009 Bytes
755023e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""HTTP-сервис Image: изображение → текст.

Запуск:
    python -m image_text.server --port 8001

- GET  /       — мини-интерфейс в браузере
- POST /ocr    — raw-телом изображения → JSON {text, lines}
"""

from __future__ import annotations

import argparse
import json
import os
import sys
import tempfile
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlparse

from .engine import ImageEngine

IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".bmp", ".webp", ".tif", ".tiff"}

HTML_PAGE = """<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<title>Image — изображение → текст</title>
<style>
 body{font-family:system-ui,sans-serif;max-width:640px;margin:40px auto;padding:0 16px;color:#222}
 h1{font-size:22px}
 .row{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin:16px 0}
 input[type=file]{border:1px solid #ccc;padding:6px;border-radius:6px}
 button{background:#0b5fff;color:#fff;border:0;padding:8px 16px;border-radius:6px;cursor:pointer}
 pre{background:#f4f4f5;border:1px solid #e4e4e7;border-radius:8px;padding:12px;white-space:pre-wrap}
 #status{font-size:14px;color:#666;min-height:20px}
</style>
</head>
<body>
<h1>Image — изображение → текст</h1>
<p>Загрузите изображение с текстом — получите расшифровку (OCR).</p>
<div class="row">
 <input type="file" id="f" accept="image/*">
 <button onclick="go()">Извлечь текст</button>
</div>
<div id="status"></div>
<pre id="out"></pre>
<script>
async function go(){
  const f=document.getElementById('f');
  if(!f.files.length){alert('Сначала файл');return;}
  const status=document.getElementById('status');
  status.textContent='Обрабатываю...';
  const res=await fetch('/ocr',{method:'POST',body:f.files[0]});
  const data=await res.json();
  status.textContent='Готово: '+data.lines.length+' фрагментов';
  document.getElementById('out').textContent=data.text;
}
</script>
</body>
</html>
"""


def make_handler(engine: ImageEngine):
    class Handler(BaseHTTPRequestHandler):
        def _send(self, code: int, body: bytes, ctype: str) -> None:
            self.send_response(code)
            self.send_header("Content-Type", ctype)
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

        def do_GET(self) -> None:  # noqa: N802
            path = urlparse(self.path).path
            if path == "/ocr":
                self._send(200, b'{"error":"используйте POST"}', "application/json; charset=utf-8")
            elif path in ("/", "/index.html"):
                self._send(200, HTML_PAGE.encode("utf-8"), "text/html; charset=utf-8")
            elif path == "/health":
                self._send(200, b'{"ok":true}', "application/json; charset=utf-8")
            else:
                self._send(404, b"not found", "text/plain; charset=utf-8")

        def do_POST(self) -> None:  # noqa: N802
            if urlparse(self.path).path != "/ocr":
                self._send(404, b"not found", "text/plain; charset=utf-8")
                return
            length = int(self.headers.get("Content-Length", "0"))
            data = self.rfile.read(length)
            if not data:
                self._send(400, b'{"error":"пустое тело"}', "application/json; charset=utf-8")
                return
            with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tf:
                tf.write(data)
                tmp_path = tf.name
            try:
                result = engine.ocr(tmp_path)
            except Exception as exc:  # noqa: BLE001
                self._send(500, json.dumps({"error": str(exc)}, ensure_ascii=False).encode("utf-8"),
                           "application/json; charset=utf-8")
                return
            finally:
                Path(tmp_path).unlink(missing_ok=True)
            self._send(200, json.dumps(result, ensure_ascii=False).encode("utf-8"),
                       "application/json; charset=utf-8")

        def log_message(self, fmt: str, *args) -> None:
            sys.stderr.write("[image-server] %s\n" % (fmt % args))

    return Handler


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(prog="image-server", description="Image HTTP-сервис")
    ap.add_argument("--port", "-p", type=int, default=int(os.environ.get("IMAGE_PORT", "8001")))
    ap.add_argument("--host", default="0.0.0.0")
    ap.add_argument("--model-dir", default=None)
    args = ap.parse_args(argv)

    engine = ImageEngine(model_dir=args.model_dir)
    server = ThreadingHTTPServer((args.host, args.port), make_handler(engine))
    print(f"Image server on http://{args.host}:{args.port}")
    server.serve_forever()
    return 0


if __name__ == "__main__":
    sys.exit(main())