Update app.py
Browse files123456789101112131415161718192021222324252615 unmodified lines4243444546474849505152535455565758596061626364656667681 unmodified line7071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161173 unmodified lines12112212312412512612712812913013 unmodified lines1441451461471481491501 unmodified line1521531541551561571581591 unmodified line1611621631641651661671681691701711721731741 unmodified line1761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122136 unmodified lines2202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822839 unmodified lines29329429529629729829912 unmodified lines3123133143153163173183193203213223233243253264 unmodified lines3313323333343353363373383393403415 unmodified lines34734834935035135235335435535635735835936036136236336436536636736836937037137237337437537615 unmodified lines3923933943953963973983 unmodified lines402403404405406407408# app.py — Transkrip PDF -> (preview) -> Tulis ke Template Excel# Mode: 1) Satu PDF, 2) Banyak PDF (Batch -> SATU sheet pada SATU file Excel)import os, re, tempfile, tracebackfrom io import BytesIOimport gradio as grimport pandas as pdTITLE = "Transkrip → Excel (IAI IMSYA)"# ----------------- Helpers umum -----------------def _clean_text(s: str) -> str:if s is None: return ""s = s.replace("\uFFFD","-").replace("","-").replace("","-")s = s.replace("\xa0"," ").replace("\n"," ").replace("\r"," ")s = re.sub(r"\s+", " ", s).strip()return sdef _clean_grade(s: str) -> str:s = _clean_text(s).upper()s = s.replace("A–","A-").replace("B–","B-").replace("C–","C-")s = s.replace("A+","A+").replace("B+","B+").replace("C+","C+")s = s.replace("A−","A-").replace("B−","B-").replace("C−","C-")m = re.search(r"[ABCD](\+|-)?", s)return m.group(0) if m else sdef _clean_int(s: str) -> str:15 unmodified linesreturn open(f["path"], "rb").read()raise gr.Error("File upload tidak dikenali.")# ----------------- Ekstraksi PDF -----------------def _try_table_extract(page):rows = []settings = dict(vertical_strategy="lines", horizontal_strategy="lines", intersection_tolerance=5)try:tables = page.extract_tables(settings) or []except Exception:tables = []for t in tables:if not t: continuefor i, r in enumerate(t):if i == 0: # headercontinuecells = [(c or "").strip() for c in r]if len(cells) == 4:no,mk,sks,nl = cellsif mk: rows.append((_clean_int(no), _clean_text(mk), _clean_int(sks), _clean_grade(nl)))elif len(cells) == 8:no,mk,sks,nl,no2,mk2,sks2,nl2 = cellsif mk: rows.append((_clean_int(no), _clean_text(mk), _clean_int(sks), _clean_grade(nl)))if mk2: rows.append((_clean_int(no2), _clean_text(mk2), _clean_int(sks2), _clean_grade(nl2)))return rowsdef _regex_lines(page):1 unmodified linetxt = (page.extract_text() or "").replace("\r"," ").replace("\xa0"," ")pat = re.compile(r"^\s*(\d{1,3})\s+([A-Za-z0-9().,\- /&]+?)\s+(\d{1,2})\s+([A-D][\+\-]?)\s*$", re.MULTILINE)for m in re.finditer(pat, txt):no,mk,sks,nl = m.groups()rows.append((_clean_int(no), _clean_text(mk), _clean_int(sks), _clean_grade(nl)))return rowsdef parse_transcript_pdf(pdf_bytes: bytes):import pdfplumber # lazy importrows = []with pdfplumber.open(BytesIO(pdf_bytes)) as pdf:for page in pdf.pages:part = _try_table_extract(page)if not part or len(part) < 5:part = _regex_lines(page)rows.extend(part)# uniqueseen=set(); uniq=[]for no,mk,sks,nl in rows:key=(no,mk)if key in seen: continueseen.add(key); uniq.append((no,mk,sks,nl))return uniq# ----------------- Normalisasi -----------------def _norm_mk(s: str) -> str:s = (s or "").lower()s = re.sub(r"\([^)]*\)", " ", s) # buang dalam kurungs = s.replace("&","dan")s = re.sub(r"[^a-z0-9 ]", " ", s)s = re.sub(r"\s+"," ", s).strip()return sdef _norm_name(s: str) -> str:return re.sub(r"\s+"," ", (s or "").strip().lower())def _name_from_filename(name_like) -> str:"""Ambil nama mhs dari nama file: buang kata umum ('transkrip','nilai',dll)."""base = os.path.splitext(os.path.basename(str(name_like)))[0]s = base.replace("_", " ").replace("-", " ")s = re.sub(r"(?i)\b(transkrip|transcript|nilai|kartu|ujian|khs|krs)\b", " ", s)s = re.sub(r"\s+", " ", s).strip()return s# ----------------- Tulis ke Template (single, per DF) -----------------def fill_template_with_df(df: pd.DataFrame,template_bytes: bytes,3 unmodified linesvalue_row_horizontal: int = 2,stop_at_blank_vertical: bool = True):"""Isi template berdasarkan df [No, Mata Kuliah, SKS, Nilai]."""import openpyxl # lazy import# kamus MK->Nilaimk2nilai = {}for _, r in df.iterrows():mk = str(r.get("Mata Kuliah") or r.get("MataKuliah") or r.get("Mata_kuliah") or "")13 unmodified linesif v == label.lower(): return creturn None# deteksi modeif mode == "auto":col_mk = find_col("mata kuliah")mode = "vertical" if col_mk else "horizontal"1 unmodified lineif mode == "vertical":col_mk = find_col("mata kuliah")col_nilai = find_col("nilai")if not col_mk:raise gr.Error("Template vertikal butuh kolom header 'Mata Kuliah' (baris header).")if not col_nilai:col_nilai = col_mk + 1ws.cell(header_row, col_nilai).value = "Nilai"1 unmodified liner = header_row + 1while r <= max_row:mk_tmpl = ws.cell(r, col_mk).valueif (mk_tmpl is None or str(mk_tmpl).strip() == "") and stop_at_blank_vertical:breakkey = _norm_mk(str(mk_tmpl))if key in mk2nilai:ws.cell(r, col_nilai).value = mk2nilai[key]r += 1elif mode == "horizontal":val_row = value_row_horizontalfor c in range(1, max_col+1):header = ws.cell(header_row, c).value1 unmodified linekey = _norm_mk(str(header))if 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# ----------------- Batch: preview banyak PDF (gabungan) -----------------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 = _name_from_filename(name) # <<< pakai nama yang sudah dibersihkanpdf_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)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: isi ke SATU sheet berdasarkan Nama + MK -----------------def batch_apply_one_sheet(tpl_file, state_list, sheet_name, header_row, name_col_label):import openpyxlif not state_list:6 unmodified linesws = wb[sheet_name] if (sheet_name and sheet_name in wb.sheetnames) else wb.activehdr_row = int(header_row or 1)# petakan header MK -> kolomhdr_map = {}max_col = ws.max_columnfor c in range(1, max_col + 1):hdr_map[_norm_mk(str(ws.cell(hdr_row, c).value or ""))] = c# cari kolom "Nama"wanted_label = (name_col_label or "Nama").strip().lower()name_col = Nonefor c in range(1, max_col + 1):v = str(ws.cell(hdr_row, c).value or "").strip().lower()if v == wanted_label:name_col = cbreakif not name_col:raise gr.Error(f"Tidak menemukan kolom '{name_col_label}' pada baris header {hdr_row}.")# peta nama mahasiswa -> barisname2row = {}for r in range(hdr_row + 1, ws.max_row + 1):nm = ws.cell(r, name_col).valueif nm is None or str(nm).strip() == "":continuename2row[_norm_name(str(nm))] = rmissing_students = []missing_courses = set()filled = 0for item in state_list:pdf_name = _name_from_filename(item.get("name", "Mahasiswa")) # <<< pakai nama yang dibersihkanr_target = name2row.get(_norm_name(pdf_name))if r_target is None:missing_students.append(pdf_name)continuedf = pd.DataFrame(item["rows"])for _, row in df.iterrows():mk_norm = _norm_mk(str(row.get("Mata Kuliah", "")))col = hdr_map.get(mk_norm)if not col:missing_courses.add(str(row.get("Mata Kuliah", "")))continuews.cell(r_target, col).value = str(row.get("Nilai", ""))filled += 1# simpan satu workbooktmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")wb.save(tmp.name); tmp.flush(); tmp.close()note = [f"✅ Selesai. {filled} sel diisi."]if missing_students:note.append("⚠️ Mahasiswa tidak ada di template: " + ", ".join(sorted(set(missing_students))))if missing_courses:note.append("⚠️ Kolom MK tidak ada di template: " + ", ".join(sorted(set(missing_courses))))return tmp.name, "\n".join(note)# ----------------- Tahap 1 (single): 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 (single): 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.")12 unmodified linestmp.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}")with gr.Tabs():# -------- Tab 1: Satu PDF --------with gr.Tab("Satu PDF"):df_state = gr.State(value=None) # simpan hasil ekstraksi tahap 1with gr.Row():pdf = gr.File(label="1) PDF Transkrip", file_types=[".pdf"])4 unmodified linesbtn_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)5 unmodified linesgr.Markdown("### Unduh Excel Hasil (setelah isi template)")out_xlsx = gr.File(label="Excel Hasil")# wiring tahap 1def _store_df(df, msg):return df, df, msgevt = btn_parse.click(step1_process_pdf,inputs=[pdf],outputs=[out_df, status],)evt.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],)# -------- Tab 2: Banyak PDF (Batch) -> SATU sheet --------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")15 unmodified linesgr.Markdown("### Unduh Excel Hasil (satu sheet)")out_file = gr.File(label="Excel Hasil (1 file)")# wiring batchbtn_prev.click(batch_preview, inputs=[pdfs], outputs=[out_df_b, batch_state, status_b])btn_apply_b.click(batch_apply_one_sheet,3 unmodified linesreturn demo# ------- Jalankan (runner python) atau ekspor objek (runner gradio) -------if __name__ == "__main__":demo = build_ui()port = int(os.environ.get("PORT", "7860"))12345678910111213141516171819202122232425262715 unmodified lines4344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371 unmodified line1391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272283 unmodified lines23223323423523623723813 unmodified lines2522532542552562571 unmodified line2592602612622632642652661 unmodified line2682692702712722732742752762772782792802811 unmodified line2832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243256 unmodified lines3323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114129 unmodified lines42242342442542642712 unmodified lines4404414424434444454464474484494504514524534544 unmodified lines4594604614624634644655 unmodified lines47147247347447547647747847948048148248348448548648748848915 unmodified lines5055065075085095103 unmodified lines514515516517518519# app.py — Transkrip PDF -> (preview) -> Tulis ke Template Excel# Mode: 1) Satu PDF, 2) Banyak PDF (Batch -> SATU sheet pada SATU file Excel)import os, re, tempfile, difflibfrom io import BytesIOimport gradio as grimport pandas as pdTITLE = "Transkrip → Excel (IAI IMSYA)"# =============== Util umum ===============def _clean_text(s: str) -> str:if s is None: return ""s = s.replace("\uFFFD","-").replace("","-").replace("","-")s = s.replace("\xa0"," ").replace("\r"," ").replace("\n"," ")s = re.sub(r"\s+"," ", s).strip()return sdef _clean_grade(s: str) -> str:s = _clean_text(s).upper()s = (s.replace("A–","A-").replace("B–","B-").replace("C–","C-").replace("A+","A+").replace("B+","B+").replace("C+","C+").replace("A−","A-").replace("B−","B-").replace("C−","C-"))m = re.fullmatch(r"[ABCD](\+|-)?", s)return m.group(0) if m else sdef _clean_int(s: str) -> str:15 unmodified linesreturn open(f["path"], "rb").read()raise gr.Error("File upload tidak dikenali.")# =============== Normalisasi kunci ===============def _norm_mk(s: str) -> str:s = (s or "").lower()s = re.sub(r"\([^)]*\)", " ", s) # buang (…)s = s.replace("&","dan")s = re.sub(r"[^a-z0-9 ]"," ", s)s = re.sub(r"\s+"," ", s).strip()return sdef _norm_name(s: str) -> str:return re.sub(r"\s+"," ", (s or "").strip().lower())def _name_from_filename(name_like) -> str:base = os.path.splitext(os.path.basename(str(name_like)))[0]s = base.replace("_", " ").replace("-", " ")s = re.sub(r"(?i)\b(transkrip|transcript|nilai|kartu|ujian|khs|krs|full)\b"," ", s)s = re.sub(r"\s+"," ", s).strip()return sdef _best_match(query: str, choices: list[str], cutoff: float = 0.78) -> str | None:if not query or not choices: return Noneres = difflib.get_close_matches(query, choices, n=1, cutoff=cutoff)return res[0] if res else None# =============== Ekstraksi PDF ===============def _try_table_extract(page):"""Ekstraksi tabel via pdfplumber; cover:- 4 kolom (No | MK | SKS | Nilai)- 7 kolom (No | Kode | MK | Nilai | AM | SKS | Bobot)- tabel dua-blok (kiri-kanan) di satu halaman"""rows = []settings = dict(vertical_strategy="lines", horizontal_strategy="lines", intersection_tolerance=5)try:tables = page.extract_tables(settings) or []except Exception:tables = []for t in tables:if not t: continue# beberapa file punya header di baris 0; kita loncatifor i, r in enumerate(t):if i == 0: # asumsi headercontinuecells = [(c or "").strip() for c in r]if not any(cells):continue# 4 kolom klasikif len(cells) == 4:no, mk, sks, nl = cellsif mk:rows.append((_clean_int(no), _clean_text(mk), _clean_int(sks), _clean_grade(nl)))continue# 7 kolom IMSYAif len(cells) >= 7:no = cells[0]; mk = cells[2]# cari grade & sks dari sisi kanan blokgrade, sks = None, Nonefor j in range(3, len(cells)):g = _clean_grade(cells[j])if re.fullmatch(r"[ABCD](\+|-)?", g or ""):grade = g# cari SKS di 1–3 kolom setelah gradefor k in range(j+1, min(j+4, len(cells))):cand = _clean_int(cells[k] or "")if cand.isdigit() and 0 < int(cand) <= 9:sks = cand; breakbreakif mk and grade and sks:rows.append((_clean_int(no), _clean_text(mk), sks, grade))continue# fallback tabel lebar (>=6 kolom): ambil MK di kolom 2/1, grade & sks dari kananif len(cells) >= 6:mk = cells[2] if len(cells) > 2 else cells[1]grade, sks = None, Nonefor j in range(len(cells)-1, -1, -1):tj = cells[j].strip()if not grade and re.fullmatch(r"[ABCD](?:\+|-)?", _clean_grade(tj) or ""):grade = _clean_grade(tj); continueif grade and sks is None:cand = _clean_int(tj)if cand.isdigit() and 0 < int(cand) <= 9:sks = cand; breakif mk and grade and sks:rows.append(("", _clean_text(mk), sks, grade))return rowsdef _regex_lines(page):1 unmodified linetxt = (page.extract_text() or "").replace("\r"," ").replace("\xa0"," ")pat = re.compile(r"^\s*(\d{1,3})\s+([A-Za-z0-9().,\- /&]+?)\s+(\d{1,2})\s+([A-D][\+\-]?)\s*$", re.MULTILINE)for m in re.finditer(pat, txt):no, mk, sks, nl = m.groups()rows.append((_clean_int(no), _clean_text(mk), _clean_int(sks), _clean_grade(nl)))return rowsdef _flex_lines(page):"""Fallback baris bebas:<MK> <GRADE> [<AM>] <SKS> [<BOBOT>]GRADE di kanan, SKS di kanan grade."""rows = []text = page.extract_text() or ""pat = re.compile(r"^(?P<name>.+?)\s+(?P<grade>[ABCD][+\-]?)\s+(?:(?P<am>\d+(?:[.,]\d+)?)\s+)?(?P<sks>\d{1,2})(?:\s+\S+)?\s*$",re.IGNORECASE)for raw in text.split("\n"):s = _clean_text(raw)if not s: continueif re.search(r"\b(kode|mata|mk|sks|nilai|semester|jumlah|total|transkrip)\b", s, re.I):continuem = pat.match(s)if not m: continuename = m.group("name")grade = _clean_grade(m.group("grade"))sks = _clean_int(m.group("sks"))# buang No/Kode di awalname = re.sub(r"^\d+\s+", "", name)name = re.sub(r"^[A-Z]{2,}\d{2,}\s+", "", name)name = re.sub(r"^[A-Z]{2,}\s+\d{2,}\s+", "", name)name = _clean_text(name)if len(name) < 2: continuerows.append(("", name, sks, grade))return rowsdef _extract_name_from_pdf(pdf_bytes: bytes) -> str | None:import pdfplumbertxt = ""try:with pdfplumber.open(BytesIO(pdf_bytes)) as pdf:for p in pdf.pages[:2]:t = p.extract_text() or ""txt += "\n" + texcept Exception:return Nonetxt = _clean_text(txt).upper()# Nama: ... / Nama Mahasiswa: ...for pat in [r"NAMA\s*:\s*([A-Z .'\-]+)", r"NAMA\s*MAHASISWA\s*:\s*([A-Z .'\-]+)"]:m = re.search(pat, txt, re.I)if m:name = m.group(1).strip()# buang embel-embel setelahnya (mis. " PROGRAM PENDIDIKAN …")name = name.split(" PROGRAM PENDIDIKAN")[0].strip()return namereturn Nonedef parse_transcript_pdf(pdf_bytes: bytes):import pdfplumberrows = []with pdfplumber.open(BytesIO(pdf_bytes)) as pdf:for page in pdf.pages:part = _try_table_extract(page)if not part or len(part) < 5:more = _regex_lines(page)if more: part.extend(more)if not part or len(part) < 5:more = _flex_lines(page)if more: part.extend(more)rows.extend(part)# unique + isi nomor jika kosongseen, uniq = set(), []n = 1for no, mk, sks, nl in rows:key = (mk, sks, nl)if key in seen:continueseen.add(key)if not str(no).strip():no = n; n += 1uniq.append((no, mk, sks, nl))return uniq# =============== Tulis ke Template (single PDF) ===============def fill_template_with_df(df: pd.DataFrame,template_bytes: bytes,3 unmodified linesvalue_row_horizontal: int = 2,stop_at_blank_vertical: bool = True):import openpyxlmk2nilai = {}for _, r in df.iterrows():mk = str(r.get("Mata Kuliah") or r.get("MataKuliah") or r.get("Mata_kuliah") or "")13 unmodified linesif v == label.lower(): return creturn Noneif mode == "auto":col_mk = find_col("mata kuliah")mode = "vertical" if col_mk else "horizontal"1 unmodified lineif mode == "vertical":col_mk = find_col("mata kuliah")col_nilai = find_col("nilai")if not col_mk:raise gr.Error("Template vertikal butuh header 'Mata Kuliah'.")if not col_nilai:col_nilai = col_mk + 1ws.cell(header_row, col_nilai).value = "Nilai"1 unmodified liner = header_row + 1while r <= max_row:mk_tmpl = ws.cell(r, col_mk).valueif (mk_tmpl is None or str(mk_tmpl).strip()=="") and stop_at_blank_vertical:breakkey = _norm_mk(str(mk_tmpl))if key in mk2nilai:ws.cell(r, col_nilai).value = mk2nilai[key]r += 1else: # horizontalval_row = value_row_horizontalfor c in range(1, max_col+1):header = ws.cell(header_row, c).value1 unmodified linekey = _norm_mk(str(header))if key in mk2nilai:ws.cell(val_row, c).value = mk2nilai[key]bio = BytesIO()wb.save(bio); bio.seek(0)return bio# =============== Batch: Preview ===============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"pdf_bytes = _read_uploaded(f)detected = _extract_name_from_pdf(pdf_bytes)base = detected if detected else _name_from_filename(name)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)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: Isi ke 1 sheet (Nama + MK) ===============def batch_apply_one_sheet(tpl_file, state_list, sheet_name, header_row, name_col_label):import openpyxlif not state_list:6 unmodified linesws = wb[sheet_name] if (sheet_name and sheet_name in wb.sheetnames) else wb.activehdr_row = int(header_row or 1)# peta header -> kolom + daftar untuk fuzzyhdr_map, hdr_keys = {}, []max_col = ws.max_columnfor c in range(1, max_col+1):key = _norm_mk(str(ws.cell(hdr_row, c).value or ""))if key:hdr_map[key] = chdr_keys.append(key)# kolom namawanted = (name_col_label or "Nama").strip().lower()name_col = Nonefor c in range(1, max_col+1):v = str(ws.cell(hdr_row, c).value or "").strip().lower()if v == wanted:name_col = c; breakif not name_col:raise gr.Error(f"Tidak menemukan kolom '{name_col_label}' pada baris header {hdr_row}.")# peta nama template -> barisname2row, template_names = {}, []for r in range(hdr_row+1, ws.max_row+1):nm = ws.cell(r, name_col).valueif not nm or str(nm).strip()=="":continuek = _norm_name(str(nm))name2row[k] = rtemplate_names.append(k)missing_students, missing_courses = [], set()filled, matched = 0, 0for item in state_list:raw = item.get("name", "Mahasiswa")key = _norm_name(raw)r_target = name2row.get(key)if r_target is None:guess = _best_match(key, template_names, cutoff=0.78)if guess:r_target = name2row[guess]if r_target is None:missing_students.append(raw)continueelse:matched += 1df = pd.DataFrame(item["rows"])for _, row in df.iterrows():mk_norm = _norm_mk(str(row.get("Mata Kuliah","")))col = hdr_map.get(mk_norm)if col is None:mk_guess = _best_match(mk_norm, hdr_keys, cutoff=0.78)if mk_guess is not None:col = hdr_map.get(mk_guess)if not col:missing_courses.add(str(row.get("Mata Kuliah","")))continuews.cell(r_target, col).value = str(row.get("Nilai",""))filled += 1tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")wb.save(tmp.name); tmp.flush(); tmp.close()total = len(state_list)note = [f"✅ Selesai. Mahasiswa terdeteksi: {total}. Cocok dengan template: {matched}/{total}. Sel terisi: {filled}."]if missing_students:note.append("⚠️ Nama di PDF tidak ada/mirip di template: " + ", ".join(sorted(set(missing_students))))if missing_courses:note.append("⚠️ Kolom MK tidak ditemukan di template: " + ", ".join(sorted(set(missing_courses))))return tmp.name, "\n".join(note)# =============== Satu PDF: Proses & Isi Template ===============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."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.")12 unmodified linestmp.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}")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"])4 unmodified linesbtn_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)5 unmodified linesgr.Markdown("### Unduh Excel Hasil (setelah isi template)")out_xlsx = gr.File(label="Excel Hasil")def _store_df(df, msg): return df, df, msgevt = btn_parse.click(step1_process_pdf, inputs=[pdf], outputs=[out_df, status])evt.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=[])with gr.Row():pdfs = gr.File(label="1) PDF Transkrip (banyak)", file_types=[".pdf"], file_count="multiple")15 unmodified linesgr.Markdown("### Unduh Excel Hasil (satu sheet)")out_file = gr.File(label="Excel Hasil (1 file)")btn_prev.click(batch_preview, inputs=[pdfs], outputs=[out_df_b, batch_state, status_b])btn_apply_b.click(batch_apply_one_sheet,3 unmodified linesreturn demoif __name__ == "__main__":demo = build_ui()port = int(os.environ.get("PORT", "7860"))
app.py+229-118