TrungLC commited on
Commit
7cdbd56
·
verified ·
1 Parent(s): 5e56abd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -128
app.py CHANGED
@@ -1,175 +1,110 @@
1
  #!/usr/bin/env python3
2
  """
3
- app.py - Wrapper thân thiện hoàn toàn với môi trường không tương tác (Docker, CI/CD, cron...)
4
- Tính năng mới so với bản cũ:
5
- - Tìm file đệ quy trong toàn bộ cây thư mục nếu cần (--search-subdirs)
6
- - Hỗ trợ chỉ định thư mục tìm kiếm qua --input-dir hoặc biến INPUT_DIR
7
- - Linh hoạt hơn với pattern tên file
8
- - Luôn chọn file đầu tiên nếu không tương tác VÀ có ít nhất 1 file tìm thấy
9
- - Thoát lỗi rõ ràng nếu vẫn không tìm thấy gì
10
- - Hiển thị thông báo chi tiết khi debug
11
  """
12
 
13
  import argparse
14
- import glob
15
  import os
16
  import subprocess
17
  import sys
18
  from pathlib import Path
19
 
20
 
21
- def find_candidates(patterns, search_dir=".", recursive=False):
22
- """
23
- Tìm file theo nhiều pattern, trả về danh sách unique giữ nguyên thứ tự.
24
- """
25
- files = []
26
- search_path = Path(search_dir)
27
-
28
  for pattern in patterns:
29
- # Hỗ trợ cả pattern có chứa thư mục con
30
- full_pattern = str(search_path / pattern) if not str(pattern).startswith("/") else pattern
31
- found = glob.glob(full_pattern, recursive=recursive)
32
- files.extend(found)
33
-
34
- # Loại trùng, giữ thứ tự
35
- seen = set()
36
- uniq = []
37
- for f in files:
38
- abs_f = os.path.abspath(f)
39
- if abs_f not in seen:
40
- seen.add(abs_f)
41
- uniq.append(f)
42
- return uniq
43
-
44
-
45
- def choose_file(prompt, candidates, interactive=True, auto=False):
46
- if not candidates:
47
- return None
48
-
49
- if len(candidates) == 1 or not interactive or auto:
50
- chosen = candidates[0]
51
- action = "Tự động chọn" if (len(candidates) > 1 or not interactive or auto) else "Tìm thấy"
52
- print(f"{prompt}: {action} {chosen}")
53
- return chosen
54
-
55
- # Trường hợp tương tác và có nhiều file
56
- print(f"{prompt} tìm thấy {len(candidates)} file:")
57
- for i, f in enumerate(candidates, 1):
58
- print(f" {i}. {f}")
59
- try:
60
- while True:
61
- sel = input(f"Chọn số (1-{len(candidates)}) hoặc nhập đường dẫn đầy đủ: ").strip()
62
- if sel.isdigit():
63
- idx = int(sel)
64
- if 1 <= idx <= len(candidates):
65
- return candidates[idx - 1]
66
- if os.path.exists(sel):
67
- return sel
68
- print("Đường dẫn không hợp lệ hoặc không tồn tại, thử lại.")
69
- except (EOFError, KeyboardInterrupt):
70
- print("\nSTDIN không khả dụng → tự động chọn file đầu tiên.")
71
- return candidates[0]
72
 
73
 
74
  def main():
75
- parser = argparse.ArgumentParser(
76
- description="Wrapper gọi process_plt.py - cực kỳ thân thiện với Docker/CI/CD"
77
- )
78
  parser.add_argument("--thuoc", help="Đường dẫn file thuốc")
79
  parser.add_argument("--xetnghiem", help="Đường dẫn file xét nghiệm")
80
  parser.add_argument("--icd_plt", help="Đường dẫn file ICD_PLT")
81
- parser.add_argument("--out", default="ketqua.csv", help="File kết quả (default: ketqua.csv)")
82
- parser.add_argument("--input-dir", default="/app", help="Thư mục để tìm file tự động (default: /app)")
83
- parser.add_argument("--search-subdirs", action="store_true", help="Tìm đệ quy trong các thư mục con")
84
- parser.add_argument("--auto", action="store_true", help="Luôn tự động chọn file đầu tiên (rất hữu ích cho CI)")
85
  args = parser.parse_args()
86
 
87
- interactive = sys.stdin.isatty()
88
- auto_mode = args.auto or not interactive # Quan trọng: non-interactive = auto
89
 
90
- # Ưu tiên: CLI args → env → tự tìm
91
- thuoc = args.thuoc or os.getenv("THUOC")
92
- xetnghiem = args.xetnghiem or os.getenv("XETNGHIEM")
93
- icd_plt = args.icd_plt or os.getenv("ICD_PLT")
94
 
95
  search_dir = args.input_dir
