protae5544 commited on
Commit
6830804
·
verified ·
1 Parent(s): 1ecca81

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +176 -590
app.py CHANGED
@@ -1,94 +1,40 @@
1
  import gradio as gr
2
  import sqlite3
3
- import json
4
- from huggingface_hub import hf_hub_download, upload_file
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
  import requests
18
 
19
- # อ่าน .env (ถ้ามี)
20
- load_dotenv()
21
- REPO_ID = os.getenv("REPO_ID", "protae5544/WorkerManagement")
22
- ORIGINAL_REPO_ID = os.getenv("ORIGINAL_REPO_ID", None)
23
 
24
- # ดาวน์โหลดฟอนต์จาก Space อื่น
25
- def download_fonts():
26
  try:
27
- # ดาวน์โหลดฟอนต์จาก protae5544/worberkit2024poe
28
- font_urls = {
29
- 'THSarabunNew.ttf': 'https://huggingface.co/spaces/protae5544/worberkit2024poe/resolve/main/fontCSS/subset-THSarabunNew.woff2',
30
- 'THSarabunNew-Bold.ttf': 'https://huggingface.co/spaces/protae5544/worberkit2024poe/resolve/main/fontCSS/subset-THSarabunNew-Bold.woff2'
31
- }
32
 
33
- # ใช้ฟอนต์ที่มีอยู่แล้วในระบบ หรือดาวน์โหลดจาก Google Fonts
34
- google_fonts = {
35
- 'THSarabunNew.ttf': 'https://fonts.gstatic.com/s/sarabun/v13/DtVjJx26TKEqsc-lWcmw-wKE7wM.ttf',
36
- 'THSarabunNew-Bold.ttf': 'https://fonts.gstatic.com/s/sarabun/v13/DtVmJx26TKEqsc-lWcmw5wq0hwOKBwXcb0A.ttf'
37
- }
38
 
39
- for filename, url in google_fonts.items():
40
- if not os.path.exists(filename):
41
- try:
42
- response = requests.get(url, timeout=10)
43
- if response.status_code == 200:
44
- with open(filename, 'wb') as f:
45
- f.write(response.content)
46
- print(f"Downloaded font: {filename}")
47
- except Exception as e:
48
- print(f"Error downloading {filename}: {e}")
49
-
50
- except Exception as e:
51
- print(f"Error in download_fonts: {e}")
52
-
53
- # ตั้งค่าฟอนต์
54
- def setup_fonts():
55
- try:
56
- # ดาวน์โหลดฟอนต์ก่อน
57
- download_fonts()
58
 
59
- # ลงทะเบียนฟอนต์
60
- if os.path.exists('THSarabunNew.ttf'):
61
- pdfmetrics.registerFont(TTFont('THSarabun', 'THSarabunNew.ttf'))
62
- print("Registered THSarabun font")
63
 
64
- if os.path.exists('THSarabunNew-Bold.ttf'):
65
- pdfmetrics.registerFont(TTFont('THSarabunBold', 'THSarabunNew-Bold.ttf'))
66
- print("Registered THSarabunBold font")
67
-
68
  return True
69
- except Exception as e:
70
- print(f"Warning: Could not load fonts: {e}")
71
  return False
72
 
73
- # เริ่มต้นฟอนต์
74
- font_available = setup_fonts()
75
-
76
- # ฟังก์ชันแปลงวันที่เป็นภาษาไทย
77
- def thai_date_time(timestamp):
78
- months = {
79
- 1: "มกราคม", 2: "กุมภาพันธ์", 3: "มีนาคม", 4: "เมษายน",
80
- 5: "พฤษภาคม", 6: "มิถุนายน", 7: "กรกฎาคม", 8: "สิงหาคม",
81
- 9: "กันยายน", 10: "ตุลาคม", 11: "พฤศจิกายน", 12: "ธันวาคม"
82
- }
83
- dt = time.localtime(timestamp)
84
- day = dt.tm_mday
85
- month = months[dt.tm_mon]
86
- year = dt.tm_year + 543
87
- hour = dt.tm_hour
88
- minute = dt.tm_min
89
- return f"{day:02d} {month} {year} {hour:02d}:{minute:02d} น."
90
-
91
- # เริ่มต้นฐานข้อมูล
92
  def init_db():
93
  conn = sqlite3.connect("workers.db")
94
  c = conn.cursor()
@@ -102,552 +48,192 @@ def init_db():
102
  payment_number TEXT,
103
  created_at TEXT
