Download app.py from echosta/Transkrip: direct link, hf CLI and curl.
- Browser
- Download file 16.4 kB
-
https://huggingface.co/spaces/echosta/Transkrip/resolve/main/app.py
- Command line
-
hf download hf://spaces/echosta/Transkrip/app.py
-
curl -L -o app.py https://huggingface.co/spaces/echosta/Transkrip/resolve/main/app.py
16.4 kB
| # 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, traceback | |
| from io import BytesIO | |
| import gradio as gr | |
| import pandas as pd | |
| TITLE = "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 s | |
| def _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 s | |
| def _clean_int(s: str) -> str: | |
| s = _clean_text(s) | |
| m = re.search(r"\d+", s) | |
| return m.group(0) if m else s | |
| def _read_uploaded(f): | |
| if f is None: return None | |
| 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("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: continue | |
| for i, r in enumerate(t): | |
| if i == 0: # header | |
| continue | |
| cells = [(c or "").strip() for c in r] | |
| if len(cells) == 4: | |
| no,mk,sks,nl = cells | |
| if 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 = cells | |
| if 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 rows | |
| def _regex_lines(page): | |
| rows = [] | |
| txt = (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 rows | |
| def parse_transcript_pdf(pdf_bytes: bytes): | |
| import pdfplumber # lazy import | |
| rows = [] | |
| 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) | |
| # unique | |
| seen=set(); uniq=[] | |
| for no,mk,sks,nl in rows: | |
| key=(no,mk) | |
| if key in seen: continue | |
| seen.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 kurung | |
| s = s.replace("&","dan") | |
| s = re.sub(r"[^a-z0-9 ]", " ", s) | |
| s = re.sub(r"\s+"," ", s).strip() | |
| return s | |
| def _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, | |
| mode: str = "auto", # "auto" | "vertical" | "horizontal" | |
| sheet_name: str | None = None, | |
| header_row: int = 1, | |
| value_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->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 | |
| wb = openpyxl.load_workbook(BytesIO(template_bytes)) | |
| ws = wb[sheet_name] if (sheet_name and sheet_name in wb.sheetnames) else wb.active | |
| max_col = ws.max_column | |
| max_row = ws.max_row | |
| 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 | |
| # deteksi mode | |
| if mode == "auto": | |
| col_mk = find_col("mata kuliah") | |
| mode = "vertical" if col_mk else "horizontal" | |
| if 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 + 1 | |
| ws.cell(header_row, col_nilai).value = "Nilai" | |
| 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() == "") and stop_at_blank_vertical: | |
| break | |
| key = _norm_mk(str(mk_tmpl)) | |
| if key in mk2nilai: | |
| ws.cell(r, col_nilai).value = mk2nilai[key] | |
| r += 1 | |
| elif mode == "horizontal": | |
| val_row = value_row_horizontal | |
| 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(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 dibersihkan | |
| pdf_bytes = _read_uploaded(f) | |
| rows = parse_transcript_pdf(pdf_bytes) | |
| df = pd.DataFrame(rows, columns=["No","Mata Kuliah","SKS","Nilai"]) | |
| df["Sumber"] = base | |
| try: | |
| df["No"] = pd.to_numeric(df["No"], errors="coerce") | |
| df = df.sort_values("No").reset_index(drop=True) | |
| except Exception: | |
| pass | |
| combined.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 openpyxl | |
| if 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) | |
| wb = openpyxl.load_workbook(BytesIO(tpl_bytes)) | |
| ws = wb[sheet_name] if (sheet_name and sheet_name in wb.sheetnames) else wb.active | |
| hdr_row = int(header_row or 1) | |
| # petakan header MK -> kolom | |
| hdr_map = {} | |
| max_col = ws.max_column | |
| for 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 = None | |
| for c in range(1, max_col + 1): | |
| v = str(ws.cell(hdr_row, c).value or "").strip().lower() | |
| if v == wanted_label: | |
| name_col = c | |
| break | |
| if not name_col: | |
| raise gr.Error(f"Tidak menemukan kolom '{name_col_label}' pada baris header {hdr_row}.") | |
| # peta nama mahasiswa -> baris | |
| name2row = {} | |
| for r in range(hdr_row + 1, ws.max_row + 1): | |
| nm = ws.cell(r, name_col).value | |
| if nm is None or str(nm).strip() == "": | |
| continue | |
| name2row[_norm_name(str(nm))] = r | |
| missing_students = [] | |
| missing_courses = set() | |
| filled = 0 | |
| for item in state_list: | |
| pdf_name = _name_from_filename(item.get("name", "Mahasiswa")) # <<< pakai nama yang dibersihkan | |
| r_target = name2row.get(_norm_name(pdf_name)) | |
| if r_target is None: | |
| missing_students.append(pdf_name) | |
| continue | |
| df = 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", ""))) | |
| continue | |
| ws.cell(r_target, col).value = str(row.get("Nilai", "")) | |
| filled += 1 | |
| # simpan satu workbook | |
| tmp = 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.") | |
| pdf_bytes = _read_uploaded(pdf_file) | |
| rows = parse_transcript_pdf(pdf_bytes) | |
| if not rows: | |
| return None, "Tidak ada baris terdeteksi dari PDF." | |
| 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 | |
| return 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.") | |
| if tpl_file is None: | |
| raise gr.Error("Unggah file Excel template dulu.") | |
| tpl_bytes = _read_uploaded(tpl_file) | |
| out = fill_template_with_df( | |
| pd.DataFrame(df_state), | |
| 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), | |
| ) | |
| tmp = 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}") | |
| with gr.Tabs(): | |
| # -------- Tab 1: Satu PDF -------- | |
| with gr.Tab("Satu PDF"): | |
| df_state = gr.State(value=None) # simpan hasil ekstraksi tahap 1 | |
| with 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 1 | |
| def _store_df(df, msg): | |
| return df, df, msg | |
| evt = 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 2 | |
| 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) -> 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") | |
| 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, 1 Sheet)", variant="secondary") | |
| with gr.Accordion("Opsi Mapping Template (Batch)", open=False): | |
| sheet_b = gr.Textbox(label="Nama Sheet (kosongkan = aktif)", value="") | |
| header_b = gr.Number(label="Baris Header (default 1)", value=1, precision=0) | |
| name_col_label = gr.Textbox(label="Label kolom Nama di template", value="Nama") | |
| gr.Markdown("### Ringkasan Hasil Ekstraksi (gabungan)") | |
| out_df_b = gr.Dataframe(wrap=True) | |
| status_b = gr.Textbox(label="Status", lines=3) | |
| gr.Markdown("### Unduh Excel Hasil (satu sheet)") | |
| out_file = gr.File(label="Excel Hasil (1 file)") | |
| # wiring batch | |
| btn_prev.click(batch_preview, inputs=[pdfs], outputs=[out_df_b, batch_state, status_b]) | |
| btn_apply_b.click( | |
| batch_apply_one_sheet, | |
| inputs=[tpl_b, batch_state, sheet_b, header_b, name_col_label], | |
| outputs=[out_file, status_b], | |
| ) | |
| return demo | |
| # ------- Jalankan (runner python) atau ekspor objek (runner gradio) ------- | |
| if __name__ == "__main__": | |
| demo = build_ui() | |
| port = int(os.environ.get("PORT", "7860")) | |
| demo.queue().launch(server_name="0.0.0.0", server_port=port) | |
| else: | |
| demo = build_ui() | |
| app = demo | |