File size: 9,046 Bytes
880e2d9 591e69e 880e2d9 a38c57e 880e2d9 | 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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 | # ============================================================
# Groq OCR + XLSX Export โ Gradio ็
# ไฝฟ็จๆนๆณ๏ผๅท่กๆญค็จๅผๅพๆๅจ็่ฆฝๅจ้ๅ Gradio ไป้ข
# ============================================================
import base64
import io
import re
import os
from datetime import datetime
from PIL import Image
from groq import Groq
import gradio as gr
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
# ่จญๅฎ
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
API_KEY = "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"
MODEL = "meta-llama/llama-4-scout-17b-16e-instruct"
PROMPT = """
่ซๅฐๅ็ๅ
งๅฎน้ฒ่ก OCR๏ผๅฐๅตๆธฌๅฐ็ๆๆๆๅญไปฅใ้่กใ็ๆนๅผ่ผธๅบใ
ๆฏไธ่ก่ซ็จไปฅไธๆ ผๅผ๏ผ
่ก่, ๅ
งๅฎน
ไพๅฆ๏ผ
1, ้ๆฏ็ฌฌไธ่กๆๅญ
2, ้ๆฏ็ฌฌไบ่กๆๅญ
่ซๅๅฟ
ๅดๆ ผ้ตๅฎๆญคๆ ผๅผ๏ผไธ่ฆๅคๅ ่ชชๆใ
"""
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๅทฅๅ
ทๅฝๆธ
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
def encode_image_bytes(img_bytes: bytes) -> str:
"""ๅฐๅ็ไฝๅ
็ต่ฝ็บ base64 ๅญไธฒ"""
return base64.b64encode(img_bytes).decode("utf-8")
def call_groq_ocr(base64_image: str) -> str:
"""ๅผๅซ Groq API ้ฒ่ก OCR"""
client = Groq(api_key=API_KEY)
resp = client.chat.completions.create(
model=MODEL,
messages=[{
"role": "user",
"content": [
{"type": "text", "text": PROMPT},
{"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}}
]
}],
temperature=0,
max_completion_tokens=1024,
top_p=1,
stream=False,
)
return resp.choices[0].message.content
def parse_ocr_to_rows(text: str) -> list:
"""ๅฐ OCR ๅๅณ็ๆๅญ่งฃๆ็บ [{"่ก่": ..., "ๅ
งๅฎน": ...}, ...]"""
rows = []
for line in text.strip().splitlines():
line = line.strip()
if not line:
continue
# ๅ่ฉฆๆๅบ ใๆธๅญ, ๅ
งๅฎนใ ๆจกๅผ
match = re.match(r"^(\d+)\s*[,ใ]\s*(.+)$", line)
if match:
rows.append({"่ก่": match.group(1), "ๅ
งๅฎน": match.group(2)})
else:
# ๆไธๅฐๅบ่็่ฉฑ็ดๆฅ็ถๅ
งๅฎน
rows.append({"่ก่": str(len(rows) + 1), "ๅ
งๅฎน": line})
return rows
def save_xlsx(ocr_dict: dict, filename: str):
"""ๅฐ็ตๆๅฏซๆ XLSX๏ผๆฏๅผตๅ็ไธๅ sheet"""
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
wb = Workbook()
wb.remove(wb.active) # ๅ
ๅชๆ้ ่จญ็ Sheet
# ๆจฃๅผ่จญๅฎ
header_font = Font(name="Microsoft JhengHei", bold=True, color="FFFFFF", size=11)
header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
header_align = Alignment(horizontal="center", vertical="center")
body_font = Font(name="Microsoft JhengHei", size=11)
thin_border = Border(
left=Side(style="thin"), right=Side(style="thin"),
top=Side(style="thin"), bottom=Side(style="thin")
)
for img_name, rows in ocr_dict.items():
# sheet ๅ็จฑ๏ผๅปๆๅฏๆชๅ๏ผ้ทๅบฆ้ๅถ31ๅญๅ
๏ผExcel้ๅถ๏ผ
sheet_name = os.path.splitext(img_name)[0][:31]
ws = wb.create_sheet(title=sheet_name)
# ๅฏซๅ
ฅ่กจ้ ญ
headers = ["่ก่", "ๅ
งๅฎน"]
for col_idx, h in enumerate(headers, start=1):
cell = ws.cell(row=1, column=col_idx, value=h)
cell.font = header_font
cell.fill = header_fill
cell.alignment = header_align
cell.border = thin_border
# ๅฏซๅ
ฅๆธๆ
for row_idx, r in enumerate(rows, start=2):
for col_idx, key in enumerate(["่ก่", "ๅ
งๅฎน"], start=1):
cell = ws.cell(row=row_idx, column=col_idx, value=r[key])
cell.font = body_font
cell.border = thin_border
# ่ชฟๆดๆฌๅฏฌ
ws.column_dimensions["A"].width = 8
ws.column_dimensions["B"].width = 50
wb.save(filename)
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
# ไธป่็ๅฝๆธ
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
def process_images(images):
"""่็ไธๅณ็ๅ็ไธฆ้ฒ่ก OCR"""
if not images:
return "โ ๏ธ ่ซๅ
ไธๅณ่ณๅฐไธๅผตๅ็๏ผ", None, None
ocr_dict = {}
log_output = []
total = len(images)
log_output.append(f"๐ ๅ
ฑไธๅณไบ {total} ๅผตๅ็๏ผ้ๅง้ๅผต่็...\n")
# ้ๅผต่็
for idx, img_file in enumerate(images, start=1):
# ่ฎๅๅ็
img_path = img_file.name if hasattr(img_file, 'name') else img_file
fname = os.path.basename(img_path)
log_output.append(f"\n{'=' * 50}")
log_output.append(f"๐ [{idx}/{total}] ่็ไธญ๏ผ{fname}")
log_output.append(f"{'=' * 50}")
try:
# ่ฎๅๅ็ไฝๅ
็ต
with open(img_path, 'rb') as f:
img_bytes = f.read()
# ๅผๅซ Groq OCR
log_output.append("โณ ๆญฃๅจๅผๅซ Groq API ้ฒ่ก OCR ...")
base64_full = encode_image_bytes(img_bytes)
raw_text = call_groq_ocr(base64_full)
log_output.append("\n๐ OCR ๅๅง่ผธๅบ๏ผ")
log_output.append("โ" * 40)
log_output.append(raw_text)
log_output.append("โ" * 40)
# ่งฃๆ็ตๆ
parsed = parse_ocr_to_rows(raw_text)
ocr_dict[fname] = parsed
if parsed:
log_output.append(f"\nโ
ๆญคๅๅตๆธฌๅบ {len(parsed)} ่กๆๅญ")
log_output.append(f"\n{'่ก่':<6} ๅ
งๅฎน")
log_output.append("โ" * 40)
for r in parsed:
log_output.append(f"{r['่ก่']:<6} {r['ๅ
งๅฎน']}")
else:
log_output.append("\nโ ๏ธ ๆญคๅๆชๅตๆธฌๅฐไปปไฝๆๅญ")
except Exception as e:
log_output.append(f"โ ่็ๅคฑๆ๏ผ{e}")
continue
# ็ๆ XLSX
total_lines = sum(len(v) for v in ocr_dict.values())
log_output.append(f"\n\n{'=' * 50}")
if total_lines:
log_output.append(f"๐ ๅ
จ้จๅฎๆ๏ผๅ
ฑๅพ {total} ๅผตๅ็ไธญ่งฃๆๅบ {total_lines} ่กๆๅญ")
# ไฟๅญ XLSX
output_filename = f"ocr_result_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
save_xlsx(ocr_dict, output_filename)
# ็ๆ้ ่ฆฝ่กจๆ ผ
preview_data = []
for img_name, rows in ocr_dict.items():
for r in rows:
preview_data.append([img_name, r['่ก่'], r['ๅ
งๅฎน']])
return "\n".join(log_output), output_filename, preview_data
else:
log_output.append("โ ๏ธ ๆๆๅ็ๅๆชๅตๆธฌๅฐไปปไฝๆๅญ")
return "\n".join(log_output), None, None
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
# Gradio ไป้ข
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
with gr.Blocks(title="Groq OCR ๅทฅๅ
ท", theme=gr.themes.Soft()) as demo:
gr.Markdown("# ๐ผ๏ธ Groq OCR โ XLSX ่ผธๅบๅทฅๅ
ท")
gr.Markdown("ไธๅณไธๅผตๆๅคๅผตๅ็๏ผ็ณป็ตฑๆ่ชๅ้ฒ่ก OCR ่พจ่ญไธฆๅฏๅบ็บ Excel ๆชๆก๏ผๆฏๅผตๅไธๅ Sheet๏ผ")
with gr.Row():
with gr.Column(scale=1):
image_input = gr.File(
label="๐ท ไธๅณๅ็๏ผๅฏๅค้ธ๏ผ",
file_count="multiple",
file_types=["image"]
)
process_btn = gr.Button("๐ ้ๅง OCR", variant="primary", size="lg")
with gr.Column(scale=2):
log_output = gr.Textbox(
label="๐ ่็ๆฅ่ช",
lines=20,
max_lines=30,
#show_copy_button=True
)
with gr.Row():
download_file = gr.File(label="๐พ ไธ่ผ XLSX ๆชๆก")
with gr.Row():
preview_table = gr.Dataframe(
label="๐ ็ตๆ้ ่ฆฝ",
headers=["ๅ็ๅ็จฑ", "่ก่", "ๅ
งๅฎน"],
wrap=True
)
# ็ถๅฎไบไปถ
process_btn.click(
fn=process_images,
inputs=[image_input],
outputs=[log_output, download_file, preview_table]
)
gr.Markdown("---")
gr.Markdown("๐ก **ไฝฟ็จ่ชชๆ**๏ผไธๅณๅ็ โ ้ปๆใ้ๅง OCRใโ ็ญๅพ
่็ๅฎๆ โ ไธ่ผ XLSX ๆชๆก")
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
# ๅๅๆ็จ
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
if __name__ == "__main__":
demo.launch(
share=False, # ่จญ็บ True ๅฏ็ข็ๅ
ฌ้ๅไบซ้ฃ็ต
server_name="0.0.0.0", # ๅ
่จฑๅค้จ่จชๅ
server_port=7860 # ๆๅฎ็ซฏๅฃ
) |