Update app.py
Browse files
app.py
CHANGED
|
@@ -1,90 +1,157 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
import requests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import gradio as gr
|
| 4 |
|
| 5 |
-
#
|
| 6 |
HF_API_TOKEN = os.environ.get("HF_API_TOKEN")
|
| 7 |
if HF_API_TOKEN is None:
|
| 8 |
raise RuntimeError(
|
| 9 |
"环境变量 HF_API_TOKEN 未设置,请在 Space 的 Settings -> Variables 中添加一个名为 HF_API_TOKEN 的 Secret。"
|
| 10 |
)
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
|
| 14 |
-
MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct"
|
| 15 |
-
|
| 16 |
API_URL = f"https://api-inference.huggingface.co/models/{MODEL_ID}"
|
| 17 |
HEADERS = {"Authorization": f"Bearer {HF_API_TOKEN}"}
|
| 18 |
|
| 19 |
|
| 20 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
payload = {
|
| 22 |
-
"inputs":
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
"temperature": temperature,
|
| 26 |
-
"do_sample": True,
|
| 27 |
-
},
|
| 28 |
}
|
| 29 |
-
response = requests.post(API_URL, headers=HEADERS, json=payload, timeout=120)
|
| 30 |
-
response.raise_for_status()
|
| 31 |
-
data = response.json()
|
| 32 |
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
if isinstance(data, list) and len(data) > 0:
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
return str(data)
|
| 38 |
|
| 39 |
|
| 40 |
-
def
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
dialog += f"用户: {user_msg}\n助手: {bot_msg}\n"
|
| 46 |
-
dialog += f"用户: {message}\n助手:"
|
| 47 |
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
|
| 57 |
with gr.Blocks() as demo:
|
| 58 |
-
gr.Markdown(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
with gr.Row():
|
| 61 |
-
with gr.Column(
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
lines=2,
|
| 67 |
)
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
gr.
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
inputs=[
|
| 79 |
-
outputs=
|
| 80 |
-
)
|
| 81 |
-
msg.submit(
|
| 82 |
-
chat_fn,
|
| 83 |
-
inputs=[chatbot, msg, max_new_tokens, temperature],
|
| 84 |
-
outputs=[chatbot, msg],
|
| 85 |
)
|
| 86 |
-
clear_btn.click(lambda: ([], ""), None, [chatbot, msg])
|
| 87 |
|
| 88 |
if __name__ == "__main__":
|
| 89 |
-
# 不要给 launch() 传额外参数,HF 会自己管理 host/port
|
| 90 |
demo.launch()
|
|
|
|
| 1 |
import os
|
| 2 |
+
import base64
|
| 3 |
import requests
|
| 4 |
+
from io import BytesIO
|
| 5 |
+
from typing import List, Union
|
| 6 |
+
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import pypdfium2 as pdfium
|
| 9 |
import gradio as gr
|
| 10 |
|
| 11 |
+
# 从环境变量中读取 HF API Token
|
| 12 |
HF_API_TOKEN = os.environ.get("HF_API_TOKEN")
|
| 13 |
if HF_API_TOKEN is None:
|
| 14 |
raise RuntimeError(
|
| 15 |
"环境变量 HF_API_TOKEN 未设置,请在 Space 的 Settings -> Variables 中添加一个名为 HF_API_TOKEN 的 Secret。"
|
| 16 |
)
|
| 17 |
|
| 18 |
+
# 使用 OCR 模型
|
| 19 |
+
MODEL_ID = "tencent/HunyuanOCR"
|
|
|
|
|
|
|
| 20 |
API_URL = f"https://api-inference.huggingface.co/models/{MODEL_ID}"
|
| 21 |
HEADERS = {"Authorization": f"Bearer {HF_API_TOKEN}"}
|
| 22 |
|
| 23 |
|
| 24 |
+
def image_to_base64(image: Image.Image) -> str:
|
| 25 |
+
"""把 PIL Image 转成 base64 字符串"""
|
| 26 |
+
buffered = BytesIO()
|
| 27 |
+
image.save(buffered, format="PNG")
|
| 28 |
+
img_bytes = buffered.getvalue()
|
| 29 |
+
img_b64 = base64.b64encode(img_bytes).decode("utf-8")
|
| 30 |
+
return img_b64
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def call_ocr_model(image: Image.Image) -> str:
|
| 34 |
+
"""对单张图片调用 HunyuanOCR"""
|
| 35 |
+
img_b64 = image_to_base64(image)
|
| 36 |
payload = {
|
| 37 |
+
"inputs": {
|
| 38 |
+
"image": img_b64
|
| 39 |
+
}
|
|
|
|
|
|
|
|
|
|
| 40 |
}
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
+
try:
|
| 43 |
+
response = requests.post(API_URL, headers=HEADERS, json=payload, timeout=120)
|
| 44 |
+
response.raise_for_status()
|
| 45 |
+
except Exception as e:
|
| 46 |
+
return f"[调用模型出错] {type(e).__name__}: {e}"
|
| 47 |
+
|
| 48 |
+
try:
|
| 49 |
+
data = response.json()
|
| 50 |
+
except Exception as e:
|
| 51 |
+
return f"[解析返回结果出错] {type(e).__name__}: {e}\n原始返回:{response.text[:1000]}"
|
| 52 |
+
|
| 53 |
+
# 尝试多种常见返回结构
|
| 54 |
if isinstance(data, list) and len(data) > 0:
|
| 55 |
+
first = data[0]
|
| 56 |
+
if isinstance(first, dict):
|
| 57 |
+
for key in ["generated_text", "text", "output", "label"]:
|
| 58 |
+
if key in first and isinstance(first[key], str):
|
| 59 |
+
return first[key].strip()
|
| 60 |
+
return str(first)
|
| 61 |
+
|
| 62 |
+
if isinstance(data, dict):
|
| 63 |
+
for key in ["generated_text", "text", "output", "label"]:
|
| 64 |
+
if key in data and isinstance(data[key], str):
|
| 65 |
+
return data[key].strip()
|
| 66 |
+
return str(data)
|
| 67 |
+
|
| 68 |
return str(data)
|
| 69 |
|
| 70 |
|
| 71 |
+
def pdf_to_images(pdf_bytes: bytes, dpi: int = 200) -> List[Image.Image]:
|
| 72 |
+
"""把 PDF 的每一页渲染成 PIL Image 列表"""
|
| 73 |
+
pdf = pdfium.PdfDocument(pdf_bytes)
|
| 74 |
+
n_pages = len(pdf)
|
| 75 |
+
images: List[Image.Image] = []
|
|
|
|
|
|
|
| 76 |
|
| 77 |
+
for i in range(n_pages):
|
| 78 |
+
page = pdf[i]
|
| 79 |
+
pil_image = page.render(scale=dpi / 72).to_pil() # 72 dpi 是 PDF 默认分辨率
|
| 80 |
+
images.append(pil_image)
|
| 81 |
+
|
| 82 |
+
return images
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def run_ocr(file: Union[bytes, None], image: Union[Image.Image, None]) -> str:
|
| 86 |
+
"""
|
| 87 |
+
总入口:可以上传 PDF 或 图片。
|
| 88 |
+
- 如果上传了 PDF(file),对 PDF 每一页做 OCR
|
| 89 |
+
- 如果只上传图片,对图片做 OCR
|
| 90 |
+
- 如果两个都没传,提示用户
|
| 91 |
+
"""
|
| 92 |
+
if file is None and image is None:
|
| 93 |
+
return "请上传 PDF 文件或图片。"
|
| 94 |
+
|
| 95 |
+
results = []
|
| 96 |
+
|
| 97 |
+
# 1. 如果上传了 PDF
|
| 98 |
+
if file is not None:
|
| 99 |
+
try:
|
| 100 |
+
pdf_bytes = file
|
| 101 |
+
pages = pdf_to_images(pdf_bytes)
|
| 102 |
+
except Exception as e:
|
| 103 |
+
return f"[解析 PDF 出错] {type(e).__name__}: {e}"
|
| 104 |
|
| 105 |
+
if not pages:
|
| 106 |
+
return "PDF 中未检测到页面。"
|
| 107 |
+
|
| 108 |
+
for idx, page_img in enumerate(pages, start=1):
|
| 109 |
+
text = call_ocr_model(page_img)
|
| 110 |
+
results.append(f"===== 第 {idx} 页 =====\n{text}\n")
|
| 111 |
+
|
| 112 |
+
# 2. 如果上传了图片
|
| 113 |
+
if image is not None:
|
| 114 |
+
text = call_ocr_model(image)
|
| 115 |
+
# 如果前面已经有 PDF 结果,就在后面追加,否则单独一段
|
| 116 |
+
if results:
|
| 117 |
+
results.append("===== 图片识别结果 =====\n" + text)
|
| 118 |
+
else:
|
| 119 |
+
results.append(text)
|
| 120 |
+
|
| 121 |
+
return "\n".join(results)
|
| 122 |
|
| 123 |
|
| 124 |
with gr.Blocks() as demo:
|
| 125 |
+
gr.Markdown(
|
| 126 |
+
f"""# 文档 OCR Demo(HunyuanOCR)
|
| 127 |
+
使用模型:`{MODEL_ID}`
|
| 128 |
+
|
| 129 |
+
你可以:
|
| 130 |
+
- 上传 **PDF 文件**(多页会逐页识别,并按页分隔)
|
| 131 |
+
- 或上传 **单张图片**(截图、拍照等)
|
| 132 |
+
"""
|
| 133 |
+
)
|
| 134 |
|
| 135 |
with gr.Row():
|
| 136 |
+
with gr.Column():
|
| 137 |
+
pdf_input = gr.File(
|
| 138 |
+
label="上传 PDF 文件(可选)",
|
| 139 |
+
file_types=[".pdf"],
|
| 140 |
+
type="binary",
|
|
|
|
| 141 |
)
|
| 142 |
+
image_input = gr.Image(
|
| 143 |
+
type="pil",
|
| 144 |
+
label="上传图片(可选)",
|
| 145 |
+
)
|
| 146 |
+
run_button = gr.Button("开始识别")
|
| 147 |
+
with gr.Column():
|
| 148 |
+
output_text = gr.Textbox(label="识别结果", lines=25)
|
| 149 |
+
|
| 150 |
+
run_button.click(
|
| 151 |
+
fn=run_ocr,
|
| 152 |
+
inputs=[pdf_input, image_input],
|
| 153 |
+
outputs=output_text,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
)
|
|
|
|
| 155 |
|
| 156 |
if __name__ == "__main__":
|
|
|
|
| 157 |
demo.launch()
|