104
  )''')
105
- c.execute('''CREATE TABLE IF NOT EXISTS attachments (
106
- request_number TEXT,
107
- file_url TEXT,
108
- FOREIGN KEY(request_number) REFERENCES workers(request_number)
109
- )''')
110
- c.execute('''CREATE TABLE IF NOT EXISTS pdfs (
111
- request_number TEXT,
112
- pdf_url TEXT,
113
- FOREIGN KEY(request_number) REFERENCES workers(request_number)
114
- )''')
115
  conn.commit()
116
  conn.close()
117
 
118
- # สำรองฐานข้อมูล
119
- def create_receipt_pdf(request_number, english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number):
120
- filename = f"pdfs/receipt_{request_number}.pdf"
121
- local_path = f"temp_{request_number}.pdf"
122
 
123
- # สร้างโฟลเดอร์ pdfs ถ้าไม่มี
124
- os.makedirs("pdfs", exist_ok=True)
125
-
126
- c = canvas.Canvas(local_path, pagesize=A4)
127
  width, height = A4
128
 
129
- # กำหนดตำแหน่งและขนาดตามเอกสารต้นฉบับ
130
- # ใช้ Helvetica สำหรับความเข้ากันได้
131
-
132
- # หัวเอกสาร - กระทรวงแรงงาน
133
- c.setFont("Helvetica-Bold", 20)
134
- c.drawCentredText(width/2, height-80, "กระทรวงแรงงาน")
135
-
136
- c.setFont("Helvetica-Bold", 16)
137
- c.drawCentredText(width/2, height-110, "ใบเสร็จรับเงิน (ต้นฉบับ)")
138
-
139
- # ข้อมูลส่วนหัว
140
- c.setFont("Helvetica", 12)
141
- y_pos = height - 150
142
-
143
- c.drawString(50, y_pos, f"เลขที่: {receipt_number}")
144
- c.drawString(350, y_pos, "แบบ ภ.1600-034")
145
-
146
- y_pos -= 25
147
- c.drawString(50, y_pos, "ที่ทำการ: สำนักบริหารแรงงานต่างด้าว")
148
-
149
- y_pos -= 25
150
- c.drawString(50, y_pos, "วันที่: 01 เมษายน 2568")
151
-
152
- y_pos -= 25
153
- c.drawString(50, y_pos, f"เลขที่ใบชำระเงิน: {payment_number}")
154
-
155
- y_pos -= 25
156
- c.drawString(50, y_pos, f"เลขรับคำขอที่: {request_number}")
157
-
158
- # ข้อมูลผู้ชำระเงิน
159
- y_pos -= 40
160
- c.setFont("Helvetica-Bold", 12)
161
- c.drawString(50, y_pos, "ข้อมูลผู้ชำระเงิน:")
162
-
163
- y_pos -= 25
164
- c.setFont("Helvetica", 12)
165
- c.drawString(50, y_pos, f"ชื่อผู้ชำระเงิน: {english_name}")
166
-
167
- y_pos -= 20
168
- c.drawString(50, y_pos, f"สัญชาติ: {nationality}")
169
-
170
- y_pos -= 20
171
- c.drawString(50, y_pos, f"เลขอ้างอิงคนต่างด้าว: {foreign_reference_number}")
172
-
173
- y_pos -= 20
174
- c.drawString(50, y_pos, f"หมายเลขประจำตัวคนต่างด้าว: {id_number}")
175
-
176
- # ข้อมูลนายจ้าง
177
- y_pos -= 40
178
- c.setFont("Helvetica-Bold", 12)
179
- c.drawString(50, y_pos, "ข้อมูลนายจ้าง:")
180
-
181
- y_pos -= 25
182
- c.setFont("Helvetica", 12)
183
- c.drawString(50, y_pos, "ชื่อนายจ้าง/สถานประกอบการ: บริษัท บาน กง เอ็นจิเนียริ่ง จำกัด")
184
-
185
- y_pos -= 20
186
- c.drawString(50, y_pos, "เลขประจำตัวนายจ้าง: 0415567000061")
187
-
188
- # รายการค่าธรรมเนียม
189
- y_pos -= 40
190
- c.setFont("Helvetica-Bold", 14)
191
- c.drawString(50, y_pos, "รายการค่าธรรมเนียม")
192
-
193
- # วาดเส้นใต้หัวข้อ
194
- c.line(50, y_pos-5, 500, y_pos-5)
195
-
196
- y_pos -= 30
197
- c.setFont("Helvetica", 12)
198
- c.drawString(70, y_pos, "1. ค่าธรรมเนียมในการยื่นคำขอ ฉบับละ 100 บาท")
199
- c.drawString(450, y_pos, "100.00")
200
-
201
- y_pos -= 25
202
- c.drawString(70, y_pos, "2. ค่าธรรมเนียมการพิจารณา")
203
- c.drawString(450, y_pos, "900.00")
204
-
205
- # เส้นคั่น
206
- y_pos -= 15
207
- c.line(400, y_pos, 500, y_pos)
208
-
209
- y_pos -= 25
210
- c.setFont("Helvetica-Bold", 12)
211
- c.drawString(70, y_pos, "รวมเป็นเงินทั้งสิ้น (บาท): (หนึ่งพันบาทถ้วน)")
212
- c.drawString(430, y_pos, "1,000.00")
213
-
214
- # เส้นใต้ยอดรวม
215
- c.line(400, y_pos-5, 500, y_pos-5)
216
- c.line(400, y_pos-8, 500, y_pos-8)
217
-
218
- # ข้อความรับรอง
219
- y_pos -= 40
220
- c.setFont("Helvetica", 12)
221
- c.drawString(50, y_pos, "ได้รับเงินไว้เป็นการถูกต้องแล้ว")
222
-
223
- # ลายเซ็น
224
- y_pos -= 60
225
- c.drawString(300, y_pos, "(ลงชื่อ) นางสาวอารีวรรณ โพธิ์นิ่มแดง")
226
- c.drawString(350, y_pos-20, "(ผู้รับเงิน)")
227
-
228
- y_pos -= 45
229
- c.drawString(300, y_pos, "ตำแหน่ง: นักวิชาการแรงงานชำนาญการ")
230
-
231
- # QR Code ที่มุมขวาล่าง
232
  pdf_url = f"https://huggingface.co/spaces/{REPO_ID}/resolve/main/{filename}"
233
  try:
234
- qr = qrcode.QRCode(version=1, box_size=8, border=2)
235
- qr.add_data(pdf_url)
236
- qr.make(fit=True)
237
- qr_img = qr.make_image(fill_color="black", back_color="white")
238
- qr_img.save("temp_qr.png")
239
- c.drawImage("temp_qr.png", width-150, 50, width=80, height=80)
240
  except Exception as e:
241
  print(f"Error creating QR code: {e}")
242
 
243
- # Timestamp ที่ด้านล่าง
244
- c.setFont("Helvetica", 8)
245
- print_time = thai_date_time(time.time())
246
- c.drawString(50, 30, f"พิมพ์เมื่อ: {print_time}")
 
 
 
 
 
 
 
 
 
 
247
 
248
- # เส้นขอบกรอบเอกสาร
249
- c.rect(30, 30, width-60, height-60, stroke=1, fill=0)
250
 
251
  c.showPage()
252
  c.save()
253
 
254
- # เพิ่ม HTML version สำหรับ preview และ print
255
- create_html_receipt(request_number, english_name, foreign_reference_number,
256
- id_number, nationality, receipt_number, payment_number)
257
-
258
- # อัพโหลด PDF
259
  try:
260
  upload_file(
261
- path_or_fileobj=local_path,
262
  path_in_repo=filename,
263
  repo_id=REPO_ID,
264
  repo_type="space"
265
  )
266
- print(f"PDF uploaded successfully: {filename}")
267
- except Exception as e:
268
- print(f"Error uploading PDF: {e}")
269
  return None
 
 
 
 
 
 
 
270
 
271
- # บันทึกข้อมูล PDF ในฐานข้อมูล
272
  conn = sqlite3.connect("workers.db")
273
- cursor = conn.cursor()
274
- cursor.execute("INSERT OR REPLACE INTO pdfs (request_number, pdf_url) VALUES (?, ?)",
275
- (request_number, pdf_url))
276
- conn.commit()
277
  conn.close()
278
 
279
- return pdf_url
280
-
281
- # เพิ่มฟังก์ชันสร้าง HTML version
282
- def create_html_receipt(request_number, english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number):
283
- html_filename = f"receipts/receipt_{request_number}.html"
284
- local_html_path = f"temp_{request_number}.html"
285
 
286
- os.makedirs("receipts", exist_ok=True)
 
 
 
 
 
 
 
287
 
288
- pdf_url = f"https://huggingface.co/spaces/{REPO_ID}/resolve/main/pdfs/receipt_{request_number}.pdf"
289
- print_time = thai_date_time(time.time())
 
290
 
291
- html_content = f"""
292
- <!DOCTYPE html>
293
- <html lang="th">
294
- <head>
295
- <meta charset="UTF-8">
296
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
297
- <title>ใบเสร็จรับเงิน - {request_number}</title>
298
- <script src="https://cdn.jsdelivr.net/npm/[email protected]/build/qrcode.min.js"></script>
299
- <style>
300
- @import url('https://fonts.googleapis.com/css2?family=Sarabun:wght@400;600;700&display=swap');
301
-
302
- * {{
303
- margin: 0;
304
- padding: 0;
305
- box-sizing: border-box;
306
- }}
307
-
308
- body {{
309
- font-family: 'Sarabun', Arial, sans-serif;
310
- background: #f5f5f5;
311
- padding: 20px;
312
- }}
313
-
314
- .receipt-container {{
315
- max-width: 800px;
316
- margin: 0 auto;
317
- background: white;
318
- border: 2px solid #000;
319
- padding: 30px;
320
- box-shadow: 0 0 20px rgba(0,0,0,0.1);
321
- }}
322
-
323
- .header {{
324
- text-align: center;
325
- margin-bottom: 30px;
326
- border-bottom: 2px solid #000;
327
- padding-bottom: 20px;
328
- }}
329
-
330
- .header h1 {{
331
- font-size: 24px;
332
- font-weight: 700;
333
- margin-bottom: 10px;
334
- }}
335
-
336
- .header h2 {{
337
- font-size: 18px;
338
- font-weight: 600;
339
- }}
340
-
341
- .info-section {{
342
- margin-bottom: 25px;
343
- }}
344
-
345
- .info-row {{
346
- display: flex;
347
- justify-content: space-between;
348
- margin-bottom: 8px;
349
- padding: 5px 0;
350
- }}
351
-
352
- .info-label {{
353
- font-weight: 600;
354
- }}
355
-
356
- .section-title {{
357
- font-size: 16px;
358
- font-weight: 700;
359
- margin: 20px 0 15px 0;
360
- border-bottom: 1px solid #ccc;
361
- padding-bottom: 5px;
362
- }}
363
-
364
- .fee-table {{
365
- width: 100%;
366
- border-collapse: collapse;
367
- margin: 20px 0;
368
- }}
369
-
370
- .fee-table th,
371
- .fee-table td {{
372
- border: 1px solid #000;
373
- padding: 10px;
374
- text-align: left;
375
- }}
376
-
377
- .fee-table th {{
378
- background: #f0f0f0;
379
- font-weight: 700;
380
- }}
381
-
382
- .amount {{
383
- text-align: right;
384
- font-weight: 600;
385
- }}
386
-
387
- .total-row {{
388
- background: #f9f9f9;
389
- font-weight: 700;
390
- }}
391
-
392
- .signature-section {{
393
- margin-top: 40px;
394
- display: flex;
395
- justify-content: space-between;
396
- align-items: flex-end;
397
- }}
398
-
399
- .signature-box {{
400
- text-align: center;
401
- }}
402
-
403
- .qr-section {{
404
- display: flex;
405
- flex-direction: column;
406
- align-items: center;
407
- }}
408
-
409
- .footer {{
410
- margin-top: 30px;
411
- text-align: center;
412
- font-size: 12px;
413
- color: #666;
414
- border-top: 1px solid #ccc;
415
- padding-top: 15px;
416
- }}
417
-
418
- .download-section {{
419
- text-align: center;
420
- margin: 20px 0;
421
- padding: 15px;
422
- background: #e3f2fd;
423
- border-radius: 8px;
424
- border: 1px solid #2196f3;
425
- }}
426
-
427
- .download-btn {{
428
- background: #2196f3;
429
- color: white;
430
- padding: 10px 20px;
431
- border: none;
432
- border-radius: 5px;
433
- cursor: pointer;
434
- font-size: 16px;
435
- margin: 5px;
436
- text-decoration: none;
437
- display: inline-block;
438
- }}
439
-
440
- .download-btn:hover {{
441
- background: #1976d2;
442
- }}
443
-
444
- /* Print Styles */
445
- @media print {{
446
- body {{
447
- background: white;
448
- padding: 0;
449
- }}
450
-
451
- .receipt-container {{
452
- box-shadow: none;
453
- border: 2px solid #000;
454
- max-width: none;
455
- width: 100%;
456
- }}
457
-
458
- .download-section {{
459
- display: none;
460
- }}
461
-
462
- .no-print {{
463
- display: none;
464
- }}
465
-
466
- /* ปรับขนาดสำหรับการพิมพ์ */
467
- .header h1 {{
468
- font-size: 22px;
469
- }}
470
-
471
- .header h2 {{
472
- font-size: 16px;
473
- }}
474
-
475
- .info-row {{
476
- font-size: 14px;
477
- }}
478
-
479
- .fee-table {{
480
- font-size: 14px;
481
- }}
482
- }}
483
-
484
- @page {{
485
- margin: 1cm;
486
- size: A4;
487
- }}
488
- </style>
489
- </head>
490
- <body>
491
- <div class="receipt-container">
492
- <!-- Header -->
493
- <div class="header">
494
- <h1>กระทรวงแรงงาน</h1>
495
- <h2>ใบเสร็จรับเงิน (ต้นฉบับ)</h2>
496
- </div>
497
-
498
- <!-- Download Section (ไม่แสดงเวลาพิมพ์) -->
499
- <div class="download-section no-print">
500
- <h3>🔗 ดาวน์โหลดเอกสาร</h3>
501
- <a href="{pdf_url}" class="download-btn" target="_blank">📄 ดาวน์โหลด PDF</a>
502
- <button onclick="window.print()" class="download-btn">🖨️ พิมพ์เอกสาร</button>
503
- </div>
504
-
505
- <!-- Receipt Info -->
506
- <div class="info-section">
507
- <div class="info-row">
508
- <span class="info-label">เลขที่:</span>
509
- <span>{receipt_number}</span>
510
- <span class="info-label">แบบ ภ.1600-034</span>
511
- </div>
512
- <div class="info-row">
513
- <span class="info-label">ที่ทำการ:</span>
514
- <span>สำนักบริหารแรงงานต่างด้าว</span>
515
- </div>
516
- <div class="info-row">
517
- <span class="info-label">วันที่:</span>
518
- <span>01 เมษายน 2568</span>
519
- </div>
520
- <div class="info-row">
521
- <span class="info-label">เลขที่ใบชำระเงิน:</span>
522
- <span>{payment_number}</span>
523
- </div>
524
- <div class="info-row">
525
- <span class="info-label">เลขรับคำขอที่:</span>
526
- <span>{request_number}</span>
527
- </div>
528
- </div>
529
-
530
- <!-- Payer Info -->
531
- <div class="section-title">ข้อมูลผู้ชำระเงิน</div>
532
- <div class="info-section">
533
- <div class="info-row">
534
- <span class="info-label">ชื่อผู้ชำระเงิน:</span>
535
- <span>{english_name}</span>
536
- </div>
537
- <div class="info-row">
538
- <span class="info-label">สัญชาติ:</span>
539
- <span>{nationality}</span>
540
- </div>
541
- <div class="info-row">
542
- <span class="info-label">เลขอ้างอิงคนต่างด้าว:</span>
543
- <span>{foreign_reference_number}</span>
544
- </div>
545
- <div class="info-row">
546
- <span class="info-label">หมายเลขประจำตัวคนต่างด้าว:</span>
547
- <span>{id_number}</span>
548
- </div>
549
- </div>
550
-
551
- <!-- Employer Info -->
552
- <div class="section-title">ข้อมูลนายจ้าง</div>
553
- <div class="info-section">
554
- <div class="info-row">
555
- <span class="info-label">ชื่อนายจ้าง/สถานประกอบการ:</span>
556
- <span>บริษัท บาน กง เอ็นจิเนียริ่ง จำกัด</span>
557
- </div>
558
- <div class="info-row">
559
- <span class="info-label">เลขประจำตัวนายจ้าง:</span>
560
- <span>0415567000061</span>
561
- </div>
562
- </div>
563
-
564
- <!-- Fee Table -->
565
- <div class="section-title">รายการค่าธรรมเนียม</div>
566
- <table class="fee-table">
567
- <thead>
568
- <tr>
569
- <th>รายการ</th>
570
- <th class="amount">จำนวนเงิน (บาท)</th>
571
- </tr>
572
- </thead>
573
- <tbody>
574
- <tr>
575
- <td>1. ค่าธรรมเนียมในการยื่นคำขอ ฉบับละ 100 บาท</td>
576
- <td class="amount">100.00</td>
577
- </tr>
578
- <tr>
579
- <td>2. ค่าธรรมเนียมการพิจารณา</td>
580
- <td class="amount">900.00</td>
581
- </tr>
582
- <tr class="total-row">
583
- <td><strong>รวมเป็นเงินทั้งสิ้น (บาท): (หนึ่งพันบาทถ้วน)</strong></td>
584
- <td class="amount"><strong>1,000.00</strong></td>
585
- </tr>
586
- </tbody>
587
- </table>
588
-
589
- <div style="margin: 20px 0; font-weight: 600;">
590
- ได้รับเงินไว้เป็นการถูกต้องแล้ว
591
- </div>
592
-
593
- <!-- Signature Section -->
594
- <div class="signature-section">
595
- <div class="signature-box">
596
- <div style="margin-bottom: 50px;">_______________________</div>
597
- <div>(ลงชื่อ) นางสาวอารีวรรณ โพธิ์นิ่มแดง</div>
598
- <div>(ผู้รับเงิน)</div>
599
- <div style="margin-top: 10px;">ตำแหน่ง: นักวิชาการแรงงานชำนาญการ</div>
600
- </div>
601
-
602
- <div class="qr-section">
603
- <div id="qrcode"></div>
604
- <div style="font-size: 12px; margin-top: 5px;">สแกนเพื่อตรวจสอบ</div>
605
- </div>
606
- </div>
607
-
608
- <!-- Footer -->
609
- <div class="footer">
610
- <div>พิมพ์เมื่อ: {print_time}</div>
611
- <div style="margin-top: 5px;">เอกสารนี้ออกโดยระบบอัตโนมัติ - บริษัท บาน กง เอ็นจิเนียริ่ง จำกัด</div>
612
- </div>
613
- </div>
614
 
615
- <script>
616
- // สร้าง QR Code
617
- QRCode.toCanvas(document.getElementById('qrcode'), '{pdf_url}', {{
618
- width: 80,
619
- height: 80,
620
- margin: 1,
621
- color: {{
622
- dark: '#000000',
623
- light: '#FFFFFF'
624
- }}
625
- }}, function (error) {{
626
- if (error) console.error(error);
627
- console.log('QR Code generated successfully!');
628
- }});
629
-
630
- // Auto-focus สำหรับการพิมพ์
631
- window.addEventListener('load', function() {{
632
- console.log('Receipt loaded successfully');
633
- }});
634
- </script>
635
- </body>
636
- </html>
637
- """
638
 
639
- # บันทึกไฟล์ HTML
640
- with open(local_html_path, 'w', encoding='utf-8') as f:
641
- f.write(html_content)
642
 
643
- # อัพโหลด HTML
644
- try:
645
- upload_file(
646
- path_or_fileobj=local_html_path,
647
- path_in_repo=html_filename,
648
- repo_id=REPO_ID,
649
- repo_type="space"
650
- )
651
- print(f"HTML uploaded successfully: {html_filename}")
652
- except Exception as e:
653
- print(f"Error uploading HTML: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import sqlite3
 
 
3
  import os
4
+ import time
5
  from reportlab.lib.pagesizes import A4
 
6
  from reportlab.pdfgen import canvas
7
+ from reportlab.lib.units import cm
 
8
  import qrcode
9
+ from huggingface_hub import upload_file
 
 
 
10
  import requests
11
 
12
+ REPO_ID = "protae5544/WorkerManagement"
 
 
 
13
 
14
+ def setup_fonts():
 
15
  try:
16
+ from reportlab.pdfbase import pdfmetrics
17
+ from reportlab.pdfbase.ttfonts import TTFont
 
 
 
18
 
19
+ font_url = 'https://fonts.gstatic.com/s/sarabun/v13/DtVjJx26TKEqsc-lWcmw-wKE7wM.ttf'
20
+ bold_url = 'https://fonts.gstatic.com/s/sarabun/v13/DtVmJx26TKEqsc-lWcmw5wq0hwOKBwXcb0A.ttf'
 
 
 
21
 
22
+ if not os.path.exists('THSarabun.ttf'):
23
+ response = requests.get(font_url, timeout=10)
24
+ with open('THSarabun.ttf', 'wb') as f:
25
+ f.write(response.content)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
+ if not os.path.exists('THSarabunBold.ttf'):
28
+ response = requests.get(bold_url, timeout=10)
29
+ with open('THSarabunBold.ttf', 'wb') as f:
30
+ f.write(response.content)
31
 
32
+ pdfmetrics.registerFont(TTFont('THSarabun', 'THSarabun.ttf'))
33
+ pdfmetrics.registerFont(TTFont('THSarabunBold', 'THSarabunBold.ttf'))
 
 
34
  return True
35
+ except:
 
36
  return False
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  def init_db():
39
  conn = sqlite3.connect("workers.db")
40
  c = conn.cursor()
 
48
  payment_number TEXT,
49
  created_at TEXT
50
  )''')
 
 
 
 
 
 
 
 
 
 
