Update app.py
Browse files1212345676789101112131415891718192021101112131415161718192021222324232425252627282930272829303132333132333536373839343536374142433839404142434445464748494546474851525354555649505158595253616263646554555657586768697071727374757677785960616263646566676869707180818283848586878889727374919293949575# --- ganti seluruh fungsi write_to_excel dengan ini ---import re, os# app.pyimport os, tempfile, tracebackimport gradio as grimport pandas as pdfrom io import BytesIOfrom parser import parse_transcript_pdf, write_to_excel # pastikan file: parser.py
def _norm_mk(s: str) -> str: """Normalisasi nama mata kuliah agar match meski beda spasi/tanda baca.""" s = (s or "").lower() # buang isi dalam kurung dan keterangan tambahan umum s = re.sub(r"\([^)]*\)", " ", s) s = s.replace("&", "dan") # hapus tanda baca, spasi ganda s = re.sub(r"[^a-z0-9 ]", " ", s) s = re.sub(r"\s+", " ", s).strip() return sTITLE = "Transkrip → Excel (IAI IMSYA)"
def write_to_excel(df: pd.DataFrame, out_target, template_bytes: bytes | None = None): """ Isi template Excel berdasarkan nama mata kuliah. - Mode VERTIKAL: ada kolom 'Mata Kuliah' di header -> tulis nilai ke kolom 'Nilai' pada baris yang sama. - Mode HORIZONTAL: header baris 1 adalah nama-nama mata kuliah -> tulis nilai di baris 2 pada kolom yang cocok.def _read_uploaded(f): if f is None: return None # urutan aman: file-like → .name → str path → dict{'path'} if hasattr(f, "read"): try: f.seek(0) except Exception: pass return 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("Format file upload tidak dikenali.")
out_target: path string ATAU stream (BytesIO/file-like) """ import openpyxldef run(pdf_file, template_xlsx): logs = [] try: if pdf_file is None: raise gr.Error("Mohon unggah PDF transkrip.")
# Kamus {mk_norm: nilai} mk2nilai = {} for _, r in df.iterrows(): mk = str(r.get("Mata Kuliah") or r.get("MataKuliah") or r.get("Mata_kuliah") or "") nl = str(r.get("Nilai") or "") if mk.strip(): mk2nilai[_norm_mk(mk)] = nl logs.append("📥 Membaca PDF…") pdf_bytes = _read_uploaded(pdf_file)
# Jika tidak ada template: buat file baru standar (fallback) if not template_bytes: with pd.ExcelWriter(out_target, engine="openpyxl") as xw: df.to_excel(xw, index=False, sheet_name="Transkrip") return rows = parse_transcript_pdf(pdf_bytes) if not rows: return pd.DataFrame(), None, "Tidak ada baris terdeteksi dari PDF."
# Load template wb = openpyxl.load_workbook(BytesIO(template_bytes)) ws = wb["TRANSKIP OK"] if "TRANSKIP OK" in wb.sheetnames else wb.active df = pd.DataFrame(rows, columns=["No","Mata Kuliah","SKS","Nilai"]) try: df["No"] = pd.to_numeric(df["No"], errors="coerce") df = df.sort_values("No").reset_index(drop=True) except Exception: pass
# Deteksi mode # Cek apakah ada kolom 'Mata Kuliah' (mode vertikal) header_row = 1 max_col = ws.max_column max_row = ws.max_row tpl_bytes = _read_uploaded(template_xlsx) if template_xlsx else None tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx") tmp_path = tmp.name; tmp.close()
def find_col(label): for c in range(1, max_col + 1): v = str(ws.cell(header_row, c).value or "").strip().lower() if v == label.lower(): return c return None write_to_excel(df, tmp_path, tpl_bytes) logs.append(f"✅ Selesai. {len(df)} baris.")
col_mk = find_col("mata kuliah") col_nilai = find_col("nilai") return df, tmp_path, "\n".join(logs)
if col_mk: # ===== Mode VERTIKAL ===== if not col_nilai: # bikin kolom Nilai di sebelah kanan kolom Mata Kuliah col_nilai = col_mk + 1 ws.cell(header_row, col_nilai).value = "Nilai" except gr.Error as e: return None, None, f"ERROR: {e}" except Exception as e: return None, None, f"ERROR tak terduga: {e}\n\n{traceback.format_exc()}"
# isi per baris r = header_row + 1 while r <= max_row: mk_tmpl = ws.cell(r, col_mk).value if mk_tmpl is None or str(mk_tmpl).strip() == "": # jika baris kosong panjang, berhenti # (kalau masih ada mata kuliah di bawah, ganti logic ini jadi r += 1) break key = _norm_mk(str(mk_tmpl)) if key in mk2nilai: ws.cell(r, col_nilai).value = mk2nilai[key] r += 1def build_ui(): with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown(f"# {TITLE}") with gr.Row(): pdf = gr.File(label="PDF Transkrip", file_types=[".pdf"]) tpl = gr.File(label="Template Excel (opsional)", file_types=[".xlsx"]) btn = gr.Button("Proses") out_df = gr.Dataframe(label="Hasil Ekstraksi", wrap=True) out_xlsx = gr.File(label="Unduh Excel") status = gr.Textbox(label="Status", lines=8) btn.click(run, inputs=[pdf, tpl], outputs=[out_df, out_xlsx, status]) return demo
else: # ===== Mode HORIZONTAL ===== # anggap baris 1 adalah header mata kuliah; tulis nilai di baris 2 value_row = header_row + 1 for c in range(1, max_col + 1): header = ws.cell(header_row, c).value if header is None: continue key = _norm_mk(str(header)) if key in mk2nilai: ws.cell(value_row, c).value = mk2nilai[key]# >>> INI PENTING untuk Spaces: ekspor objek Gradio bernama `demo` di level moduldemo = build_ui()
# Simpan if isinstance(out_target, (str, os.PathLike)): wb.save(out_target) else: wb.save(out_target)# Jangan panggil demo.launch() di Spacesapp.py+60-80