protae5544 commited on
Commit
7708e5a
·
verified ·
1 Parent(s): 57832e8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -127
app.py CHANGED
@@ -1,127 +1,25 @@
1
- import gradio as gr
2
- import sqlite3
3
- import json
4
- import platform
5
- from huggingface_hub import hf_hub_download, upload_file
6
- import os
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 logging
18
-
19
- # ตั้งค่าการบันทึกข้อผิดพลาด
20
- logging.basicConfig(filename='app.log', level=logging.INFO)
21
- logger = logging.getLogger()
22
-
23
- # โหลด Environment Variables
24
- load_dotenv()
25
- REPO_ID = os.getenv("REPO_ID", "protae5544/WorkerManagement")
26
- ORIGINAL_REPO_ID = os.getenv("ORIGINAL_REPO_ID")
27
-
28
- # ตั้งค่าฟอนต์
29
- try:
30
- if platform.system() == "Linux":
31
- font_path = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
32
- if os.path.exists(font_path):
33
- pdfmetrics.registerFont(TTFont('THSarabunBold', font_path))
34
- else:
35
- pdfmetrics.registerFont(TTFont('THSarabunBold', 'THSarabunNew-Bold.ttf'))
36
- except Exception as e:
37
- logger.error(f"Font error: {str(e)}")
38
-
39
- # ฟังก์ชันแปลงวันที่ไทย
40
- def thai_date(timestamp):
41
- thai_months = ["มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน",
42
- "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม",
43
- "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"]
44
- dt = time.localtime(timestamp)
45
- return f"{dt.tm_mday} {thai_months[dt.tm_mon-1]} {dt.tm_year + 543}"
46
-
47
- # เริ่มต้นฐานข้อมูล (ปรับปรุงใหม่)
48
- def init_db():
49
- try:
50
- conn = sqlite3.connect("workers.db")
51
- c = conn.cursor()
52
-
53
- c.execute("""
54
- CREATE TABLE IF NOT EXISTS workers (
55
- id INTEGER PRIMARY KEY AUTOINCREMENT,
56
- request_number TEXT UNIQUE,
57
- english_name TEXT,
58
- foreign_ref TEXT,
59
- id_number TEXT CHECK(length(id_number) = 13),
60
- nationality TEXT DEFAULT 'เมียนมา',
61
- receipt_num TEXT,
62
- payment_num TEXT,
63
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
64
- )""")
65
-
66
- c.execute("""
67
- CREATE TABLE IF NOT EXISTS attachments (
68
- id INTEGER PRIMARY KEY AUTOINCREMENT,
69
- request_number TEXT,
70
- file_path TEXT,
71
- FOREIGN KEY(request_number) REFERENCES workers(request_number)
72
- )""")
73
-
74
- conn.commit()
75
- except Exception as e:
76
- logger.error(f"Database error: {str(e)}")
77
- finally:
78
- conn.close()
79
-
80
- # สร้าง PDF (แก้ไขแล้ว)
81
- def create_pdf(data, output_path):
82
- try:
83
- c = canvas.Canvas(output_path, pagesize=A4)
84
-
85
- # ตั้งค่าฟอนต์
86
- c.setFont("THSarabunBold", 14)
87
-
88
- # เพิ่มเนื้อหา PDF
89
- c.drawString(2*cm, 27*cm, f"เลขคำขอ: {data['request_number']}")
90
- c.drawString(2*cm, 26*cm, f"ชื่อ: {data['english_name']}")
91
- # ... เพิ่มเนื้อหาอื่นๆ ...
92
-
93
- c.save()
94
- return True
95
- except Exception as e:
96
- logger.error(f"PDF generation failed: {str(e)}")
97
- return False
98
-
99
- # ส่วนต่อประสาน Gradio (ปรับปรุงใหม่)
100
- with gr.Blocks(title="Worker Management", theme=gr.themes.Soft()) as app:
101
-
102
- # UI Components
103
- with gr.Row():
104
- req_num = gr.Textbox(label="เลขคำขอ", interactive=False)
105
- eng_name = gr.Textbox(label="ชื่อภาษาอังกฤษ")
106
-
107
- with gr.Row():
108
- id_num = gr.Textbox(label="เลขประจำตัว 13 หลัก")
109
- nationality = gr.Textbox(label="สัญชาติ", value="เมียนมา")
110
-
111
- submit_btn = gr.Button("บันทึกข้อมูล", variant="primary")
112
- output = gr.Textbox(label="สถานะ")
113
-
114
- # Event Handling
115
- submit_btn.click(
116
- fn=lambda: "บันทึกข้อมูลสำเร็จ",
117
- outputs=output
118
- )
119
-
120
- # เริ่มต้นระบบ
121
- if __name__ == "__main__":
122
- init_db()
123
- app.launch(
124
- server_name="0.0.0.0",
125
- server_port=int(os.getenv("PORT", 7860)),
126
- share=False
127
- )
 