51
  conn.commit()
52
  conn.close()
53
 
54
+ def create_pdf(request_number, english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number):
55
+ filename = f"receipt_{request_number}.pdf"
 
 
56
 
57
+ c = canvas.Canvas(filename, pagesize=A4)
 
 
 
58
  width, height = A4
59
 
60
+ font_available = setup_fonts()
61
+
62
+ # **หัวเอกสาร - เหมือนต้นฉบับ**
63
+ if font_available:
64
+ c.setFont("THSarabunBold", 52.284/2.83465) # ขนาดตามต้นฉบับ
65
+ else:
66
+ c.setFont("Helvetica-Bold", 18)
67
+ c.drawString(2*cm, 28*cm, "กระทรวงแรงงาน")
68
+
69
+ if font_available:
70
+ c.setFont("THSarabun", 35.212/2.83465)
71
+ else:
72
+ c.setFont("Helvetica", 12)
73
+ c.drawString(2*cm, 27.5*cm, "ใบเสร็จรับเงิน (ต้นฉบับ)")
74
+ c.drawString(2*cm, 26*cm, f"เลขที่: {receipt_number}")
75
+ c.drawString(2*cm, 25.5*cm, "ที่ทำการ: สำนักบริหารแรงงานต่างด้าว")
76
+ c.drawString(2*cm, 25*cm, "วันที่: 01 เมษายน 2568")
77
+ c.drawString(2*cm, 24.5*cm, f"เลขที่ใบชำระเงิน: {payment_number}")
78
+ c.drawString(2*cm, 24*cm, f"เลขรับคำขอที่: {request_number}")
79
+ c.drawString(2*cm, 23.5*cm, f"ชื่อผู้ชำระเงิน: {english_name}")
80
+ c.drawString(2*cm, 23*cm, f"สัญชาติ: {nationality}")
81
+ c.drawString(2*cm, 22.5*cm, f"เลขอ้างอิงคนต่างด้าว: {foreign_reference_number}")
82
+ c.drawString(2*cm, 22*cm, f"หมายเลขประจำตัวคนต่างด้าว: {id_number}")
83
+ c.drawString(2*cm, 21.5*cm, "ชื่อนายจ้าง / สถานประกอบการ: บริษัท บาน กง เอ็นจิเนียริ่ง จำกัด")
84
+ c.drawString(2*cm, 21*cm, "เลขประจำตัวนายจ้าง: 0415567000061")
85
+
86
+ # **รายการ - เหมือนต้นฉบับ**
87
+ if font_available:
88
+ c.setFont("THSarabunBold", 35.212/2.83465)
89
+ else:
90
+ c.setFont("Helvetica-Bold", 12)
91
+ c.drawString(2*cm, 20*cm, "รายการ")
92
+
93
+ if font_available:
94
+ c.setFont("THSarabun", 35.212/2.83465)
95
+ else:
96
+ c.setFont("Helvetica", 12)
97
+ c.drawString(2*cm, 19.5*cm, "1. ค่าธรรมเนียมในการยื่นคำขอ ฉบับละ 100 บาท: 100.00")
98
+ c.drawString(2*cm, 19*cm, "2. ค่าธรรมเนียม: 900.00")
99
+ c.drawString(2*cm, 18.5*cm, "รวมเป็นเงินทั้งสิ้น (บาท): (หนึ่งพันบาทถ้วน) 1,000.00")
100
+ c.drawString(2*cm, 18*cm, "ได้รับเงินไว้เป็นการถูกต้องแล้ว")
101
+ c.drawString(2*cm, 17.5*cm, "(ลงชื่อ) นางสาวอารีวรรณ โพธิ์นิ่มแดง (ผู้รับเงิน)")
102
+ c.drawString(2*cm, 17*cm, "ตำแหน่ง: นักวิชาการแรงงานชำนาญการ")
103
+
104
+ # **QR Code ที่ตำแหน่งเดิม**
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  pdf_url = f"https://huggingface.co/spaces/{REPO_ID}/resolve/main/{filename}"
106
  try:
