Download app.py from benxa34/test01: direct link, hf CLI and curl.
- Browser
- Download file 2.11 kB
-
https://huggingface.co/spaces/benxa34/test01/resolve/main/app.py
- Command line
-
hf download hf://spaces/benxa34/test01/app.py
-
curl -L -o app.py https://huggingface.co/spaces/benxa34/test01/resolve/main/app.py
2.11 kB
| 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) |