LaurentTRIPIED's picture
Update app.py
82ac12d verified
raw
history blame
2.78 kB
###################################################
# Import des bibliothèques
###################################################
import streamlit as st
import PyPDF2
import json
import os
###################################################
# LES FONCTIONS DE CONVERSION PDF -> TEXTE -> JSON
###################################################
# Fonction pour extraire le texte du PDF
def extract_text_from_pdf(pdf_path):
text = []
with open(pdf_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
for i, page in enumerate(pdf_reader.pages):
text.append({"page": i + 1, "text": page.extract_text()})
return text
# Fonction pour sauvegarder le texte dans un fichier JSON
def save_text_to_json(data, output_file):
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
# Fonction pour afficher le contenu du fichier JSON
def display_json_contents(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
st.write(data)
except FileNotFoundError:
st.error(f"Le fichier {file_path} n'a pas été trouvé.")
###################################################
# INTERFACE
###################################################
# Interface Streamlit
st.title("Extracteur de Texte PDF et Sauvegarde en JSON")
# Chemin vers le fichier PDF et le fichier JSON de sortie
pdf_path = 'data/07-VF2_UDM_Oneframe_A4-2023.pdf'
json_output_path = 'data/extracted_text.json'
# Bouton pour lancer l'extraction et la sauvegarde
if st.button('Extraire le texte du PDF et sauvegarder en JSON'):
pdf_text = extract_text_from_pdf(pdf_path)
save_text_to_json(pdf_text, json_output_path)
st.success("Le texte a été extrait et sauvegardé.")
# Vérification de l'existence du fichier JSON et affichage du chemin absolu
if os.path.exists(json_output_path):
st.success(f"Le fichier {json_output_path} existe bien dans le répertoire data.")
st.write(f"Chemin absolu du fichier JSON : {os.path.abspath(json_output_path)}")
else:
st.error(f"Le fichier {json_output_path} n'a pas été trouvé dans le répertoire data.")
# Bouton pour afficher le contenu du fichier JSON
if st.button('Afficher le contenu JSON'):
display_json_contents(json_output_path)
# Option pour télécharger le fichier JSON
try:
with open(json_output_path, 'r', encoding='utf-8') as f:
download = st.download_button(
label="Télécharger le JSON",
data=f,
file_name="extracted_text.json",
mime="application/json"
)
except FileNotFoundError:
st.error(f"Le fichier {json_output_path} n'est pas disponible pour téléchargement.")