107
+ qr = qrcode.make(pdf_url)
108
+ qr.save("temp_qr.png")
109
+ c.drawImage("temp_qr.png", 15*cm, 15*cm, width=3*cm, height=3*cm)
 
 
 
110
  except Exception as e:
111
  print(f"Error creating QR code: {e}")
112
 
113
+ # **เพิ่ม print timestamp ด้านล่าง - เหมือนต้นฉบับ**
114
+ if font_available:
115
+ c.setFont("THSarabun", 20/2.83465)
116
+ else:
117
+ c.setFont("Helvetica", 7)
118
+
119
+ # แปลงเวลาเป็นภาษาไทย
120
+ months = {
121
+ 1: "มกราคม", 2: "กุมภาพันธ์", 3: "มีนาคม", 4: "เมษายน",
122
+ 5: "พฤษภาคม", 6: "มิถุนายน", 7: "กรกฎาคม", 8: "สิงหาคม",
123
+ 9: "กันยายน", 10: "ตุลาคม", 11: "พฤศจิกายน", 12: "ธันวาคม"
124
+ }
125
+ dt = time.localtime(time.time())
126
+ thai_time = f"{dt.tm_mday:02d} {months[dt.tm_mon]} {dt.tm_year + 543} {dt.tm_hour:02d}:{dt.tm_min:02d} น"
127
 
