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