96
- recursive = args.search_subdirs
97
-
98
- print(f"=== Bắt đầu xử lý lúc {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ===")
99
- print(f"Thư mục tìm kiếm: {search_dir} (đệ quy={'có' if recursive else 'không'})")
100
- print(f"Chế độ tự động: {'BẬT' if auto_mode else 'TẮT'}")
101
 
102
- # Tự động tìm nếu chưa có
103
  if not thuoc:
104
- patterns = [
105
- "thuoc.*", "thuoc*.*", "*thuoc*.xlsx", "*thuoc*.xls", "*thuoc*.csv",
106
- "Thuoc.*", "*Thuoc*.xlsx", "*Thuoc*.csv"
107
- ]
108
- cand = find_candidates(patterns, search_dir, recursive)
109
- thuoc = choose_file("File THUOC", cand, interactive, auto_mode)
110
 
111
  if not xetnghiem:
112
- patterns = [
113
- "xetnghiem.*", "xetnghiem*.*", "*xetnghiem*.xlsx", "*xetnghiem*.xls", "*xetnghiem*.csv",
114
- "XetNghiem.*", "*XetNghiem*.xlsx"
115
- ]
116
- cand = find_candidates(patterns, search_dir, recursive)
117
- xetnghiem = choose_file("File XET NGHIỆM", cand, interactive, auto_mode)
118
 
119
  if not icd_plt:
120
- patterns = [
121
- "ICD_PLT.*", "ICD*PLT*.*", "*ICD_PLT*.xlsx", "*ICD_PLT*.xls", "*ICD_PLT*.csv",
122
- "icd_plt.*", "*icd_plt*.xlsx"
123
- ]
124
- cand = find_candidates(patterns, search_dir, recursive)
125
- icd_plt = choose_file("File ICD_PLT", cand, interactive, auto_mode)
126
 
127
  # Kiểm tra cuối cùng
128
  missing = []
129
- for name, path in [("thuoc", thuoc), ("xetnghiem", xetnghiem), ("icd_plt", icd_plt)]:
130
  if not path:
131
- missing.append((name, "<chưa xác định>"))
132
  elif not os.path.exists(path):
133
- missing.append((name, path))
134
 
135
  if missing:
136
- print("\nLỖI: Không thể tìm thấy các file bắt buộc:")
137
- for name, path in missing:
138
- print(f" • {name.upper():10}: {path}")
139
- print("\nCách khắc phục:")
140
- print(" 1. Đặt đúng tên file và mount vào container")
141
- print(" 2. Hoặc dùng biến môi trường:")
142
- print(" THUOC=/data/thuoc.xlsx XETNGHIEM=/data/xn.xlsx ICD_PLT=/data/icd.csv python app.py")
143
- print(" 3. Hoặc truyền tham số trực tiếp:")
144
- print(" python app.py --thuoc /path/thuoc.xlsx --xetnghiem ...")
145
  sys.exit(1)
146
 
147
- # Tìm và gọi process_plt.py
148
- script_dir = Path(__file__).parent.resolve()
149
- process_script = script_dir / "process_plt.py"
 
 
150
 
151
  cmd = [
152
- sys.executable, str(process_script),
153
- "--thuoc", str(thuoc),
154
- "--xetnghiem", str(xetnghiem),
155
- "--icd_plt", str(icd_plt),
156
  "--out", args.out
157
  ]
158
 
159
  print("\nTất cả file đã sẵn sàng!")
160
- print("Thực thi lệnh:")
161
- print(" " + " ".join(cmd))
162
-
163
- try:
164
- result = subprocess.call(cmd)
165
- print(f"\nHoàn thành với mã trả về: {result}")
166
- sys.exit(result)
167
- except FileNotFoundError:
168
- print("\nLỖI: Không tìm th��y process_plt.py trong cùng thư mục với app.py")
169
- sys.exit(127)
170
- except Exception as e:
171
- print(f"\nLỖI khi chạy process_plt.py: {e}")
172
- sys.exit(1)
173
 
174
 
175
  if __name__ == "__main__":
 
1
  #!/usr/bin/env python3
2
  """
3
+ app.py - Wrapper siêu thân thiện Docker/CI/CD
4
+ Ưu tiên lấy file theo thứ tự:
5
+ 1. Tham số dòng lệnh (--thuoc, --xetnghiem, --icd_plt)
6
+ 2. Biến môi trường THUOC, XETNGHIEM, ICD_PLT
7
+ 3. Tự động tìm trong thư mục chỉ định (--input-dir)
 
 
 
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 danh sách pattern"""
 
 
 
 
 
19
  for pattern in patterns:
