Update app.py
Browse files123456724 unmodified lines3233343536373839404142434445121 unmodified lines1671681691701711721731741751761771781799 unmodified lines1891901911921931941958 unmodified lines2042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642653 unmodified lines269270271272273274# app.py — Transkrip PDF -> (preview) -> Tulis ke Template Excel# Tahap 1: Proses PDF hanya untuk mengekstrak & preview.# Tahap 2: Upload Excel template -> isi nilai sesuai nama MK -> unduh hasil.import os, re, tempfile, tracebackfrom io import BytesIOimport gradio as gr24 unmodified linesdef _read_uploaded(f):if f is None: return Noneif hasattr(f, "read"):try: f.seek(0)except Exception: passreturn f.read()if hasattr(f, "name") and isinstance(f.name, str) and os.path.exists(f.name):return open(f.name, "rb").read()if isinstance(f, str) and os.path.exists(f):return open(f, "rb").read()if isinstance(f, dict) and "path" in f and os.path.exists(f["path"]):return open(f["path"], "rb").read()raise gr.Error("File upload tidak dikenali.")121 unmodified linesif key in mk2nilai:ws.cell(val_row, c).value = mk2nilai[key]else:raise gr.Error("Mode tidak dikenal. Pilih auto/vertical/horizontal.")bio = BytesIO()wb.save(bio); bio.seek(0)return bio # BytesIO siap diunduh# ----------------- Tahap 1: Proses PDF -----------------def step1_process_pdf(pdf_file):if pdf_file is None:raise gr.Error("Unggah PDF transkrip dulu.")9 unmodified linespassreturn df, f"✅ PDF diproses. {len(df)} baris terdeteksi."# ----------------- Tahap 2: Isi Template -----------------def step2_apply_template(tpl_file, df_state, mode, sheet_name, header_row, value_row):if df_state is None or len(df_state) == 0:raise gr.Error("Belum ada hasil ekstraksi. Jalankan 'Proses PDF' dulu.")8 unmodified linesheader_row=int(header_row or 1),value_row_horizontal=int(value_row or 2),)# simpan ke file temp agar kompatibel dengan gr.File outputtmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")tmp.write(out.read()); tmp.flush(); tmp.close()return tmp.name, "✅ Nilai berhasil ditulis ke template."# ----------------- UI -----------------def build_ui():with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown(f"# {TITLE}")df_state = gr.State(value=None) # simpan hasil ekstraksi tahap 1with gr.Row():pdf = gr.File(label="1) PDF Transkrip", file_types=[".pdf"])tpl = gr.File(label="2) Excel Template (sesudah preview)", file_types=[".xlsx"])with gr.Row():btn_parse = gr.Button("Proses PDF", variant="primary")btn_apply = gr.Button("Isi Template Excel", variant="secondary")with gr.Accordion("Opsi Mapping Template", open=False):mode = gr.Radio(["auto", "vertical", "horizontal"],value="auto",label="Mode pengisian")sheet_name = gr.Textbox(label="Nama Sheet (kosongkan = aktif)", value="")header_row = gr.Number(label="Baris Header (default 1)", value=1, precision=0)value_row = gr.Number(label="Baris Nilai (horizontal) default 2", value=2, precision=0)gr.Markdown("### Hasil Ekstraksi")out_df = gr.Dataframe(wrap=True)status = gr.Textbox(label="Status", lines=3)gr.Markdown("### Unduh Excel Hasil (setelah isi template)")out_xlsx = gr.File(label="Excel Hasil")# wiring tahap 1def _store_df(df, msg):return df, df, msgbtn_parse.click(step1_process_pdf,inputs=[pdf],outputs=[out_df, status],).then(_store_df,inputs=[out_df, status],outputs=[df_state, out_df, status],)# wiring tahap 2btn_apply.click(step2_apply_template,inputs=[tpl, df_state, mode, sheet_name, header_row, value_row],outputs=[out_xlsx, status],)return demo3 unmodified linesport = int(os.environ.get("PORT", "7860"))demo.queue().launch(server_name="0.0.0.0", server_port=port)else:# kalau kamu pakai sdk: gradio, Spaces akan mencari 'app' / 'demo'demo = build_ui()app = demo1234524 unmodified lines3031323334353637383940414243444546121 unmodified lines1681691701711721731741751761771781791809 unmodified lines1901911921931941951968 unmodified lines2052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363 unmodified lines340341342343344# app.py — Transkrip PDF -> (preview) -> Tulis ke Template Excel# Mode: 1) Satu PDF, 2) Banyak PDF (Batch -> ZIP Excel)import os, re, tempfile, tracebackfrom io import BytesIOimport gradio as gr24 unmodified linesdef _read_uploaded(f):if f is None: return None# UploadedFile / file-likeif hasattr(f, "read"):try: f.seek(0)except Exception: passreturn f.read()# path on diskif hasattr(f, "name") and isinstance(f.name, str) and os.path.exists(f.name):return open(f.name, "rb").read()if isinstance(f, str) and os.path.exists(f):return open(f, "rb").read()# gradio dict {'name','size','data','path'}if isinstance(f, dict) and "path" in f and os.path.exists(f["path"]):return open(f["path"], "rb").read()raise gr.Error("File upload tidak dikenali.")121 unmodified linesif key in mk2nilai:ws.cell(val_row, c).value = mk2nilai[key]else:raise gr.Error("Mode tidak dikenali. Pilih auto/vertical/horizontal.")bio = BytesIO()wb.save(bio); bio.seek(0)return bio # BytesIO siap diunduh# ----------------- Tahap 1: Proses PDF (single) -----------------def step1_process_pdf(pdf_file):if pdf_file is None:raise gr.Error("Unggah PDF transkrip dulu.")9 unmodified linespassreturn df, f"✅ PDF diproses. {len(df)} baris terdeteksi."# ----------------- Tahap 2: Isi Template (single) -----------------def step2_apply_template(tpl_file, df_state, mode, sheet_name, header_row, value_row):if df_state is None or len(df_state) == 0:raise gr.Error("Belum ada hasil ekstraksi. Jalankan 'Proses PDF' dulu.")8 unmodified linesheader_row=int(header_row or 1),value_row_horizontal=int(value_row or 2),)tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")tmp.write(out.read()); tmp.flush(); tmp.close()return tmp.name, "✅ Nilai berhasil ditulis ke template."# ----------------- BATCH: preview banyak PDF -----------------def batch_preview(pdf_files):if not pdf_files:raise gr.Error("Unggah beberapa PDF dulu.")combined = []state_list = []for f in pdf_files:name = getattr(f, "name", None) or (isinstance(f, dict) and f.get("name")) or "file.pdf"base = os.path.splitext(os.path.basename(str(name)))[0]pdf_bytes = _read_uploaded(f)rows = parse_transcript_pdf(pdf_bytes)df = pd.DataFrame(rows, columns=["No","Mata Kuliah","SKS","Nilai"])df["Sumber"] = basetry:df["No"] = pd.to_numeric(df["No"], errors="coerce")df = df.sort_values("No").reset_index(drop=True)except Exception:passcombined.append(df)# simpan ke state sebagai dict (aman untuk serialisasi)state_list.append({"name": base, "rows": df[["No","Mata Kuliah","SKS","Nilai"]].to_dict(orient="records")})big = pd.concat(combined, ignore_index=True) if combined else pd.DataFrame()msg = f"✅ {len(state_list)} PDF diproses. Total baris: {len(big)}."return big, state_list, msg# ----------------- BATCH: apply template -> ZIP -----------------def _safe_name(s: str) -> str:s = re.sub(r"[^\w\-]+", "_", s.strip())return s.strip("_") or "output"def batch_apply(tpl_file, state_list, mode, sheet_name, header_row, value_row):import zipfileif not state_list:raise gr.Error("Belum ada hasil batch. Klik 'Proses Semua PDF' dulu.")if tpl_file is None:raise gr.Error("Unggah file Excel template dulu.")tpl_bytes = _read_uploaded(tpl_file)tmpzip = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")with zipfile.ZipFile(tmpzip.name, "w", compression=zipfile.ZIP_DEFLATED) as z:for item in state_list:base = _safe_name(item.get("name", "output"))df = pd.DataFrame(item["rows"])out = fill_template_with_df(df, tpl_bytes,mode=mode,sheet_name=(sheet_name or None),header_row=int(header_row or 1),value_row_horizontal=int(value_row or 2),)z.writestr(f"{base}.xlsx", out.getvalue())return tmpzip.name, f"✅ ZIP siap. {len(state_list)} file Excel dibuat."# ----------------- UI -----------------def build_ui():with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown(f"# {TITLE}")with gr.Tabs():# ---- Tab 1: Satu PDF ----with gr.Tab("Satu PDF"):df_state = gr.State(value=None)with gr.Row():pdf = gr.File(label="1) PDF Transkrip", file_types=[".pdf"])tpl = gr.File(label="2) Excel Template (setelah preview)", file_types=[".xlsx"])with gr.Row():btn_parse = gr.Button("Proses PDF", variant="primary")btn_apply = gr.Button("Isi Template Excel", variant="secondary")with gr.Accordion("Opsi Mapping Template", open=False):mode = gr.Radio(["auto", "vertical", "horizontal"], value="auto", label="Mode pengisian")sheet_name = gr.Textbox(label="Nama Sheet (kosongkan = aktif)", value="")header_row = gr.Number(label="Baris Header (default 1)", value=1, precision=0)value_row = gr.Number(label="Baris Nilai (horizontal) default 2", value=2, precision=0)gr.Markdown("### Hasil Ekstraksi")out_df = gr.Dataframe(wrap=True)status = gr.Textbox(label="Status", lines=3)gr.Markdown("### Unduh Excel Hasil (setelah isi template)")out_xlsx = gr.File(label="Excel Hasil")# wiring singledef _store_df(df, msg): return df, df, msgbtn_parse.click(step1_process_pdf, inputs=[pdf], outputs=[out_df, status])btn_parse.then(_store_df, inputs=[out_df, status], outputs=[df_state, out_df, status])btn_apply.click(step2_apply_template,inputs=[tpl, df_state, mode, sheet_name, header_row, value_row],outputs=[out_xlsx, status])# ---- Tab 2: Banyak PDF (Batch) ----with gr.Tab("Banyak PDF (Batch)"):batch_state = gr.State(value=[]) # list of {"name": str, "rows": [dict]}with gr.Row():pdfs = gr.File(label="1) PDF Transkrip (banyak)", file_types=[".pdf"], file_count="multiple")tpl_b = gr.File(label="2) Excel Template", file_types=[".xlsx"])with gr.Row():btn_prev = gr.Button("Proses Semua PDF", variant="primary")btn_apply_b = gr.Button("Isi Template (Batch)", variant="secondary")with gr.Accordion("Opsi Mapping Template (Batch)", open=False):mode_b = gr.Radio(["auto", "vertical", "horizontal"], value="auto", label="Mode pengisian")sheet_b = gr.Textbox(label="Nama Sheet (kosongkan = aktif)", value="")header_b = gr.Number(label="Baris Header (default 1)", value=1, precision=0)value_b = gr.Number(label="Baris Nilai (horizontal) default 2", value=2, precision=0)gr.Markdown("### Ringkasan Hasil Ekstraksi (gabungan)")out_df_b = gr.Dataframe(wrap=True)status_b = gr.Textbox(label="Status", lines=3)gr.Markdown("### Unduh ZIP Excel Hasil")out_zip = gr.File(label="ZIP Hasil")btn_prev.click(batch_preview, inputs=[pdfs], outputs=[out_df_b, batch_state, status_b])btn_apply_b.click(batch_apply,inputs=[tpl_b, batch_state, mode_b, sheet_b, header_b, value_b],outputs=[out_zip, status_b])return demo3 unmodified linesport = int(os.environ.get("PORT", "7860"))demo.queue().launch(server_name="0.0.0.0", server_port=port)else:demo = build_ui()app = demo
app.py+124-54