Spaces:
Sleeping

TrungLC commited on
Commit
72f1c2d
·
verified ·
1 Parent(s): 31f0e1b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -78
app.py CHANGED
@@ -1,117 +1,112 @@
1
  #!/usr/bin/env python3
2
  """
3
- app.py - Phiên bản HOÀN HẢO, chạy ngon trong Docker, CI/CD, cronjob
4
- Hỗ trợ đầy đủ:
5
- - Biến môi trường THUOC, XETNGHIEM, ICD_PLT
6
- - Tự tìm file trong thư mục /data
7
- - Không bao giờ hỏi input()
8
  """
9
 
10
- import argparse
11
  import os
12
  import subprocess
13
  import sys
14
  from pathlib import Path
15
 
16
 
17
- def find_file(patterns, search_dir="."):
18
- """Tìm file đầu tiên khớp với các pattern (không phân biệt hoa thường)"""
19
- search_path = Path(search_dir)
20
- if not search_path.exists():
 
 
21
  return None
22
 
23
- for pattern in patterns:
24
- for pat in [pattern, pattern.lower(), pattern.upper(), pattern.capitalize()]:
25
- for ext in ["", ".xlsx", ".xls", ".csv", ".XLSX", ".XLS", ".CSV"]:
26
- full_pat = f"*{pat}{ext}"
27
- for file_path in search_path.glob(full_pat):
28
- if file_path.is_file():
29
- abs_path = str(file_path.resolve())
30
- print(f"Tự động tìm thấy: {abs_path}")
31
- return abs_path
32
  return None
33
 
34
 
35
  def main():
36
- parser = argparse.ArgumentParser(description="Wrapper xử lý PLT - Docker ready 100%")
37
- parser.add_argument("--thuoc", help="Đường dẫn file thuốc")
38
- parser.add_argument("--xetnghiem", help="Đường dẫn file xét nghiệm")
39
- parser.add_argument("--icd_plt", help="Đường dẫn file ICD_PLT")
40
- parser.add_argument("--out", default="/app/ketqua.csv", help="File kết quả")
41
- parser.add_argument("--input-dir", default="/data", help="Thư mục tìm file tự động (default: /data)")
42
- args = parser.parse_args()
43
-
44
- print("\n=== KHỞI ĐỘNG XỬ LÝ PLT ===")
45
  print(f"Thời gian: {__import__('datetime').datetime.now():%Y-%m-%d %H:%M:%S}\n")
46
 
47
- # Ưu tiên: CLI → env → tự tìm trong input-dir
48
- thuoc = args.thuoc or os.getenv("THUOC")
49
- xetnghiem = args.xetnghiem or os.getenv("XETNGHIEM")
50
- icd_plt = args.icd_plt or os.getenv("ICD_PLT")
51
-
52
- search_dir = args.input_dir
53
 
 
54
  if not thuoc:
55
- print(f"→ Đang tìm file thuốc trong: {search_dir}")
56
- thuoc = find_file(["thuoc", "Thuoc", "THUOC", "thuốc", "drug", "medicine"], search_dir)
 
57
 
58
  if not xetnghiem:
59
- print(f"→ Đang tìm file xét nghiệm trong: {search_dir}")
60
- xetnghiem = find_file(["xetnghiem", "XetNghiem", "xét nghiệm", "lab", "test", "xn"], search_dir)
 
61
 
62
  if not icd_plt:
63
- print(f"→ Đang tìm file ICD_PLT trong: {search_dir}")
64
- icd_plt = find_file(["ICD_PLT", "icd_plt", "ICD", "icd", "icdplt"], search_dir)
65
-
66
- # Kiểm tra cuối cùng
67
- missing = []
68
- for name, path in [("THUOC", thuoc), ("XETNGHIEM", xetnghiem), ("ICD_PLT", icd_plt)]:
69
- if not path:
70
- missing.append(f"{name}: chưa xác định")
71
- elif not os.path.exists(path):
72
- missing.append(f"{name}: không tồn tại → {path}")
73
-
74
- if missing:
75
- print("LỖI: Thiếu file bắt buộc!\n")
76
- for m in missing:
77
- print(" •", m)
 
 
 
 
 
 
78
  print("\n" + "="*60)