128
+ c.drawString(2*cm, 2*cm, f"พิมพ์เมื่อ: {thai_time}")
 
129
 
130
  c.showPage()
131
  c.save()
132
 
133
+ # อัพโหลดไฟล์
 
 
 
 
134
  try:
135
  upload_file(
136
+ path_or_fileobj=filename,
137
  path_in_repo=filename,
138
  repo_id=REPO_ID,
139
  repo_type="space"
140
  )
141
+ return pdf_url
142
+ except:
 
143
  return None
144
+
145
+ def add_worker(english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number):
146
+ if not all([english_name, foreign_reference_number, id_number, nationality, receipt_number, payment_number]):
147
+ return "❌ กรุณากรอกข้อมูลให้ครบทุกช่อง"
148
+
149
+ if not id_number.isdigit() or len(id_number) != 13:
150
+ return "❌ หมายเลขประจำตัวต้องเป็นตัวเลข 13 หลักเท่านั้น"
151
 
152
+ # สร้างเลขคำขอ
153
  conn = sqlite3.connect("workers.db")
154
+ c = conn.cursor()
155
+ c.execute("SELECT COUNT(*) FROM workers")
156
+ count = c.fetchone()[0]
 
157
  conn.close()
158
 
159
+ request_number = f"WP-68-366-{150 + count:03d}"
 
 
 
 
 