20
+ for ext in ["", ".xlsx", ".xls", ".csv"]:
21
+ full_pat = pattern + ext
22
+ candidates = list(Path(search_dir).glob(f"*{full_pat}*")) + list(Path(search_dir).glob(f"*{full_pat.lower()}*"))
23
+ for cand in candidates:
24
+ if cand.is_file():
25
+ return str_cand = str(cand.resolve())
26
+ print(f"Tự động tìm thấy: {str_cand}")
27
+ return str_cand
28
+ return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
 
31
  def main():
32
+ parser = argparse.ArgumentParser(description="Wrapper gọi process_plt.py – Docker ready")
 
 
33
  parser.add_argument("--thuoc", help="Đường dẫn file thuốc")
34
  parser.add_argument("--xetnghiem", help="Đường dẫn file xét nghiệm")
35
  parser.add_argument("--icd_plt", help="Đường dẫn file ICD_PLT")
36
+ parser.add_argument("--out", default="/app/ketqua.csv", help="File kết quả (default: /app/ketqua.csv)")
37
+ parser.add_argument("--input-dir", default="/data", help="Thư mục để tìm file nếu không chỉ định (default: /data)")
 
 
38
  args = parser.parse_args()
39
 
40
+ print("=== KHỞI ĐỘNG XỬ LÝ PLT ===")
41
+ print(f"Thời gian: {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
42
 
43
+ # Lấy đường dẫn theo thứ tự ưu tiên: CLI → env → tự tìm
44
+ thuoc = args.thuoc or os.environ.get("THUOC")
45
+ xetnghiem = args.xetnghiem or os.environ.get("XETNGHIEM")
46
+ icd_plt = args.icd_plt or os.environ.get("ICD_PLT")
47
 
48
  search_dir = args.input_dir
 
 
 
 
 
49
 
 
50
  if not thuoc:
51
+ print("Không thấy --thuoc hoặc biến THUOC → đang tìm tự động trong", search_dir)
52
+ thuoc = find_file(["thuoc", "Thuoc", "THUOC", "thuốc"], search_dir)
 
 
 
 
53
 
54
  if not xetnghiem:
55
+ print("Không thấy --xetnghiem hoặc biến XETNGHIEM → đang tìm tự động trong", search_dir)
56
+ xetnghiem = find_file(["xetnghiem", "XetNghiem", "xét nghiệm", "lab", "test"], search_dir)
 
 
 
 
57
 
58
  if not icd_plt:
59
+ print("Không thấy --icd_plt hoặc biến ICD_PLT → đang tìm tự động trong", search_dir)
60
+ icd_plt = find_file(["ICD_PLT", "icd_plt", "ICD", "icd"], search_dir)
 
 
 
 
61
 
62
  # Kiểm tra cuối cùng
63
  missing = []
64
+ for name, path in [("THUOC", thuoc), ("XETNGHIEM", xetnghiem), ("ICD_PLT", icd_plt)]:
65
  if not path:
66
+ missing.append(f"{name}: chưa xác định")
67
  elif not os.path.exists(path):
68
+ missing.append(f"{name}: không tồn tại → {path}")
69
 
70
  if missing:
71
+ print("\nCẢNH BÁO: Thiếu file bắt buộc:")
72
+ for m in missing:
73
+ print(" •", m)
74
+ print("\nHãy thử một trong các cách sau:")
75
+ print(" "1. Dùng biến môi trường (khuyên dùng):")
76
+ print(" docker run -e THUOC=/data/thuoc.xlsx -e XETNGHIEM=/data/xn.xlsx -e ICD_PLT=/data/icd.csv ...")
77
+ print(" 2. Mount thư mục và để script tự tìm:")
78
+ print(" docker run -v ./data:/data your-image")
 
79
  sys.exit(1)
80
 
81
+ # Chạy process_plt.py
82
+ script_path = Path(__file__).parent / "process_plt.py"
83
+ if not script_path.exists():
84
+ print("LỖI: Không tìm thấy process_plt.py trong cùng thư mục!")
85
+ sys.exit(127)
86
 
87
  cmd = [
88
+ sys.executable, str(script_path),
89
+ "--thuoc", thuoc,
90
+ "--xetnghiem", xetnghiem,
91
+ "--icd_plt", icd_plt,
92
  "--out", args.out
93
  ]
94
 
95
  print("\nTất cả file đã sẵn sàng!")
96
+ print("Đường dẫn sử dụng:")
97
+ print(f" • Thuốc : {thuoc}")
98
+ print(f" • Xét nghiệm : {xetnghiem}")
99
+ print(f" • ICD_PLT : {icd_plt}")
100
+ print(f" • Kết quả : {args.out}")
101
+ print("\nĐang thực thi:")
102
+ print(" " + " ".join(cmd))
103
+ print("-" * 60)
104
+
105
+ result = subprocess.call(cmd)
106
+ print(f"\nHOÀN THÀNH! Mã trả về: {result}")
107
+ sys.exit(result)
 
108
 
109
 
110
  if __name__ == "__main__":