79
- print("CÁCH KHẮC PHỤC (chọn 1 trong 3):")
80
- print("\n1. Dùng biến môi trường (KHUYẾN NGHỊ NHẤT):")
81
- print(" docker run -e THUOC=/data/thuoc.xlsx -e XETNGHIEM=/data/xn.xlsx -e ICD_PLT=/data/ICD.csv your-image")
82
- print("\n2. Mount thư mục chứa file vào /data (script tự tìm):")
83
- print(" docker run -v \"/đường/dẫn/thư/mục/dữ/liệu:/data\" your-image")
84
- print("\n3. Truyền trực tiếp tham số:")
85
- print(" docker run -v ./data:/data your-image python app.py --thuoc /data/abc.xlsx ...")
86
- print("="*60)
87
  sys.exit(1)
88
 
89
- # Chạy process_plt.py
90
- script_path = Path(__file__).parent.resolve() / "process_plt.py"
91
- if not script_path.exists():
92
- print("LỖI: Không tìm thấy file process_plt.py trong cùng thư mục!")
93
- sys.exit(127)
94
 
95
  cmd = [
96
- sys.executable, str(script_path),
97
  "--thuoc", thuoc,
98
  "--xetnghiem", xetnghiem,
99
  "--icd_plt", icd_plt,
100
- "--out", args.out
101
  ]
102
 
103
- print("Tất cả file đã sẵn sàng!")
104
- print(f" • Thuốc : {thuoc}")
105
- print(f" • Xét nghiệm : {xetnghiem}")
106
- print(f" • ICD_PLT : {icd_plt}")
107
- print(f" • Kết quả : {args.out}")
108
- print("\nĐang chạy lệnh:")
109
  print(" " + " ".join(cmd))
110
- print("\n" + "-"*80)
 
 
111
 
112
- result = subprocess.call(cmd)
113
- print(f"\nHOÀN THÀNH! Mã thoát: {result}")
114
- sys.exit(result)
 
 
 
115
 
116
 
117
  if __name__ == "__main__":
 
1
  #!/usr/bin/env python3
2
  """
3
+ app.py - Wrapper xử lý PLT hoàn hảo cho Docker
4
+ Tự động tìm file theo tên tiếng Việt thực tế, không cần biết chính xác tên file
5
+ Chỉ cần mount thư mục vào /data là chạy luôn – không cần gõ gì thêm
 
 
6
  """
7
 
 
8
  import os
9
  import subprocess
10
  import sys
11
  from pathlib import Path
12
 
13
 
14
+ def tim_file_theo_tu_khoa(keywords, thu_muc="/data"):
15
+ """
16
+ Tìm file đầu tiên trong thư mục có chứa ít nhất một từ khóa (không phân biệt hoa/thường)
17
+ """
18
+ thu_muc_path = Path(thu_muc)
19
+ if not thu_muc_path.exists():
20
  return None
21
 
22
+ for file in thu_muc_path.iterdir():
23
+ if file.is_file():
24
+ ten_file = file.name.lower()
25
+ if any(tu_khoa.lower() in ten_file for tu_khoa in keywords):
26
+ duong_dan = str(file.resolve())
27
+ print(f"Đã tìm thấy → {keywords[0].upper()}: {duong_dan}")
28
+ return duong_dan
 
 
29
  return None
30
 
31
 
32
  def main():
33
+ print("\n" + "="*60)
34
+ print(" BẮT ĐẦU XỬ LÝ PHIẾU LĨNH THUỐC (PLT)")
35
+ print("="*60)
 
 
 
 
 
 
36
  print(f"Thời gian: {__import__('datetime').datetime.now():%Y-%m-%d %H:%M:%S}\n")