160
 
161
+ # บันทึกข้อมูล
162
+ conn = sqlite3.connect("workers.db")
163
+ c = conn.cursor()
164
+ c.execute('''INSERT INTO workers VALUES (?, ?, ?, ?, ?, ?, ?, ?)''',
165
+ (request_number, english_name, foreign_reference_number, id_number,
166
+ nationality, receipt_number, payment_number, str(time.time())))
167
+ conn.commit()
168
+ conn.close()
169
 
170
+ # สร้าง PDF
171
+ pdf_url = create_pdf(request_number, english_name, foreign_reference_number,
172
+ id_number, nationality, receipt_number, payment_number)
173
 
174
+ if pdf_url:
175
+ result = f"""✅ สร้างใบเสร็จสำเร็จ!
176
+
177
+ 📋 เลขคำขอ: {request_number}
178
+ 👤 ชื่อ: {english_name}
179
+ 🆔 หมายเลขประจำตัว: {id_number}
180
+
181
+ 📄 ดาวน์โหลด PDF: {pdf_url}
182
+
183
+ 🔍 หน้าตาใบเสร็จจะเหมือนเดิมทุกประการ:
184
+ - หัวเอกสาร "กระทรวงแรงงาน"
185
+ - ข้อมูลเรียงตามต้นฉบับ
186
+ - QR Code ที่มุมขวา
187
+ - ลายเซ็นเจ้าหน้าที่
188
+ - วันที่พิมพ์ด้านล่าง
189
+
190
+ 📱 สแกน QR Code ในใบเสร็จเพื่อดาวน์โหลด��ีกครั้ง"""
191
+ return result
192
+ else:
193
+ return "❌ เกิดข้อผิดพลาดในการสร้าง PDF"
194
+
195
+ def view_all():
196
+ conn = sqlite3.connect("workers.db")
197
+ c = conn.cursor()
198
+ c.execute("SELECT request_number, english_name, nationality, id_number FROM workers ORDER BY request_number DESC")
199
+ workers = c.fetchall()
200
+ conn.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
 
