Spaces:
Paused
Paused
Download src/utils/file_reader.py from sam2009897/AstraWeave: direct link, hf CLI and curl.
- Browser
- Download file 847 Bytes
-
https://huggingface.co/spaces/sam2009897/AstraWeave/resolve/main/src/utils/file_reader.py
- Command line
-
hf download hf://spaces/sam2009897/AstraWeave/src/utils/file_reader.py
-
curl -L -o file_reader.py https://huggingface.co/spaces/sam2009897/AstraWeave/resolve/main/src/utils/file_reader.py
847 Bytes
| import os | |
| def read_file(path: str) -> str: | |
| if not os.path.isfile(path): | |
| return f"Error: file not found at {path}" | |
| ext = os.path.splitext(path)[1].lower() | |
| if ext in (".txt", ".csv", ".md", ".json", ".xml", ".yaml", ".yml"): | |
| with open(path, "r", encoding="utf-8", errors="replace") as f: | |
| return f.read() | |
| elif ext == ".pdf": | |
| return _read_pdf(path) | |
| elif ext in (".png", ".jpg", ".jpeg", ".gif", ".bmp"): | |
| return f"[Image file: {os.path.basename(path)}]" | |
| else: | |
| return f"[Unsupported file type: {ext}]" | |
| def _read_pdf(path: str) -> str: | |
| try: | |
| import pdfminer.high_level | |
| text = pdfminer.high_level.extract_text(path) | |
| return text if text.strip() else "[PDF: no extractable text]" | |
| except ImportError: | |
| return "[PDF reader not available]" | |