Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248# ============================================================# Groq OCR + XLSX Export โ Gradio ็# ไฝฟ็จๆนๆณ๏ผๅท่กๆญค็จๅผๅพๆๅจ็่ฆฝๅจ้ๅ Gradio ไป้ข# ============================================================
import base64import ioimport reimport osfrom datetime import datetimefrom PIL import Imagefrom groq import Groqimport 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 # ๆๅฎ็ซฏๅฃ )app.pyAdded+248