Spaces:
Sleeping
Sleeping
Create utils.py
Browse files- pipelines/utils.py +26 -0
pipelines/utils.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import docx
|
| 3 |
+
|
| 4 |
+
def detect_filetype(filename: str, file_bytes: bytes) -> str:
|
| 5 |
+
fname = (filename or "").lower()
|
| 6 |
+
if fname.endswith(".pdf"):
|
| 7 |
+
return "pdf"
|
| 8 |
+
if any(fname.endswith(ext) for ext in [".png", ".jpg", ".jpeg", ".tiff", ".bmp"]):
|
| 9 |
+
return "image"
|
| 10 |
+
if fname.endswith(".docx"):
|
| 11 |
+
return "docx"
|
| 12 |
+
if fname.endswith(".txt"):
|
| 13 |
+
return "txt"
|
| 14 |
+
if file_bytes[:4] == b"%PDF":
|
| 15 |
+
return "pdf"
|
| 16 |
+
return "unknown"
|
| 17 |
+
|
| 18 |
+
def load_doc_text(filetype: str, file_bytes: bytes) -> str:
|
| 19 |
+
if filetype == "docx":
|
| 20 |
+
f = io.BytesIO(file_bytes)
|
| 21 |
+
doc = docx.Document(f)
|
| 22 |
+
return "\n".join([p.text for p in doc.paragraphs])
|
| 23 |
+
elif filetype == "txt":
|
| 24 |
+
return file_bytes.decode("utf-8", errors="ignore")
|
| 25 |
+
else:
|
| 26 |
+
return ""
|