vithacocf commited on
Commit
77c0246
·
verified ·
1 Parent(s): e598c60

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -27
app.py CHANGED
@@ -117,50 +117,67 @@ def _guess_name_and_mime(file, file_bytes: bytes) -> Tuple[str, str]:
117
 
118
  def extract_pdf_tables(file_path: str) -> pd.DataFrame:
119
  """
120
- Extract bảng PDF bằng Camelot:
121
- - thử mode lattice (bảng có khung line)
122
- - fallback stream (bảng không line rõ)
123
- Trả về DataFrame hợp nhất.
124
  """
 
125
  all_dfs = []
126
 
127
- # --- Thử lattice trước ---
128
- try:
129
- print("🔍 Thử extract bằng lattice...")
130
- tables = camelot.read_pdf(file_path, flavor="lattice", pages="all")
131
- if tables and tables.n > 0:
132
- for t in tables:
133
- all_dfs.append(t.df)
134
- print(f"✅ Lattice: {tables.n} bảng phát hiện.")
135
- except Exception as e:
136
- print(f"⚠️ Lattice lỗi: {e}")
137
 
138
- # --- Fallback stream ---
139
- if not all_dfs:
 
 
 
140
  try:
141
- print("🔁 Thử extract bằng stream...")
142
- tables = camelot.read_pdf(file_path, flavor="stream", pages="all")
 
 
143
  if tables and tables.n > 0:
144
  for t in tables:
145
- all_dfs.append(t.df)
146
- print(f"✅ Stream: {tables.n} bảng phát hiện.")
 
147
  except Exception as e:
148
- print(f" Stream lỗi: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
 
150
  if not all_dfs:
151
- print("🚫 Không phát hiện bảng nào.")
152
  return pd.DataFrame()
153
 
154
- # --- Hợp nhất tất cả bảng ---
155
  df_final = pd.concat(all_dfs, ignore_index=True)
156
-
157
- # Nếu header là 0,1,2,... → dùng dòng đầu làm header thật
158
  if all(str(c).isdigit() for c in df_final.columns):
159
  df_final.columns = df_final.iloc[0]
160
  df_final = df_final[1:]
161
-
162
  df_final = df_final.dropna(how="all").reset_index(drop=True)
163
- print(f"✅ Tổng hợp {len(df_final)} dòng, {len(df_final.columns)} cột.")
164
  return df_final
165
 
166
  def extract_pdf_note(file_path: str) -> str:
 
117
 
118
  def extract_pdf_tables(file_path: str) -> pd.DataFrame:
119
  """
120
+ Extract bảng PDF bằng Camelot (từng trang):
121
+ - Thử lattice
122
+ - Nếu thất bại fallback stream
123
+ - Gộp tất cả
124
  """
125
+ import camelot
126
  all_dfs = []
127
 
128
+ # Đếm tổng số trang
129
+ import fitz
130
+ total_pages = len(fitz.open(file_path))
131
+ print(f"📄 Tổng số trang: {total_pages}")
 
 
 
 
 
 
132
 
133
+ for page_no in range(1, total_pages + 1):
134
+ print(f"🔍 Đang xử lý trang {page_no}...")
135
+ dfs_this_page = []
136
+
137
+ # --- Thử lattice ---
138
  try:
139
+ tables = camelot.read_pdf(
140
+ file_path, flavor="lattice",
141
+ pages=str(page_no), strip_text="\n", line_scale=40
142
+ )
143
  if tables and tables.n > 0:
144
  for t in tables:
145
+ if t.shape[0] > 0:
146
+ dfs_this_page.append(t.df)
147
+ print(f"✅ Trang {page_no}: Lattice thành công ({tables.n} bảng).")
148
  except Exception as e:
149
+ print(f"⚠️ Trang {page_no} lattice lỗi: {e}")
150
+
151
+ # --- Fallback stream ---
152
+ if not dfs_this_page:
153
+ try:
154
+ tables = camelot.read_pdf(
155
+ file_path, flavor="stream",
156
+ pages=str(page_no), edge_tol=200, row_tol=10
157
+ )
158
+ if tables and tables.n > 0:
159
+ for t in tables:
160
+ if t.shape[0] > 0:
161
+ dfs_this_page.append(t.df)
162
+ print(f"✅ Trang {page_no}: Stream thành công ({tables.n} bảng).")
163
+ except Exception as e:
164
+ print(f"❌ Trang {page_no} stream lỗi: {e}")
165
+
166
+ if dfs_this_page:
167
+ all_dfs.extend(dfs_this_page)
168
+ else:
169
+ print(f"🚫 Trang {page_no}: Không phát hiện bảng.")
170
 
171
  if not all_dfs:
172
+ print(" Không tìm thấy bảng trong toàn bộ PDF.")
173
  return pd.DataFrame()
174
 
 
175
  df_final = pd.concat(all_dfs, ignore_index=True)
 
 
176
  if all(str(c).isdigit() for c in df_final.columns):
177
  df_final.columns = df_final.iloc[0]
178
  df_final = df_final[1:]
 
179
  df_final = df_final.dropna(how="all").reset_index(drop=True)
180
+ print(f"✅ Tổng hợp: {len(df_final)} dòng, {len(df_final.columns)} cột.")
181
  return df_final
182
 
183
  def extract_pdf_note(file_path: str) -> str: