Spaces:
Sleeping
Sleeping
Create uploadFile.py
Browse files- uploadFile.py +54 -0
uploadFile.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import chardet
|
| 2 |
+
from fastapi import UploadFile, HTTPException
|
| 3 |
+
from io import BytesIO
|
| 4 |
+
from docx import Document
|
| 5 |
+
import fitz
|
| 6 |
+
|
| 7 |
+
async def file_to_text(file: UploadFile):
|
| 8 |
+
file_extension = file.filename.split('.')[-1].lower()
|
| 9 |
+
|
| 10 |
+
if file_extension == 'csv':
|
| 11 |
+
csv_data = await file.read()
|
| 12 |
+
encoding = chardet.detect(csv_data)['encoding']
|
| 13 |
+
try:
|
| 14 |
+
decoded_data = csv_data.decode(encoding)
|
| 15 |
+
return decoded_data
|
| 16 |
+
except UnicodeDecodeError:
|
| 17 |
+
raise HTTPException(status_code=400, detail="Le fichier CSV contient des caractères qui ne peuvent pas être décodés.")
|
| 18 |
+
|
| 19 |
+
# Fait
|
| 20 |
+
elif file_extension == 'json':
|
| 21 |
+
json_data = await file.read()
|
| 22 |
+
return json_data.decode()
|
| 23 |
+
|
| 24 |
+
# Fait
|
| 25 |
+
elif file_extension == 'docx':
|
| 26 |
+
doc_data = await file.read()
|
| 27 |
+
# Utilisez un flux mémoire pour passer les données au Document
|
| 28 |
+
doc_stream = BytesIO(doc_data)
|
| 29 |
+
doc = Document(doc_stream)
|
| 30 |
+
doc_text = [paragraph.text for paragraph in doc.paragraphs]
|
| 31 |
+
return '\n'.join(doc_text)
|
| 32 |
+
|
| 33 |
+
# Fait
|
| 34 |
+
elif file_extension == 'txt':
|
| 35 |
+
txt_data = await file.read()
|
| 36 |
+
return txt_data.decode()
|
| 37 |
+
|
| 38 |
+
# Fait
|
| 39 |
+
elif file_extension == 'pdf':
|
| 40 |
+
try:
|
| 41 |
+
pdf_data = await file.read()
|
| 42 |
+
# Chargez les données binaires dans un objet fitz.Document
|
| 43 |
+
pdf_document = fitz.open("pdf", pdf_data)
|
| 44 |
+
text = ''
|
| 45 |
+
# Extrait le texte de chaque page
|
| 46 |
+
for page in pdf_document:
|
| 47 |
+
text += page.get_text()
|
| 48 |
+
pdf_document.close()
|
| 49 |
+
return text
|
| 50 |
+
except Exception as e:
|
| 51 |
+
raise HTTPException(status_code=500, detail=f"Erreur de lecture du fichier PDF : {e}")
|
| 52 |
+
|
| 53 |
+
else:
|
| 54 |
+
return HTTPException(status_code=400, detail="Format de fichier non pris en charge")
|