当我第一次构建 MedSpeak 时,必须手动输入缩写。这对演示来说没问题,但标签的全部意义在于它已经写好了——所以很自然的下一步就是让人们拍摄标签的照片,完全跳过打字。
此更新通过 Tesseract.js 添加了浏览器内 OCR,将页面切换为 JSON API 而非表单提交,并保留了其他所有内容——查找表、解码逻辑——完全不变。
1. 底层发生了什么变化
翻译逻辑(decode(),以及 FREQUENCY/TIMING/ROUTE/FORM 表)与原始版本完全相同。改变的是文本如何进入该函数,以及结果如何返回到页面:
- 表单不再执行整页 POST——而是使用一个小型
fetch()调用 JSON API - 文件输入允许您选择或拍摄照片
- Tesseract.js 在完全浏览器内运行 OCR——图像从不上传到服务器
- Tesseract 找到的任何文本都会放入输入框并自动解码
def do_POST(self):
if self.path == "/api/decode":
length = int(self.headers.get("Content-Length", 0))
data = json.loads(self.rfile.read(length) or "{}")
text = data.get("text", "")
result = decode(text)
self._send(200, json.dumps({"result": result}))
else:
self._send(404, "{}")
Enter fullscreen mode Exit fullscreen mode
服务器现在以 JSON 格式输入和输出,而不是解析表单编码的正文并重新渲染完整的 HTML 页面。
2. 从页面调用 API
不再使用 <form> 提交,而是使用普通的 fetch() 调用发送当前输入值,并用返回的结果更新结果 div。
async function go(){
const text = document.getElementById('rx').value;
const out = document.getElementById('out');
if(!text.trim()){ return; }
const res = await fetch('/api/decode', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({text: text})
});
const data = await res.json();
out.classList.remove('empty');
out.innerHTML = '<span class="tag">Instructions</span>' + data.result;
}
Enter fullscreen mode Exit fullscreen mode
这就是页面感觉即时的原因——无需整页重新加载,只需更新标签卡片。
3. 从照片中读取文本
这是新的部分。Tesseract.js 从 CDN 加载并在客户端完全执行 OCR:
<script src="https://cdnjs.cloudflare.com/ajax/libs/tesseract.js/5.0.4/tesseract.min.js"></script>
Enter fullscreen mode Exit fullscreen mode
选择文件后,会立即预览并交给 OCR 函数:
function handleImage(event){
const file = event.target.files[0];
if (!file) return;
const preview = document.getElementById('preview');
preview.src = URL.createObjectURL(file);
preview.style.display = 'block';
scanImage(file);
}
Enter fullscreen mode Exit fullscreen mode
URL.createObjectURL(file) 为图像创建一个临时本地 URL,以便在 <img> 标签中显示,而无需离开浏览器。
4. 运行 OCR 并将结果反馈回来
async function scanImage(file){
const status = document.getElementById('scanStatus');
status.innerText = "Reading text from image...";
try {
const result = await Tesseract.recognize(file, 'eng');
const rawText = result.data.text.trim();
status.innerText = rawText ? ("Detected: " + rawText) : "No text found — try a clearer photo.";
if (rawText){
document.getElementById('rx').value = rawText.replace(/\n/g, ' ');
go();
}
} catch(e){
status.innerText = "Scan failed — type it manually instead.";
}
}
Enter fullscreen mode Exit fullscreen mode
Tesseract.recognize(file, 'eng') 运行整个 OCR 流程并返回检测到的文本。新行会折叠为空格(因为处方缩写通常是单行),输入框会被填充,go()——与手动输入相同的函数——会立即解码它。
5. 完整脚本,从头到尾
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
FREQUENCY = {
"qd": "once a day", "od": "once a day",
"bid": "twice a day", "tid": "three times a day", "qid": "four times a day", "qod": "every other day", "hs": "at bedtime", "stat": "immediately", "prn": "as needed", "am": "in the morning", "qam": "every morning", "pm": "in the evening", "qpm": "every evening",
}
TIMING = {
"ac": "before meals",
"pc": "after meals", "cc": "with meals",
}
ROUTE = {
"po": "by mouth", "sl": "under the tongue", "iv": "by IV", "im": "as an injection into the muscle", "sc": "as an injection under the skin", "sq": "as an injection under the skin", "pr": "rectally", "top": "applied to the skin",
}
FORM = {
"tab": "tablet", "tabs": "tablets",
"cap": "capsule", "caps": "capsules", "ml": "ml", "mg": "mg", "gtt": "drop", "gtts": "drops",
}
def decode(text):
tokens = text.replace(",", " ").split()
result = []
for tok in tokens:
raw = tok.strip(".")
low = raw.lower()
if low.isdigit():
result.append(f"Take {low}")
elif low in FORM:
result.append(FORM[low])
elif low in FREQUENCY:
result.append(FREQUENCY[low])
elif low in TIMING:
result.append(TIMING[low])
elif low in ROUTE:
result.append(ROUTE[low])
elif low.startswith("q") and low.endswith("h") and low[1:-1].isdigit():
hrs = low[1:-1]
result.append(f"every {hrs} hours")
else:
result.append(raw)
sentence = " ".join(result)
return sentence[0].upper() + sentence[1:] if sentence else ""
HTML_PAGE = """
<!DOCTYPE html>
<html><head><meta charset="utf-8">
<title>MedSpeak</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Lora:wght@500;600&family=Inter:wght@400;500;600&family=IBM+Plex+Mono:wght@500;600&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/tesseract.js/5.0.4/tesseract.min.js"></script>
<style>
:root{
--paper: #E8EDE6;
--card: #FBFAF6;
--ink: #1B2A4A;
--ink-soft: #4A5A72;
--amber: #C17817;
--amber-deep: #9C5F10;
--clay: #B3492B;
}
*{box-sizing:border-box}
body{
margin:0; padding:32px 16px 60px;
background:var(--paper);
background-image:
radial-gradient(circle at 15% 8%, rgba(193,120,23,0.06), transparent 40%),
radial-gradient(circle at 85% 90%, rgba(27,42,74,0.05), transparent 40%);
font-family:'Inter', sans-serif;
color:var(--ink);
display:flex; justify-content:center;
}
main{width:100%; max-width:560px}
.eyebrow{
font-family:'IBM Plex Mono', monospace;
font-size:12px; letter-spacing:0.12em; text-transform:uppercase;
color:var(--amber-deep); font-weight:600;
}
h1{
font-family:'Lora', serif; font-weight:600;
font-size:clamp(28px, 5vw, 36px);
margin:6px 0 4px; color:var(--ink);
}
.sub{ color:var(--ink-soft); font-size:15px; margin:0 0 28px; max-width:44ch; line-height:1.5}
.rx-mark{
display:inline-flex; align-items:center; justify-content:center;
width:40px; height:40px; border-radius:10px;
background:var(--ink); color:var(--paper);
font-family:'Lora', serif; font-weight:600; font-size:20px;
margin-bottom:14px;
}
.card{
background:var(--card); border-radius:14px; padding:22px;
box-shadow:0 1px 2px rgba(27,42,74,0.06), 0 8px 24px rgba(27,42,74,0.05);
border:1px solid rgba(27,42,74,0.08);
}
label.field-label{
display:block; font-size:13px; font-weight:600; color:var(--ink-soft);
margin-bottom:6px;
}
input[type=text]{
width:100%; padding:12px 14px; font-size:16px;
border-radius:8px; border:1.5px solid rgba(27,42,74,0.18);
font-family:'IBM Plex Mono', monospace; background:#fff; color:var(--ink);
}
input[type=text]:focus{
outline:3px solid rgba(193,120,23,0.35); outline-offset:1px;
border-color:var(--amber);
}
.row{ display:flex; gap:10px; margin-top:12px }
.row input{flex:1}
button{
padding:12px 20px; font-size:15px; font-weight:600;
border:none; border-radius:8px; cursor:pointer;
background:var(--amber); color:#fff;
font-family:'Inter', sans-serif;
transition:background .15s ease;
}
button:hover{ background:var(--amber-deep) }
button:focus-visible{ outline:3px solid var(--ink); outline-offset:2px }
.examples{ font-size:13px; color:var(--ink-soft); margin-top:10px }
.examples code{
font-family:'IBM Plex Mono', monospace; background:rgba(27,42,74,0.06);
padding:2px 6px; border-radius:4px;
}
.label-wrap{ margin-top:26px }
.rx-label{
position:relative;
background:#fff;
border:1.5px solid rgba(27,42,74,0.15);
border-radius:2px;
padding:18px 18px 16px;
font-family:'IBM Plex Mono', monospace;
font-size:15px; line-height:1.55; color:var(--ink);
transform:rotate(-0.6deg);
box-shadow:0 6px 16px rgba(27,42,74,0.10);
}
.rx-label::before{
content:"";
position:absolute; top:-1px; left:8px; right:8px; height:1px;
background-image: repeating-linear-gradient(90deg, rgba(27,42,74,0.35) 0 6px, transparent 6px 12px);
}
.rx-label .tag{
font-family:'Inter', sans-serif; font-weight:600; font-size:11px;
letter-spacing:0.08em; text-transform:uppercase; color:var(--amber-deep);
display:block; margin-bottom:6px;
}
.rx-label.empty{ color:var(--ink-soft); font-style:normal }
.scan-section{ margin-top:30px }
.scan-section .field-label{ margin-bottom:10px }
.upload-box{
background:var(--card); border:1.5px dashed rgba(27,42,74,0.25);
border-radius:12px; padding:18px; text-align:center;
}
.upload-box input[type=file]{ font-family:'Inter', sans-serif; font-size:14px }
#preview{ max-width:100%; margin-top:12px; border-radius:8px; display:none }
#scanStatus{ font-size:13px; color:var(--ink-soft); margin-top:10px }
@media (prefers-reduced-motion: reduce){
* { transition:none !important }
}
</style>
</head>
<body>
<main>
<div class="rx-mark">Rx</div>
<div class="eyebrow">Prescription shorthand, decoded</div>
<h1>MedSpeak</h1>
<p class="sub">Type or scan the shorthand exactly as written on the label — get back plain instructions anyone can follow.</p>
<div class="card">
<label class="field-label" for="rx">Prescription text</label>
<div class="row">
<input type="text" id="rx" placeholder="e.g. 1 tab BID pc" onkeydown="if(event.key==='Enter')go()">
<button onclick="go()">Decode</button>
</div>
<p class="examples">Try <code>1 tab BID pc</code> · <code>PRN q6h</code> · <code>2 cap TID AC PO</code></p>
<div class="label-wrap">
<div class="rx-label empty" id="out">
<span class="tag">Instructions</span>
Decoded text will appear here.
</div>
</div>
</div>
<div class="scan-section">
<label class="field-label">Or scan a photo of the prescription</label>
<div class="upload-box">
<input type="file" id="imgInput" accept="image/*" onchange="handleImage(event)">
<img id="preview">
<p id="scanStatus"></p>
</div>
</div>
</main>
<script>
async function go(){
const text = document.getElementById('rx').value;
const out = document.getElementById('out');
if(!text.trim()){ return; }
const res = await fetch('/api/decode', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({text: text})
});
const data = await res.json();
out.classList.remove('empty');
out.innerHTML = '<span class="tag">Instructions</span>' + data.result;
}
function handleImage(event){
const file = event.target.files[0];
if (!file) return;
const preview = document.getElementById('preview');
preview.src = URL.createObjectURL(file);
preview.style.display = 'block';
scanImage(file);
}
async function scanImage(file){
const status = document.getElementById('scanStatus');
status.innerText = "Reading text from image...";
try {
const result = await Tesseract.recognize(file, 'eng');
const rawText = result.data.text.trim();
status.innerText = rawText ? ("Detected: " + rawText) : "No text found — try a clearer photo.";
if (rawText){
document.getElementById('rx').value = rawText.replace(/\\n/g, ' ');
go();
}
} catch(e){
status.innerText = "Scan failed — type it manually instead.";
}
}
</script>
</body></html>
"""
class Handler(BaseHTTPRequestHandler):
def _send(self, code, body, ctype="application/json"):
self.send_response(code)
self.send_header("Content-Type", ctype)
self.end_headers()
self.wfile.write(body.encode())
def do_GET(self):
if self.path == "/":
self._send(200, HTML_PAGE, "text/html")
else:
self._send(404, "{}")
def do_POST(self):
if self.path == "/api/decode":
length = int(self.headers.get("Content-Length", 0))
data = json.loads(self.rfile.read(length) or "{}")
text = data.get("text", "")
result = decode(text)
self._send(200, json.dumps({"result": result}))
else:
self._send(404, "{}")
def log_message(self, *args):
pass
if __name__ == "__main__":
print("MedSpeak running at http://localhost:8000")
ThreadingHTTPServer(("0.0.0.0, 8000), Handler).serve_forever()
Enter fullscreen mode Exit fullscreen mode
使用 python medspeak.py 运行它,然后打开 http://localhost:8000。
6. 试用
与之前相同的解码示例,加上新的扫描路径:
| 输入方式 | 示例 | 输出 |
|---|---|---|
| 手动输入 | 1 tab BID pc |
Take 1 tablet twice a day after meals |
| 手动输入 | PRN q6h |
As needed every 6 hours |
扫描标签照片(内容为 2 CAP TID AC PO) |
(照片) | Take 2 capsules three times a day before meals by mouth |
总结
使用 Tesseract.js 在客户端执行 OCR 的好处是,任何人的处方照片都不会触及服务器——识别完全在浏览器标签页中进行,只有识别出的文本才会发送到 /api/decode。对于处理医疗标签的工具来说,这是一个有意义的隐私属性,而且通过选择客户端 OCR 库而不是服务器端库,这基本上是免费获得的。
注意:OCR 准确性取决于照片质量、光线和笔迹——始终对照实际标签仔细检查扫描结果,如有任何歧义,请咨询您的药剂师。
0 Comments
Log in to join the conversation.No comments yet. Be the first to share your thoughts.