# -*- coding: utf-8 -*-
"""表格页二次识别：强调表格结构与行列对应"""
import base64, json, os, glob, time
import urllib.request
from concurrent.futures import ThreadPoolExecutor

API="https://api.deepseek.com/v1/chat/completions"; MODEL="deepseek-v4-flash-vision-exp"
KEY="sk-2af0093dfbac45359276d8aa85d83618"
SRC="/home/zyw/Downloads/dl-hub/26-合同审查/originals"
OUT="/home/zyw/Downloads/dl-hub/26-合同审查/pages2"
os.makedirs(OUT,exist_ok=True)

PROMPT = """这是一张中文合同/清单的表格页照片。请把表格完整、准确地转成 Markdown 表格，要求：
1. 先判断表格有几列、每列表头是什么，在表格上方用一行注明「列数：N，表头：A|B|C...」。
2. 每一行的每个单元格内容必须与图片中该行该列严格对应，绝对不要把不同列的单元格内容错位、合并或串行。
3. 从上到下逐行输出，行顺序必须和图片一致（不要颠倒顺序）。
4. 如果表头使用了合并单元格或跨页续表未重复表头，请推断表头并用（推断）标注。
5. 原文数字、型号、规格、单位、标点必须逐字一致（如 Φ8、@20cm、800*800、2.8m×1.2m×1.5m）。
6. 模糊处用 〔?〕，空白填写处用【空白】。
7. 表格之外的其他文字（标题、说明、页码）也要照实转录，页码放最后。
8. 只输出转录内容，不要解释。"""

def ocr(path):
    b64=base64.b64encode(open(path,"rb").read()).decode()
    payload={"model":MODEL,"temperature":0,"max_tokens":8000,"messages":[{"role":"user","content":[
      {"type":"image_url","image_url":{"url":"data:image/jpeg;base64,"+b64}},
      {"type":"text","text":PROMPT}]}]}
    req=urllib.request.Request(API,data=json.dumps(payload).encode(),
      headers={"Authorization":"Bearer "+KEY,"Content-Type":"application/json"})
    with urllib.request.urlopen(req,timeout=600) as r:
        d=json.loads(r.read())
    return d["choices"][0]["message"].get("content") or ""

TARGETS=["微信图片_20260910183850","微信图片_20260910183854","微信图片_20260910183858",
 "微信图片_20260910183902","微信图片_20260910183905","微信图片_20260910183908",
 "微信图片_20260910183912","微信图片_20260910183915","微信图片_20260910183917",
 "微信图片_20260910183921","微信图片_20260910183924","微信图片_20260910183927",
 "微信图片_20260910183931","微信图片_20260910183934"]

def work(n):
    f=os.path.join(SRC,n+".jpg"); dst=os.path.join(OUT,n+".md")
    if os.path.exists(dst) and os.path.getsize(dst)>50: return "skip "+n
    for a in range(1,5):
        try:
            t=ocr(f)
            if len(t.strip())>50:
                open(dst,"w",encoding="utf-8").write(t); return f"OK {n} ({len(t)})"
        except Exception as e: pass
        time.sleep(4*a)
    return "FAIL "+n

with ThreadPoolExecutor(max_workers=4) as ex:
    for r in ex.map(work,TARGETS): print(r,flush=True)
print("TABLE PASS DONE")
