CoolFace
Apppublic

Nomanalvi/PDF_Convertor

sourceHugging Faceafl-3.0updated 4y agoView on Hugging Face
1likes
pdfconv.py108 linesDownload Raw Back to root
1import streamlit as st  # data app development2import subprocess  # process in the os3from subprocess import STDOUT, check_call  # os process manipuation4import os  # os process manipuation5import base64  # byte object into a pdf file6import camelot as cam  # extracting tables from PDFs7import pandas as pd8from io import BytesIO9import ctypes10from ctypes.util import find_library11from pyxlsb import open_workbook as open_xlsb12find_library("".join(("gsdll", str(ctypes.sizeof(ctypes.c_voidp) * 8), ".dll")))13#<name-of-ghostscript-library-on-windows>14# to run this only once and it's cached15@st.cache16def gh():17    """install ghostscript on the linux machine"""18    proc = subprocess.Popen('apt-get install -y ghostscript', shell=True, stdin=None, stdout=open(os.devnull, "wb"),19                            stderr=STDOUT, executable="/bin/bash")20    proc.wait()21 22 23gh()24 25st.title("PDF Table Extractor")26st.subheader("for `Vara` Research GmbH")27 28st.image("https://www.vararesearch.de/wp-content/uploads/2020/03/vara-research-konsensus-management-consensus.png", width=200)29 30# file uploader on streamlit31 32input_pdf = st.file_uploader(label="upload your pdf here", type='pdf')33 34# Display only when a PDF is uploaded35 36#if input_pdf is not None:   37def show_pdf(file_path):38     with open(file_path,"rb") as f:39         base64_pdf = base64.b64encode(f.read()).decode('utf-8')40         pdf_display = f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="700" height="1000" type="application/pdf"></iframe>'41         st.markdown(pdf_display, unsafe_allow_html=True)42    43    44 # run this only when a PDF is uploaded45if input_pdf is not None:46    # byte object into a PDF file47    with open("input.pdf", "wb") as f:48        base64_pdf = base64.b64encode(input_pdf.read()).decode('utf-8')49       50        f.write(base64.b64decode(base64_pdf))51    f.close()52    show_pdf('input.pdf')53    54    st.markdown("### Page Number")55 56#page_number = st.text_input("Enter the page # from where you want to extract the PDF eg: 3", value=1)57    page_number = st.text_input("Enter the page # from where you want to extract the PDF eg: 3", value=2)58 59 60    # read the pdf and parse it using stream61    table = cam.read_pdf("input.pdf", pages=page_number, multiple_tables=True ,flavor ='stream', split_text=True, edge_tol=200) #,, edge_tol=50 , flavor ='stream',table_areas=['10, 740, 580, 10']62 63    st.markdown("### Number of Tables")64 65    # display the output after parsing66    st.write(table)67 68    # display the table69   70 71    if len(table) > 0:72        # extract the index value of the table.73 74        option = st.selectbox(label="Select the Table to be displayed", options=range(len(table) + 1))75 76        st.markdown('### Output Table')77        78        # Function that Covert the data into Excel 79        def to_excel(df):80            output = BytesIO()81            writer = pd.ExcelWriter(output, engine='xlsxwriter')82            df.to_excel(writer, index=False ,sheet_name='Sheet1')83            workbook = writer.book84            worksheet = writer.sheets['Sheet1']85            format1 = workbook.add_format({'num_format': '0.00'}) 86            worksheet.set_column('A:A', None, format1)  87            writer.save()88            processed_data = output.getvalue()89            return processed_data90            #print(option)91 92 93 94        # display the dataframe95    96        op_df = table[int(option) - 1].df97        st.dataframe(op_df)98        df_xlsx= to_excel(op_df)99 100 101        st.download_button("📁 Download csv File ⬇️",102                            op_df.to_csv(index= False), 103                            file_name='Output_Table.csv', 104                            mime = 'text/csv')105        st.download_button(label='📥 Download Excel File ⬇️',106                           data=df_xlsx ,107                           file_name= 'Output_Table.xlsx')                                                          108