Spaces:
Sleeping
Sleeping
Ajout de ppt et pptx
Browse files
main.py
CHANGED
@@ -16,7 +16,6 @@ import asyncio # Added for asynchronous functionality
|
|
16 |
from openai import AsyncOpenAI # Import AsyncOpenAI
|
17 |
from readability import Document
|
18 |
|
19 |
-
|
20 |
import instructor # Import instructor for patching
|
21 |
|
22 |
from fastapi import FastAPI, File, UploadFile, HTTPException, BackgroundTasks
|
@@ -25,6 +24,19 @@ import pypandoc
|
|
25 |
import fitz # PyMuPDF
|
26 |
from bs4 import BeautifulSoup, Comment
|
27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
# Initialize the logger
|
29 |
logging.basicConfig(level=logging.DEBUG)
|
30 |
|
@@ -57,7 +69,9 @@ FORMAT_MAP = {
|
|
57 |
'.commonmark': 'commonmark',
|
58 |
'.cm': 'commonmark',
|
59 |
'.wiki': 'mediawiki',
|
60 |
-
'.opml': 'opml'
|
|
|
|
|
61 |
}
|
62 |
|
63 |
def get_pandoc_format(extension: str) -> str:
|
@@ -848,10 +862,11 @@ async def convert_file_to_txt(
|
|
848 |
base_filename, ext = os.path.splitext(original_filename)
|
849 |
ext = ext.lower()
|
850 |
|
851 |
-
#
|
852 |
allowed_extensions = [
|
853 |
'.odt', '.pdf', '.docx', '.html', '.htm', '.md', '.txt', '.rtf', '.epub',
|
854 |
-
'.tex', '.xml', '.org', '.commonmark', '.cm', '.wiki', '.opml'
|
|
|
855 |
]
|
856 |
|
857 |
if ext not in allowed_extensions:
|
@@ -878,8 +893,9 @@ async def convert_file_to_txt(
|
|
878 |
unique_id = uuid.uuid4().hex
|
879 |
output_filename = os.path.join(tempfile.gettempdir(), f"{base_filename}_{unique_id}.txt")
|
880 |
|
881 |
-
# Conversion
|
882 |
if ext == '.pdf':
|
|
|
883 |
text = ""
|
884 |
with fitz.open(input_filename) as doc:
|
885 |
for page in doc:
|
@@ -888,16 +904,32 @@ async def convert_file_to_txt(
|
|
888 |
f.write(text)
|
889 |
logging.debug(f"Conversion PDF réussie avec PyMuPDF : {output_filename}")
|
890 |
|
891 |
-
|
892 |
-
|
893 |
-
|
894 |
-
|
895 |
-
|
896 |
-
|
897 |
-
|
898 |
-
|
899 |
-
|
|
|
|
|
|
|
|
|
|
|
900 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
901 |
output = pypandoc.convert_file(input_filename, 'plain', outputfile=output_filename)
|
902 |
logging.debug(f"Conversion réussie avec Pandoc : {output_filename}")
|
903 |
|
@@ -907,7 +939,6 @@ async def convert_file_to_txt(
|
|
907 |
raise HTTPException(status_code=500, detail="Erreur lors de la conversion.")
|
908 |
|
909 |
# Ajouter les fichiers temporaires à la tâche d'arrière-plan pour suppression après l'envoi de la réponse
|
910 |
-
# Inclure le fichier nettoyé s'il existe
|
911 |
temp_files_to_delete = [input_filename, output_filename]
|
912 |
if ext in ['.html', '.htm']:
|
913 |
temp_files_to_delete.append(cleaned_input_filename)
|
|
|
16 |
from openai import AsyncOpenAI # Import AsyncOpenAI
|
17 |
from readability import Document
|
18 |
|
|
|
19 |
import instructor # Import instructor for patching
|
20 |
|
21 |
from fastapi import FastAPI, File, UploadFile, HTTPException, BackgroundTasks
|
|
|
24 |
import fitz # PyMuPDF
|
25 |
from bs4 import BeautifulSoup, Comment
|
26 |
|
27 |
+
# Ajout des bibliothèques pour PPTX et PPT
|
28 |
+
try:
|
29 |
+
from pptx import Presentation
|
30 |
+
except ImportError:
|
31 |
+
# Si python-pptx n'est pas installé, vous pouvez l'installer via pip install python-pptx
|
32 |
+
pass
|
33 |
+
|
34 |
+
try:
|
35 |
+
import textract
|
36 |
+
except ImportError:
|
37 |
+
# Si textract n'est pas installé, vous pouvez l'installer via pip install textract
|
38 |
+
pass
|
39 |
+
|
40 |
# Initialize the logger
|
41 |
logging.basicConfig(level=logging.DEBUG)
|
42 |
|
|
|
69 |
'.commonmark': 'commonmark',
|
70 |
'.cm': 'commonmark',
|
71 |
'.wiki': 'mediawiki',
|
72 |
+
'.opml': 'opml',
|
73 |
+
# On n'ajoute pas ici ppt et pptx, car pandoc ne gère pas directement ces formats.
|
74 |
+
# On les traitera séparément.
|
75 |
}
|
76 |
|
77 |
def get_pandoc_format(extension: str) -> str:
|
|
|
862 |
base_filename, ext = os.path.splitext(original_filename)
|
863 |
ext = ext.lower()
|
864 |
|
865 |
+
# On ajoute .ppt et .pptx aux extensions autorisées
|
866 |
allowed_extensions = [
|
867 |
'.odt', '.pdf', '.docx', '.html', '.htm', '.md', '.txt', '.rtf', '.epub',
|
868 |
+
'.tex', '.xml', '.org', '.commonmark', '.cm', '.wiki', '.opml',
|
869 |
+
'.ppt', '.pptx' # Ajout de PPT et PPTX
|
870 |
]
|
871 |
|
872 |
if ext not in allowed_extensions:
|
|
|
893 |
unique_id = uuid.uuid4().hex
|
894 |
output_filename = os.path.join(tempfile.gettempdir(), f"{base_filename}_{unique_id}.txt")
|
895 |
|
896 |
+
# Conversion des différents formats
|
897 |
if ext == '.pdf':
|
898 |
+
# Conversion PDF en texte avec PyMuPDF
|
899 |
text = ""
|
900 |
with fitz.open(input_filename) as doc:
|
901 |
for page in doc:
|
|
|
904 |
f.write(text)
|
905 |
logging.debug(f"Conversion PDF réussie avec PyMuPDF : {output_filename}")
|
906 |
|
907 |
+
elif ext == '.pptx':
|
908 |
+
# Conversion PPTX en texte avec python-pptx
|
909 |
+
if 'Presentation' not in globals():
|
910 |
+
raise HTTPException(status_code=500, detail="La librairie python-pptx n'est pas installée.")
|
911 |
+
prs = Presentation(input_filename)
|
912 |
+
text_content = []
|
913 |
+
for slide in prs.slides:
|
914 |
+
for shape in slide.shapes:
|
915 |
+
if hasattr(shape, "text"):
|
916 |
+
text_content.append(shape.text)
|
917 |
+
text = "\n".join(text_content)
|
918 |
+
with open(output_filename, "w", encoding="utf-8") as f:
|
919 |
+
f.write(text)
|
920 |
+
logging.debug(f"Conversion PPTX réussie avec python-pptx : {output_filename}")
|
921 |
|
922 |
+
elif ext == '.ppt':
|
923 |
+
# Conversion PPT en texte avec textract (nécessite les dépendances de textract)
|
924 |
+
if 'textract' not in globals():
|
925 |
+
raise HTTPException(status_code=500, detail="La librairie textract n'est pas installée.")
|
926 |
+
text = textract.process(input_filename).decode('utf-8', errors='replace')
|
927 |
+
with open(output_filename, "w", encoding="utf-8") as f:
|
928 |
+
f.write(text)
|
929 |
+
logging.debug(f"Conversion PPT réussie avec textract : {output_filename}")
|
930 |
+
|
931 |
+
else:
|
932 |
+
# Conversion des autres formats en texte avec Pandoc
|
933 |
output = pypandoc.convert_file(input_filename, 'plain', outputfile=output_filename)
|
934 |
logging.debug(f"Conversion réussie avec Pandoc : {output_filename}")
|
935 |
|
|
|
939 |
raise HTTPException(status_code=500, detail="Erreur lors de la conversion.")
|
940 |
|
941 |
# Ajouter les fichiers temporaires à la tâche d'arrière-plan pour suppression après l'envoi de la réponse
|
|
|
942 |
temp_files_to_delete = [input_filename, output_filename]
|
943 |
if ext in ['.html', '.htm']:
|
944 |
temp_files_to_delete.append(cleaned_input_filename)
|