File size: 2,110 Bytes
376410e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import requests
import json
import os

API_URL = "https://api.opentyphoon.ai/v1/ocr"

def ocr_upload(file_path, api_key,
               model="typhoon-ocr",
               task_type="default",
               max_tokens=16384,
               temperature=0.1,
               top_p=0.6,
               repetition_penalty=1.2,
               pages=None):

    if not os.path.exists(file_path):
        raise FileNotFoundError(f"File not found: {file_path}")

    with open(file_path, "rb") as f:
        files = {
            "file": (os.path.basename(file_path), f)
        }

        data = {
            "model": model,
            "task_type": task_type,
            "max_tokens": str(max_tokens),
            "temperature": str(temperature),
            "top_p": str(top_p),
            "repetition_penalty": str(repetition_penalty)
        }

        if pages:
            data["pages"] = json.dumps(pages)

        headers = {
            "Authorization": f"Bearer {api_key}"
        }

        response = requests.post(API_URL, files=files, data=data, headers=headers)

    if response.status_code != 200:
        raise Exception(f"OCR API Error {response.status_code}: {response.text}")

    return parse_ocr_response(response.json())


def parse_ocr_response(result_json):
    texts = []

    for page in result_json.get("results", []):
        if page.get("success"):
            content = page["message"]["choices"][0]["message"]["content"]

            try:
                parsed = json.loads(content)
                text = parsed.get("natural_text", content)
            except:
                text = content

            texts.append(text)
        else:
            print(f"❌ Error: {page.get('error')}")

    return "\n".join(texts)


# =========================
# ✅ ใช้งาน (Single file)
# =========================
if __name__ == "__main__":
    api_key = "sk-SJLOZn2kGqDX2zuO9doBAwb1alfocOLYQSM9SkiU2HW3KpQC"

    file_path = input("📂 ใส่ path ไฟล์: ").strip()

    text = ocr_upload(file_path, api_key)

    print("\n===== OCR RESULT =====\n")
    print(text)