37
 
38
+ # 1. Ưu tiên lấy từ biến môi trường (nếu có)
39
+ thuoc = os.getenv("THUOC")
40
+ xetnghiem = os.getenv("XETNGHIEM")
41
+ icd_plt = os.getenv("ICD_PLT")
 
 
42
 
43
+ # 2. Nếu không có → tự tìm trong /data (thư mục bạn sẽ mount vào)
44
  if not thuoc:
45
+ thuoc = tim_file_theo_tu_khoa([
46
+ "thuoc", "thuốc", "danh sách thuốc", "danhsachthuoc", "drug", "medicine"
47
+ ])
48
 
49
  if not xetnghiem:
50
+ xetnghiem = tim_file_theo_tu_khoa([
51
+ "xetnghiem", "xét nghiệm", "xn", "lab", "test", "ketqua", "kết quả"
52
+ ])
53
 
54
  if not icd_plt:
55
+ icd_plt = tim_file_theo_tu_khoa([
56
+ "icd_plt", "icdplt", "icd", "icd plt", "icd_plt", "icdlist"
57
+ ])
58
+
59
+ # 3. Kiểm tra cuối cùng
60
+ thieu = []
61
+ if not thuoc: thieu.append("THUỐC")
62
+ if not xetnghiem: thieu.append("XÉT NGHIỆM")
63
+ if not icd_plt: thieu.append("ICD_PLT")
64
+
65
+ if thieu:
66
+ print("KHÔNG TÌM THẤY FILE BẮT BUỘC:")
67
+ for item in thieu:
68
+ print(f" → {item}")
69
+ print("\nVui lòng làm một trong hai cách sau:\n")
70
+ print(" CÁCH 1 (DỄ NHẤT – KHUYẾN NGHỊ):")
71
+ print(" Chỉ cần mount thư mục chứa 3 file vào /data:")
72
+ print(" docker run -v \"C:\\duong\\dan\\toi\\thu_muc:/data\" plt")
73
+ print("\n CÁCH 2:")
74
+ print(" Dùng biến môi trường:")
75
+ print(" docker run -e THUOC=/data/thuoc.xlsx -e XETNGHIEM=/data/xn.xlsx -e ICD_PLT=/data/icd.csv plt")
76
  print("\n" + "="*60)
 
 
 
 
 
 
 
 
77
  sys.exit(1)
78
 
79
+ # 4. Chạy process_plt.py
80
+ script = Path(__file__).with_name("process_plt.py")
81
+ if not script.exists():
82
+ print("LỖI: Không tìm thấy file process_plt.py!")
83
+ sys.exit(1)
84
 
85
  cmd = [
86
+ sys.executable, str(script),
87
  "--thuoc", thuoc,
88
  "--xetnghiem", xetnghiem,
89
  "--icd_plt", icd_plt,
90
+ "--out", "/app/ketqua.csv"
91
  ]
92
 
93
+ print("TẤT CẢ FILE ĐÃ SẴN SÀNG!")
94
+ print(f" • Thuốc → {thuoc}")
95
+ print(f" • Xét nghiệm → {xetnghiem}")
96
+ print(f" • ICD_PLT → {icd_plt}")
97
+ print(f" • Kết quả → /app/ketqua.csv\n")
98
+ print("ĐANG CHẠY LỆNH:")
99
  print(" " + " ".join(cmd))
100
+ print("\n" + "-"*80 + "\n")
101
+
102
+ ket_qua = subprocess.call(cmd)
103
 
104
+ print(f"\nHOÀN TẤT! Mã trả về: {ket_qua}")
105
+ if ket_qua == 0:
106
+ print("File kết quả đã được tạo: /app/ketqua.csv")
107
+ print("Bạn có thể copy ra ngoài bằng lệnh:")
108
+ print(" docker cp <container_id>:/app/ketqua.csv .")
109
+ sys.exit(ket_qua)
110
 
111
 
112
  if __name__ == "__main__":