Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,25 +1,319 @@
|
|
1 |
-
import
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
"text": "import gradio as gr import sqlite3 import json from huggingface_hub import hf_hub_download, hf_hub_upload import os from pathlib import Path from reportlab.lib.pagesizes import A4 from reportlab.lib.units import cm from reportlab.pdfgen import canvas from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont import qrcode import zipfile import io from dotenv import load_dotenv import time # อ่าน .env (ถ้ามี) load_dotenv() REPO_ID = os.getenv(\"REPO_ID\", \"your-username/worker-management\") ORIGINAL_REPO_ID = os.getenv(\"ORIGINAL_REPO_ID\", None) # ตั้งค่าฟอนต์ try: pdfmetrics.registerFont(TTFont('THSarabun', 'THSarabunNew.ttf')) pdfmetrics.registerFont(TTFont('THSarabunBold', 'THSarabunNew-Bold.ttf')) except Exception as e: raise Exception(f\"Error loading fonts: {e}\") # ฟังก์ชันแปลงวันที่เป็นภาษาไทย def thai_date_time(timestamp): months = { 1: \"มกราคม\", 2: \"กุมภาพันธ์\", 3: \"มีนาคม\", 4: \"เมษายน\", 5: \"พฤษภาคม\", 6: \"มิถุนายน\", 7: \"กรกฎาคม\", 8: \"สิงหาคม\", 9: \"กันยายน\", 10: \"ตุลาคม\", 11: \"พฤศจิกายน\", 12: \"ธันวาคม\" } dt = time.localtime(timestamp) day = dt.tm_mday month = months[dt.tm_mon] year = dt.tm_year + 543 hour = dt.tm_hour minute = dt.tm_min period = \"น\" return f\"{day:02d} {month} {year} {hour:02d}:{minute:02d} {period}\" # เริ่มต้นฐานข้อมูล def init_db(): conn = sqlite3.connect(\"workers.db\") c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS workers ( request_number TEXT PRIMARY KEY, english_name TEXT, foreign_reference_number TEXT, id_number TEXT, nationality TEXT, receipt_number TEXT, payment_number TEXT )''') c.execute('''CREATE TABLE IF NOT EXISTS attachments ( request_number TEXT, file_url TEXT, FOREIGN KEY(request_number) REFERENCES workers(request_number) )''') c.execute('''CREATE TABLE IF NOT EXISTS pdfs ( request_number TEXT, pdf_url TEXT, FOREIGN KEY(request_number) REFERENCES workers(request_number) )''') conn.commit() conn.close() # นำเข้า JSON def import_json_to_db(): try: json_path = hf_hub_download(repo_id=REPO_ID, filename=\"worker-database.json\", repo_type=\"space\") with open(json_path, 'r', encoding='utf-8') as f: data = json.load(f) conn = sqlite3.connect(\"workers.db\") c = conn.cursor() for record in data: c.execute('''INSERT OR IGNORE INTO workers ( request_number, english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number ) VALUES (?, ?, ?, ?, ?, ?, ?)''', ( record['เลขคำขอ'], record['ชื่อภาษาอังกฤษ'], record['หมายเลขอ้างอิงคนต่างด้าว'], record['หมายเลขประจำตัว'], record['สัญชาติ'], record['เลขที่บนขวาใบเสร็จ'], record['หมายเลขชำระเงิน'] )) conn.commit() conn.close() except Exception as e: print(f\"Error importing JSON: {e}\") # สำรองฐานข้อมูล def backup_db(): try: hf_hub_upload(repo_id=REPO_ID, path_in_repo=\"workers.db\", path_or_fileobj=\"workers.db\", repo_type=\"space\") except Exception as e: print(f\"Error backing up database: {e}\") # ดึงเลขคำขอถัดไป def get_next_request_number(): conn = sqlite3.connect(\"workers.db\") c = conn.cursor() c.execute(\"SELECT request_number FROM workers\") request_numbers = c.fetchall() conn.close() if not request_numbers: return \"WP-68-366-150\" max_num = max([int(num[0].split('-')[-1]) for num in request_numbers]) return f\"WP-68-366-{max_num + 1:03d}\" # สร้าง PDF def create_receipt_pdf(request_number, english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number): filename = f\"pdfs/receipt_{request_number}.pdf\" local_path = f\"temp_{request_number}.pdf\" c = canvas.Canvas(local_path, pagesize=A4) # ใช้สไตล์จาก main (5).css c.setFont(\"THSarabunBold\", 52.284 / 2.83465) # fs0 c.drawString(2*cm, 28*cm, \"กระทรวงแรงงาน\") c.setFont(\"THSarabun\", 35.212 / 2.83465) # fs3 c.drawString(2*cm, 27.5*cm, \"ใบเสร็จรับเงิน (ต้นฉบับ)\") c.drawString(2*cm, 26*cm, f\"เลขที่: {receipt_number}\") c.drawString(2*cm, 25.5*cm, \"ที่ทำการ: สำนักบริหารแรงงานต่างด้าว\") c.drawString(2*cm, 25*cm, \"วันที่: 01 เมษายน 2568\") # คงวันที่เดิม c.drawString(2*cm, 24.5*cm, f\"เลขที่ใบชำระเงิน: {payment_number}\") c.drawString(2*cm, 24*cm, f\"เลขรับคำขอที่: {request_number}\") c.drawString(2*cm, 23.5*cm, f\"ชื่อผู้ชำระเงิน: {english_name}\") c.drawString(2*cm, 23*cm, f\"สัญชาติ: {nationality}\") c.drawString(2*cm, 22.5*cm, f\"เลขอ้างอิงคนต่างด้าว: {foreign_reference_number}\") c.drawString(2*cm, 22*cm, f\"หมายเลขประจำตัวคนต่างด้าว: {id_number}\") c.drawString(2*cm, 21.5*cm, \"ชื่อนายจ้าง / สถานประกอบการ: บริษัท บาน กง เอ็นจิเนียริ่ง จำกัด\") c.drawString(2*cm, 21*cm, \"เลขประจำตัวนายจ้าง: 0415567000061\") c.setFont(\"THSarabunBold\", 35.212 / 2.83465) c.drawString(2*cm, 20*cm, \"รายการ\") c.setFont(\"THSarabun\", 35.212 / 2.83465) c.drawString(2*cm, 19.5*cm, \"1. ค่าธรรมเนียมในการยื่นคำขอ ฉบับละ 100 บาท: 100.00\") c.drawString(2*cm, 19*cm, \"2. ค่าธรรมเนียม: 900.00\") c.drawString(2*cm, 18.5*cm, \"รวมเป็นเงินทั้งสิ้น (บาท): (หนึ่งพันบาทถ้วน) 1,000.00\") c.drawString(2*cm, 18*cm, \"ได้รับเงินไว้เป็นการถูกต้องแล้ว\") c.drawString(2*cm, 17.5*cm, \"(ลงชื่อ) นางสาวอารีวรรณ โพธิ์นิ่มแดง (ผู้รับเงิน)\") c.drawString(2*cm, 17*cm, \"ตำแหน่ง: นักวิชาการแรงงานชำนาญการ\") # QR Code (ใช้ URL ถาวร) pdf_url = f\"https://huggingface.co/spaces/{REPO_ID}/raw/main/{filename}\" qr = qrcode.make(pdf_url) qr.save(\"temp_qr.png\") c.drawImage(\"temp_qr.png\", 15*cm, 15*cm, width=3*cm, height=3*cm) # เพิ่ม print timestamp ที่ด้านล่าง c.setFont(\"THSarabun\", 20 / 2.83465) # ขนาดเล็กสำหรับ footer print_time = thai_date_time(time.time()) c.drawString(2*cm, 2*cm, f\"พิมพ์เมื่อ: {print_time}\") c.showPage() c.save() # อัพโหลด PDF ไปยัง Space ใหม่ try: hf_hub_upload(repo_id=REPO_ID, path_in_repo=filename, path_or_fileobj=local_path, repo_type=\"space\") except Exception as e: print(f\"Error uploading PDF to Space: {e}\") # อัพโหลดไปยัง Space เดิม (ถ้ามี) if ORIGINAL_REPO_ID: try: hf_hub_upload(repo_id=ORIGINAL_REPO_ID, path_in_repo=filename, path_or_fileobj=local_path, repo_type=\"space\") except Exception as e: print(f\"Error uploading to original Space: {e}\") # บันทึกข้อมูล PDF conn = sqlite3.connect(\"workers.db\") c = conn.cursor() c.execute(\"INSERT OR REPLACE INTO pdfs (request_number, pdf_url) VALUES (?, ?)\", (request_number, pdf_url)) conn.commit() conn.close() return filename # คืนค่า pdfs/receipt_xxx.pdf # ตรวจสอบข้อมูล def validate_input(english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number): if not id_number or not id_number.isdigit() or len(id_number) != 13: return \"หมายเลขประจำตัวต้องเป็นตัวเลข 13 หลัก\" if not receipt_number or not payment_number: return \"กรุณากรอกเลขที่ใบเสร็จและหมายเลขชำระเงิน\" return None # เพิ่มข้อมูลพนักงาน def add_worker(english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number, attachments): error = validate_input(english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number) if error: return error request_number = get_next_request_number() # บันทึกข้อมูล conn = sqlite3.connect(\"workers.db\") c = conn.cursor() c.execute('''INSERT INTO workers ( request_number, english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number ) VALUES (?, ?, ?, ?, ?, ?, ?)''', ( request_number, english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number )) # จัดการไฟล์แนบ attachment_urls = [] for i, file_data in enumerate(attachments or []): filename = f\"attachments/file_{request_number}_{i}_{os.path.basename(file_data.name)}\" try: hf_hub_upload(repo_id=REPO_ID, path_in_repo=filename, path_or_fileobj=file_data, repo_type=\"space\") url = f\"https://huggingface.co/spaces/{REPO_ID}/raw/main/{filename}\" c.execute(\"INSERT INTO attachments (request_number, file_url) VALUES (?, ?)\", (request_number, url)) attachment_urls.append(url) except Exception as e: print(f\"Error uploading attachment: {e}\") conn.commit() conn.close() # สร้าง PDF pdf_path = create_receipt_pdf(request_number, english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number) # สำรองฐานข้อมูล backup_db() return f\"เพิ่มข้อมูลพนักงานสำเร็จ! เลขคำขอ: {request_number}\\nPDF: {pdf_path}\\nไฟล์แนบ: {', '.join(attachment_urls) if attachment_urls else 'ไม่มีไฟล์แนบ'}\" # ดาวน์โหลด PDF ทั้งหมด def download_all_pdfs(): conn = sqlite3.connect(\"workers.db\") c = conn.cursor() c.execute(\"SELECT request_number, pdf_url FROM pdfs\") pdfs = c.fetchall() conn.close() zip_buffer = io.BytesIO() with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file: for request_number, pdf_url in pdfs: try: local_path = hf_hub_download(repo_id=REPO_ID, filename=f\"pdfs/receipt_{request_number}.pdf\", repo_type=\"space\") zip_file.write(local_path, f\"receipt_{request_number}.pdf\") except: continue zip_path = \"all_receipts.zip\" with open(zip_path, 'wb') as f: f.write(zip_buffer.getvalue()) try: hf_hub_upload(repo_id=REPO_ID, path_in_repo=\"all_receipts.zip\", path_or_fileobj=zip_path, repo_type=\"space\") except Exception as e: print(f\"Error uploading ZIP: {e}\") return f\"pdfs/all_receipts.zip\" # เริ่มต้นฐานข้อมูลและนำเข้า JSON init_db() import_json_to_db() # อินเทอร์เฟซ Gradio with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown(\"## เพิ่มข้อมูลพนักงานใหม่\") with gr.Row(): english_name = gr.Textbox(label=\"ชื่อภาษาอังกฤษ\", placeholder=\"เช่น MR. AUNG KYAW\", lines=1) foreign_reference_number = gr.Textbox(label=\"หมายเลขอ้างอิงคนต่างด้าว\", placeholder=\"เช่น 2492102076212\", lines=1) with gr.Row(): id_number = gr.Textbox(label=\"หมายเลขประจำตัว (13 หลัก)\", placeholder=\"เช่น 6685490000472\", lines=1) nationality = gr.Textbox(label=\"สัญชาติ\", value=\"เมียนมา\", lines=1) with gr.Row(): receipt_number = gr.Textbox(label=\"เลขที่บนขวาใบเสร็จ\", placeholder=\"เช่น 2100680001130\", lines=1) payment_number = gr.Textbox(label=\"หมายเลขชำระเงิน\", placeholder=\"เช่น IV680210/002350\", lines=1) attachments = gr.File(label=\"แนบไฟล์ (สูงสุด 5MB)\", file_count=\"multiple\", file_types=[\".jpg\", \".png\", \".pdf\"], max_file_size=\"5MB\") submit = gr.Button(\"บันทึกข้อมูล\") output = gr.Textbox(label=\"ผลลัพธ์\") gr.Markdown(\"## ดาวน์โหลด PDF ทั้งหมด\") download_all = gr.Button(\"ดาวน์โหลด PDF ทั้งหมด\") download_output = gr.Textbox(label=\"ลิงก์ดาวน์โหลด\") submit.click(fn=add_worker, inputs=[english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number, attachments], outputs=output) download_all.click(fn=download_all_pdfs, outputs=download_output) \ndemo.launch()แก้ไขโค้ดนี้เพื่อนำไปแทนไฟล์ app.py ใน space ซึ่งต้องการให้วิเคราะห์ความเชื่อมโยงของข้อมูลในนั้นก่อนเพราะว่าไฟล์ PDF ที่สร้างขึ้นผมยังไม่รู้ว่ากระบวนการมันจัดเก็บยังไงหน้าตาเป็นยังไงแล้วฐานข้อมูลใช้อะไรแต่ว่าอยากให้จัดการกับไฟล์นี้ตามที่บอกแล้วก็ค่อยสรุปกันอีกที https://huggingface.co/spaces/protae5544/WorkerManagement"
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import sqlite3
|
3 |
+
import json
|
4 |
+
from huggingface_hub import hf_hub_download, hf_hub_upload
|
5 |
+
import os
|
6 |
+
from pathlib import Path
|
7 |
+
from reportlab.lib.pagesizes import A4
|
8 |
+
from reportlab.lib.units import cm
|
9 |
+
from reportlab.pdfgen import canvas
|
10 |
+
from reportlab.pdfbase import pdfmetrics
|
11 |
+
from reportlab.pdfbase.ttfonts import TTFont
|
12 |
+
import qrcode
|
13 |
+
import zipfile
|
14 |
+
import io
|
15 |
+
from dotenv import load_dotenv
|
16 |
+
import time
|
17 |
+
|
18 |
+
# อ่าน .env (ถ้ามี)
|
19 |
+
load_dotenv()
|
20 |
+
REPO_ID = os.getenv("REPO_ID", "your-username/worker-management")
|
21 |
+
ORIGINAL_REPO_ID = os.getenv("ORIGINAL_REPO_ID", None)
|
22 |
+
|
23 |
+
# ตั้งค่าฟอนต์
|
24 |
+
try:
|
25 |
+
pdfmetrics.registerFont(TTFont('THSarabun', 'THSarabunNew.ttf'))
|
26 |
+
pdfmetrics.registerFont(TTFont('THSarabunBold', 'THSarabunNew-Bold.ttf'))
|
27 |
+
except Exception as e:
|
28 |
+
print(f"Warning: Could not load fonts: {e}")
|
29 |
+
# ใช้ฟอนต์เริ่มต้นแทน
|
30 |
+
pass
|
31 |
+
|
32 |
+
# ฟังก์ชันแปลงวันที่เป็นภาษาไทย
|
33 |
+
def thai_date_time(timestamp):
|
34 |
+
months = {
|
35 |
+
1: "มกราคม", 2: "กุมภาพันธ์", 3: "มีนาคม", 4: "เมษายน",
|
36 |
+
5: "พฤษภาคม", 6: "มิถุนาย��", 7: "กรกฎาคม", 8: "สิงหาคม",
|
37 |
+
9: "กันยายน", 10: "ตุลาคม", 11: "พฤศจิกายน", 12: "ธันวาคม"
|
38 |
+
}
|
39 |
+
dt = time.localtime(timestamp)
|
40 |
+
day = dt.tm_mday
|
41 |
+
month = months[dt.tm_mon]
|
42 |
+
year = dt.tm_year + 543
|
43 |
+
hour = dt.tm_hour
|
44 |
+
minute = dt.tm_min
|
45 |
+
period = "น"
|
46 |
+
return f"{day:02d} {month} {year} {hour:02d}:{minute:02d} {period}"
|
47 |
+
|
48 |
+
# เริ่มต้นฐานข้อมูล
|
49 |
+
def init_db():
|
50 |
+
conn = sqlite3.connect("workers.db")
|
51 |
+
c = conn.cursor()
|
52 |
+
c.execute('''CREATE TABLE IF NOT EXISTS workers (
|
53 |
+
request_number TEXT PRIMARY KEY,
|
54 |
+
english_name TEXT,
|
55 |
+
foreign_reference_number TEXT,
|
56 |
+
id_number TEXT,
|
57 |
+
nationality TEXT,
|
58 |
+
receipt_number TEXT,
|
59 |
+
payment_number TEXT
|
60 |
+
)''')
|
61 |
+
c.execute('''CREATE TABLE IF NOT EXISTS attachments (
|
62 |
+
request_number TEXT,
|
63 |
+
file_url TEXT,
|
64 |
+
FOREIGN KEY(request_number) REFERENCES workers(request_number)
|
65 |
+
)''')
|
66 |
+
c.execute('''CREATE TABLE IF NOT EXISTS pdfs (
|
67 |
+
request_number TEXT,
|
68 |
+
pdf_url TEXT,
|
69 |
+
FOREIGN KEY(request_number) REFERENCES workers(request_number)
|
70 |
+
)''')
|
71 |
+
conn.commit()
|
72 |
+
conn.close()
|
73 |
+
|
74 |
+
# นำเข้า JSON
|
75 |
+
def import_json_to_db():
|
76 |
+
try:
|
77 |
+
json_path = hf_hub_download(repo_id=REPO_ID, filename="worker-database.json", repo_type="space")
|
78 |
+
with open(json_path, 'r', encoding='utf-8') as f:
|
79 |
+
data = json.load(f)
|
80 |
+
|
81 |
+
conn = sqlite3.connect("workers.db")
|
82 |
+
c = conn.cursor()
|
83 |
+
for record in data:
|
84 |
+
c.execute('''INSERT OR IGNORE INTO workers (
|
85 |
+
request_number, english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number
|
86 |
+
) VALUES (?, ?, ?, ?, ?, ?, ?)''', (
|
87 |
+
record['เลขคำขอ'],
|
88 |
+
record['ชื่อภาษาอังกฤษ'],
|
89 |
+
record['หมายเลขอ้างอิงคนต่างด้าว'],
|
90 |
+
record['หมายเลขประจำตัว'],
|
91 |
+
record['สัญชาติ'],
|
92 |
+
record['เลขที่บนขวาใบเสร็จ'],
|
93 |
+
record['หมายเลขชำระเงิน']
|
94 |
+
))
|
95 |
+
conn.commit()
|
96 |
+
conn.close()
|
97 |
+
except Exception as e:
|
98 |
+
print(f"Error importing JSON: {e}")
|
99 |
+
|
100 |
+
# สำรองฐานข้อมูล
|
101 |
+
def backup_db():
|
102 |
+
try:
|
103 |
+
hf_hub_upload(repo_id=REPO_ID, path_in_repo="workers.db", path_or_fileobj="workers.db", repo_type="space")
|
104 |
+
except Exception as e:
|
105 |
+
print(f"Error backing up database: {e}")
|
106 |
+
|
107 |
+
# ดึงเลขคำขอถัดไป
|
108 |
+
def get_next_request_number():
|
109 |
+
conn = sqlite3.connect("workers.db")
|
110 |
+
c = conn.cursor()
|
111 |
+
c.execute("SELECT request_number FROM workers")
|
112 |
+
request_numbers = c.fetchall()
|
113 |
+
conn.close()
|
114 |
+
|
115 |
+
if not request_numbers:
|
116 |
+
return "WP-68-366-150"
|
117 |
+
|
118 |
+
max_num = max([int(num[0].split('-')[-1]) for num in request_numbers])
|
119 |
+
return f"WP-68-366-{max_num + 1:03d}"
|
120 |
+
|
121 |
+
# สร้าง PDF
|
122 |
+
def create_receipt_pdf(request_number, english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number):
|
123 |
+
filename = f"pdfs/receipt_{request_number}.pdf"
|
124 |
+
local_path = f"temp_{request_number}.pdf"
|
125 |
+
c = canvas.Canvas(local_path, pagesize=A4)
|
126 |
+
|
127 |
+
# ใช้ฟอนต์ที่มี หรือ Helvetica ถ้าไม่มี
|
128 |
+
try:
|
129 |
+
c.setFont("THSarabunBold", 18)
|
130 |
+
except:
|
131 |
+
c.setFont("Helvetica-Bold", 18)
|
132 |
+
|
133 |
+
c.drawString(2*cm, 28*cm, "Ministry of Labour")
|
134 |
+
|
135 |
+
try:
|
136 |
+
c.setFont("THSarabun", 12)
|
137 |
+
except:
|
138 |
+
c.setFont("Helvetica", 12)
|
139 |
+
|
140 |
+
c.drawString(2*cm, 27.5*cm, "Receipt (Original)")
|
141 |
+
c.drawString(2*cm, 26*cm, f"Number: {receipt_number}")
|
142 |
+
c.drawString(2*cm, 25.5*cm, "Office: Bureau of Foreign Workers Administration")
|
143 |
+
c.drawString(2*cm, 25*cm, "Date: 01 April 2025")
|
144 |
+
c.drawString(2*cm, 24.5*cm, f"Payment Number: {payment_number}")
|
145 |
+
c.drawString(2*cm, 24*cm, f"Request Number: {request_number}")
|
146 |
+
c.drawString(2*cm, 23.5*cm, f"Payer Name: {english_name}")
|
147 |
+
c.drawString(2*cm, 23*cm, f"Nationality: {nationality}")
|
148 |
+
c.drawString(2*cm, 22.5*cm, f"Foreign Reference Number: {foreign_reference_number}")
|
149 |
+
c.drawString(2*cm, 22*cm, f"Foreign Worker ID: {id_number}")
|
150 |
+
c.drawString(2*cm, 21.5*cm, "Employer: Ban Kong Engineering Co., Ltd.")
|
151 |
+
c.drawString(2*cm, 21*cm, "Employer ID: 0415567000061")
|
152 |
+
|
153 |
+
try:
|
154 |
+
c.setFont("THSarabunBold", 12)
|
155 |
+
except:
|
156 |
+
c.setFont("Helvetica-Bold", 12)
|
157 |
+
|
158 |
+
c.drawString(2*cm, 20*cm, "Items")
|
159 |
+
|
160 |
+
try:
|
161 |
+
c.setFont("THSarabun", 12)
|
162 |
+
except:
|
163 |
+
c.setFont("Helvetica", 12)
|
164 |
+
|
165 |
+
c.drawString(2*cm, 19.5*cm, "1. Application fee 100 Baht each: 100.00")
|
166 |
+
c.drawString(2*cm, 19*cm, "2. Service fee: 900.00")
|
167 |
+
c.drawString(2*cm, 18.5*cm, "Total amount (Baht): (One thousand Baht) 1,000.00")
|
168 |
+
c.drawString(2*cm, 18*cm, "Payment received correctly")
|
169 |
+
c.drawString(2*cm, 17.5*cm, "(Signature) Ms. Areewan Pho Nim Daeng (Receiver)")
|
170 |
+
c.drawString(2*cm, 17*cm, "Position: Senior Labor Academic")
|
171 |
+
|
172 |
+
# QR Code
|
173 |
+
pdf_url = f"https://huggingface.co/spaces/{REPO_ID}/raw/main/{filename}"
|
174 |
+
try:
|
175 |
+
qr = qrcode.make(pdf_url)
|
176 |
+
qr.save("temp_qr.png")
|
177 |
+
c.drawImage("temp_qr.png", 15*cm, 15*cm, width=3*cm, height=3*cm)
|
178 |
+
except Exception as e:
|
179 |
+
print(f"Error creating QR code: {e}")
|
180 |
+
|
181 |
+
# เพิ่ม print timestamp ที่ด้านล่าง
|
182 |
+
try:
|
183 |
+
c.setFont("THSarabun", 8)
|
184 |
+
except:
|
185 |
+
c.setFont("Helvetica", 8)
|
186 |
+
|
187 |
+
print_time = thai_date_time(time.time())
|
188 |
+
c.drawString(2*cm, 2*cm, f"Printed: {print_time}")
|
189 |
+
|
190 |
+
c.showPage()
|
191 |
+
c.save()
|
192 |
+
|
193 |
+
# อัพโหลด PDF ไปยัง Space ใหม่
|
194 |
+
try:
|
195 |
+
hf_hub_upload(repo_id=REPO_ID, path_in_repo=filename, path_or_fileobj=local_path, repo_type="space")
|
196 |
+
except Exception as e:
|
197 |
+
print(f"Error uploading PDF to Space: {e}")
|
198 |
+
|
199 |
+
# อัพโหลดไปยัง Space เดิม (ถ้ามี)
|
200 |
+
if ORIGINAL_REPO_ID:
|
201 |
+
try:
|
202 |
+
hf_hub_upload(repo_id=ORIGINAL_REPO_ID, path_in_repo=filename, path_or_fileobj=local_path, repo_type="space")
|
203 |
+
except Exception as e:
|
204 |
+
print(f"Error uploading to original Space: {e}")
|
205 |
+
|
206 |
+
# บันทึกข้อมูล PDF
|
207 |
+
conn = sqlite3.connect("workers.db")
|
208 |
+
c = conn.cursor()
|
209 |
+
c.execute("INSERT OR REPLACE INTO pdfs (request_number, pdf_url) VALUES (?, ?)",
|
210 |
+
(request_number, pdf_url))
|
211 |
+
conn.commit()
|
212 |
+
conn.close()
|
213 |
+
|
214 |
+
return filename
|
215 |
+
|
216 |
+
# ตรวจสอบข้อมูล
|
217 |
+
def validate_input(english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number):
|
218 |
+
if not id_number or not id_number.isdigit() or len(id_number) != 13:
|
219 |
+
return "หมายเลขประจำตัวต้องเป็นตัวเลข 13 หลัก"
|
220 |
+
if not receipt_number or not payment_number:
|
221 |
+
return "กรุณากรอกเลขที่ใบเสร็จและหมายเลขชำระเงิน"
|
222 |
+
return None
|
223 |
+
|
224 |
+
# เพิ่มข้อมูลพนักงาน
|
225 |
+
def add_worker(english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number, attachments):
|
226 |
+
error = validate_input(english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number)
|
227 |
+
if error:
|
228 |
+
return error
|
229 |
+
|
230 |
+
request_number = get_next_request_number()
|
231 |
+
|
232 |
+
# บันทึกข้อมูล
|
233 |
+
conn = sqlite3.connect("workers.db")
|
234 |
+
c = conn.cursor()
|
235 |
+
c.execute('''INSERT INTO workers (
|
236 |
+
request_number, english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number
|
237 |
+
) VALUES (?, ?, ?, ?, ?, ?, ?)''', (
|
238 |
+
request_number, english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number
|
239 |
+
))
|
240 |
+
|
241 |
+
# จัดการไฟล์แนบ
|
242 |
+
attachment_urls = []
|
243 |
+
for i, file_data in enumerate(attachments or []):
|
244 |
+
filename = f"attachments/file_{request_number}_{i}_{os.path.basename(file_data.name)}"
|
245 |
+
try:
|
246 |
+
hf_hub_upload(repo_id=REPO_ID, path_in_repo=filename, path_or_fileobj=file_data, repo_type="space")
|
247 |
+
url = f"https://huggingface.co/spaces/{REPO_ID}/raw/main/{filename}"
|
248 |
+
c.execute("INSERT INTO attachments (request_number, file_url) VALUES (?, ?)", (request_number, url))
|
249 |
+
attachment_urls.append(url)
|
250 |
+
except Exception as e:
|
251 |
+
print(f"Error uploading attachment: {e}")
|
252 |
+
|
253 |
+
conn.commit()
|
254 |
+
conn.close()
|
255 |
+
|
256 |
+
# สร้าง PDF
|
257 |
+
pdf_path = create_receipt_pdf(request_number, english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number)
|
258 |
+
|
259 |
+
# สำรองฐานข้อมูล
|
260 |
+
backup_db()
|
261 |
+
|
262 |
+
return f"เพิ่มข้อมูลพนักงานสำเร็จ! เลขคำขอ: {request_number}\nPDF: {pdf_path}\nไฟล์แนบ: {', '.join(attachment_urls) if attachment_urls else 'ไม่มีไฟล์แนบ'}"
|
263 |
+
|
264 |
+
# ดาวน์โหลด PDF ทั้งหมด
|
265 |
+
def download_all_pdfs():
|
266 |
+
conn = sqlite3.connect("workers.db")
|
267 |
+
c = conn.cursor()
|
268 |
+
c.execute("SELECT request_number, pdf_url FROM pdfs")
|
269 |
+
pdfs = c.fetchall()
|
270 |
+
conn.close()
|
271 |
+
|
272 |
+
zip_buffer = io.BytesIO()
|
273 |
+
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
|
274 |
+
for request_number, pdf_url in pdfs:
|
275 |
+
try:
|
276 |
+
local_path = hf_hub_download(repo_id=REPO_ID, filename=f"pdfs/receipt_{request_number}.pdf", repo_type="space")
|
277 |
+
zip_file.write(local_path, f"receipt_{request_number}.pdf")
|
278 |
+
except:
|
279 |
+
continue
|
280 |
+
|
281 |
+
zip_path = "all_receipts.zip"
|
282 |
+
with open(zip_path, 'wb') as f:
|
283 |
+
f.write(zip_buffer.getvalue())
|
284 |
+
|
285 |
+
try:
|
286 |
+
hf_hub_upload(repo_id=REPO_ID, path_in_repo="all_receipts.zip", path_or_fileobj=zip_path, repo_type="space")
|
287 |
+
except Exception as e:
|
288 |
+
print(f"Error uploading ZIP: {e}")
|
289 |
+
|
290 |
+
return f"pdfs/all_receipts.zip"
|
291 |
+
|
292 |
+
# เริ่มต้นฐานข้อมูลและนำเข้า JSON
|
293 |
+
init_db()
|
294 |
+
import_json_to_db()
|
295 |
+
|
296 |
+
# อินเทอร์เฟซ Gradio
|
297 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
298 |
+
gr.Markdown("## เพิ่มข้อมูลพนักงานใหม่")
|
299 |
+
with gr.Row():
|
300 |
+
english_name = gr.Textbox(label="ชื่อภาษาอังกฤษ", placeholder="เช่น MR. AUNG KYAW", lines=1)
|
301 |
+
foreign_reference_number = gr.Textbox(label="หมายเลขอ้างอิงคนต่างด้าว", placeholder="เช่น 2492102076212", lines=1)
|
302 |
+
with gr.Row():
|
303 |
+
id_number = gr.Textbox(label="หมายเลขประจำตัว (13 หลัก)", placeholder="เช่น 6685490000472", lines=1)
|
304 |
+
nationality = gr.Textbox(label="สัญชาติ", value="เมียนมา", lines=1)
|
305 |
+
with gr.Row():
|
306 |
+
receipt_number = gr.Textbox(label="เลขที่บนขวาใบเสร็จ", placeholder="เช่น 2100680001130", lines=1)
|
307 |
+
payment_number = gr.Textbox(label="หมายเลขชำระเงิน", placeholder="เช่น IV680210/002350", lines=1)
|
308 |
+
attachments = gr.File(label="แนบไฟล์ (สูงสุด 5MB)", file_count="multiple", file_types=[".jpg", ".png", ".pdf"], max_file_size="5MB")
|
309 |
+
submit = gr.Button("บันทึกข้อมูล")
|
310 |
+
output = gr.Textbox(label="ผลลัพธ์")
|
311 |
+
|
312 |
+
gr.Markdown("## ดาวน์โหลด PDF ทั้งหมด")
|
313 |
+
download_all = gr.Button("ดาวน์โหลด PDF ทั้งหมด")
|
314 |
+
download_output = gr.Textbox(label="ลิงก์ดาวน์โหลด")
|
315 |
+
|
316 |
+
submit.click(fn=add_worker, inputs=[english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number, attachments], outputs=output)
|
317 |
+
download_all.click(fn=download_all_pdfs, outputs=download_output)
|
318 |
+
|
319 |
+
demo.launch()
|