Team Ai
Apppublic

eccagli/pdf-processor

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py116 linesDownload Raw Back to root
1import streamlit as st2import os3import pdfplumber4import pandas as pd5import datetime6from PyPDF2 import PdfMerger7import urllib8 9# Set page title10st.title("Zappap Plaka Sistemi")11 12# File uploader for multiple PDFs13uploaded_files = st.file_uploader("PDF Dosyalarını seçiniz...", type=["pdf"], accept_multiple_files=True)14 15# Input fields16yon = st.radio("Yön Seçiniz...", ["Cikis", "Giris"], index=None)  # No default selection17if yon is None:18    st.error("Giris / Cikis ?")  # Display error message19    st.stop()  # Prevent further execution20belge_no = st.text_input("Beyanname No Yazınız...", "")21 22# Process button23if st.button("İşlemi Başlat"):24    if uploaded_files:25        # Create temporary folder to save files26        path = "temp_files"27        os.makedirs(path, exist_ok=True)28 29        filenames = []30        for uploaded_file in uploaded_files:31            file_path = os.path.join(path, uploaded_file.name)32            with open(file_path, "wb") as f:33                f.write(uploaded_file.getbuffer())34            filenames.append(file_path)35 36        # Merge PDFs37        merger = PdfMerger()38        for pdf in filenames:39            merger.append(pdf)40        output_pdf = os.path.join(path, "combined_sami.pdf")41        merger.write(output_pdf)42        merger.close()43 44        # Extract data from PDF45        pdf = pdfplumber.open(output_pdf)46        all_pages = [pd.DataFrame(page.extract_table()[1:], columns=page.extract_table()[0]) for page in pdf.pages]47        all_data = pd.concat(all_pages)48 49        date_time = all_data.iloc[:, -1].str.split(expand=True)50        date_time.columns = ["date", "time"]51        date_time["date"] = date_time["date"].apply(lambda x: x if "/" in x else x.replace(".", "/"))52 53        df = pd.DataFrame(all_data["Araç Plaka"])54        df.insert(0, "YÖN", yon)55        df.insert(1, "BELGE_TÜRÜ", 3 if yon == "Cikis" else "")56        df.insert(2, "BELGE_NO", belge_no)57        df.insert(4, "DORSE1", "")58        df.insert(5, "DORSE2", "")59        df.insert(6, "date", date_time["date"])60        df.insert(7, "time", date_time["time"])61        df = df.set_index("YÖN")62 63        # Download template & save Excel file64        url = "http://www.mavi.web.tr/ygms/Arac_Giris_Cikis_Aktarim_Sablon.xls"65        template_path = os.path.join(path, "sablon.xls")66        urllib.request.urlretrieve(url, template_path)67        68        import xlrd69        import xlwt70        from xlutils.copy import copy  # Allows modifying existing .xls file71        72        # Open the existing .xls template73        rb = xlrd.open_workbook(template_path, formatting_info=True)  # Read existing file74        wb = copy(rb)  # Make a writable copy75        sheet = wb.get_sheet(0)  # Select the first sheet76        77        # Define the starting row where data should be inserted (adjust as needed)78        start_row = 1  # Assuming row 0 has headers, and data starts from row 179        80        # Define cell formats81        general_format = xlwt.easyxf("")  # General format (default)82        text_format = xlwt.XFStyle()  83        text_format.num_format_str = "@"  # Force text format in Excel84        85        # Reset index to avoid issues86        df = df.reset_index(drop=True)87        88        # Insert data into the template without altering formatting89        for i, row in df.iterrows():90            excel_row = start_row + int(i)91        92            # Fix "YÖN" column logic93            yon_value = "Ç" if yon == "Cikis" else "G"  # Use the Streamlit user selection94        95            # Write data to each column (except header)96            sheet.write(excel_row, 0, yon_value, text_format)          # Column A97            sheet.write(excel_row, 1, str(row.get("BELGE_TÜRÜ", "")), text_format)   # Column B98            sheet.write(excel_row, 2, str(row.get("BELGE_NO", "")), text_format)     # Column C99            sheet.write(excel_row, 3, str(row.get("Araç Plaka", "")), text_format)   # Column D100            sheet.write(excel_row, 4, str(row.get("DORSE1", "")), text_format)       # Column E101            sheet.write(excel_row, 5, str(row.get("DORSE2", "")), text_format)       # Column F102            sheet.write(excel_row, 6, str(row.get("date", "")), text_format)         # Column G103            sheet.write(excel_row, 7, str(row.get("time", "")), text_format)         # Column H104        105        # Save the modified file106        output_xls = os.path.join(path, f"Sami-{datetime.datetime.today().strftime('%Y-%m-%d-%H-%M-%S')}.xls")107        wb.save(output_xls)108 109        # Display success message & download link110        st.success("İşlem Tamam!")111        with open(output_xls, "rb") as f:112            st.download_button("İşlenen Excel İndir!", f, file_name=os.path.basename(output_xls))113 114    else:115        st.warning("En az bir PDF yükleyin!")116