202
+ if not workers:
203
+ return "ยังไม่มีข้อมูลพนักงานในระบบ"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
 
205
+ result = f"📊 รายการพนักงานทั้งหมด ({len(workers)} คน)\n\n"
206
+ for i, worker in enumerate(workers, 1):
207
+ result += f"{i}. {worker[0]} | {worker[1]} | {worker[2]} | {worker[3]}\n"
208
 
209
+ return result
210
+
211
+ init_db()
212
+
213
+ with gr.Blocks(title="ระบบจัดการพนักงาน") as app:
214
+ gr.Markdown("# 🏢 ระบบจัดการข้อมูลพนักงานต่างด้าว")
215
+ gr.Markdown("### บริษัท บาน กง เอ็นจิเนียริ่ง จำกัด")
216
+ gr.Markdown("#### ✅ ใบเสร็จจะมีหน้าตาเหมือนเอกสารต้นฉบับทุกประการ")
217
+
218
+ with gr.Tab("📝 เพิ่มพนักงานใหม่"):
219
+ gr.Markdown("### กรอกข้อมูลพนักงาน")
220
+
221
+ name = gr.Textbox(label="ชื่อภาษาอังกฤษ", placeholder="MR. AUNG KYAW")
222
+ ref_num = gr.Textbox(label="หมายเลขอ้างอิงคนต่างด้าว", placeholder="2492102076212")
223
+ id_num = gr.Textbox(label="หมายเลขประจำตัว (13 หลัก)", placeholder="6685490000472")
224
+ nation = gr.Dropdown(["เมียนมา", "กัมพูชา", "ลาว", "เวียดนาม"],
225
+ label="สัญชาติ", value="เมียนมา")
226
+ receipt = gr.Textbox(label="เลขที่ใบเสร็จ", placeholder="2100680001130")
227
+ payment = gr.Textbox(label="หมายเลขชำระเงิน", placeholder="IV680210/002350")
228
+
229
+ submit = gr.Button("💾 สร้างใบเสร็จ (หน้าตาเหมือนเดิม)", variant="primary", size="lg")
230
+ result = gr.Textbox(label="ผลลัพธ์", lines=12, interactive=False)
231
+
232
+ with gr.Tab("📋 ดูรายการ"):
233
+ view_btn = gr.Button("👥 ดูรายการพนักงานทั้งหมด")
234
+ worker_list = gr.Textbox(label="รายการ", lines=15, interactive=False)
235
+
236
+ submit.click(add_worker, [name, ref_num, id_num, nation, receipt, payment], result)
237
+ view_btn.click(view_all, outputs=worker_list)
238
+
239
+ app.launch()