1
+ import anthropic
2
+
3
+ client = anthropic.Anthropic(
4
+ # defaults to os.environ.get("ANTHROPIC_API_KEY")
5
+ api_key="my_api_key",
6
+ )
7
+
8
+ message = client.messages.create(
9
+ model="claude-sonnet-4-20250514",
10
+ max_tokens=20000,
11
+ temperature=1,
12
+ system="Select the components you want to include:\n\n☑️ **บทบาทหลัก**\nYou are a web development engineer, writing web pages according to the instructions below. You are a powerful code editing assistant capable of writing code and creating artifacts in conversations with users, or modifying and updating existing artifacts as requested by users.\n\n☑️ **รูปแบบการส่งออกโค้ด**\nAll code is written in a single code block to form a complete code file for display, without separating HTML and JavaScript code. An artifact refers to a runnable complete code snippet, you prefer to integrate and output such complete runnable code rather than breaking it down into several code blocks.\n\n☑️ **โปรเจกต์หลายไฟล์**\nFor multi-file projects (Next.js, React apps, Node.js backends), organize code into appropriate file structures. Clearly indicate file paths and provide setup instructions. Include package.json, configuration files, and folder structure when needed.\n\n☑️ **Server-Side Development**\nWhen building server-side applications, include proper API routing, database connections, authentication middleware, and environment configuration. Use modern frameworks like Express.js, Next.js API routes, or similar. Include error handling and security best practices.\n\n☑️ **การตรวจสอบคุณภาพ**\nFor certain types of code, they can render graphical interfaces in a UI window. After generation, please check the code execution again to ensure there are no errors in the output.\n\n☑️ **Responsive Design**\nEnsure the application is responsive and adapts well to different screen sizes, especially mobile devices. Use mobile-first approach and consider touch-friendly interfaces.\n\n☑️ **Modern UI/UX Standards**\nFollow modern web design principles including clean typography, intuitive navigation, proper spacing, and consistent visual hierarchy. Use CSS Grid/Flexbox for layouts.\n\n☑️ **Accessibility Guidelines**\nInclude proper semantic HTML, ARIA labels where needed, keyboard navigation support, and sufficient color contrast for better accessibility.\n\n☑️ **Framework Preferences**\nPrefer using modern CSS frameworks like Tailwind CSS or Bootstrap for styling. For JavaScript frameworks, use React, Vue.js, or vanilla JS as appropriate. Include CDN links when using external libraries.\n\n☑️ **Theme Support**\nSupport both light and dark mode themes. Use CSS custom properties for easy theme switching.\n\n☑️ **Performance Optimization**\nWrite efficient, clean code with minimal dependencies. Optimize images and assets for web delivery.\n\n☑️ **Error Handling**\nInclude proper error handling and user feedback mechanisms. Provide loading states and informative error messages.\n\n☑️ **User Experience**\nFocus on smooth interactions, appropriate animations, and clear user guidance throughout the application.\n\n☑️ **Output Format**\nOutput only the HTML with embedded CSS and JavaScript, without any additional descriptive text unless specifically requested.\n\nUse only the checked items ab่ove for code generation.",
13
+ messages=[
14
+ {
15
+ "role": "user",
16
+ "content": [
17
+ {
18
+ "type": "text",
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
+ print(message.content)