Spaces:
Sleeping
Sleeping
Upload src/ingest.py with huggingface_hub
Browse files- src/ingest.py +58 -0
src/ingest.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Download public-domain text (Iliad or Dorian Gray) into data/raw/.
|
| 3 |
+
"""
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import requests
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def download_book(book: str, out_dir: str, url: str = None) -> str:
|
| 9 |
+
"""
|
| 10 |
+
Download the requested book and return local file path.
|
| 11 |
+
|
| 12 |
+
Args:
|
| 13 |
+
book: Book name ('iliad' or 'dorian')
|
| 14 |
+
out_dir: Output directory path (can be relative or absolute)
|
| 15 |
+
url: Optional URL to override default. If None, uses default Project Gutenberg URLs.
|
| 16 |
+
|
| 17 |
+
Returns:
|
| 18 |
+
str: Path to the downloaded file.
|
| 19 |
+
|
| 20 |
+
# TODO hints:
|
| 21 |
+
# - Use HTTP GET to a stable Project Gutenberg URL for the plain text.
|
| 22 |
+
# - Save as UTF-8 in data/raw/{book}.txt.
|
| 23 |
+
# - Handle re-run: skip if file exists.
|
| 24 |
+
|
| 25 |
+
# Acceptance:
|
| 26 |
+
# - Returns a str path to the downloaded file.
|
| 27 |
+
"""
|
| 28 |
+
# Map book names to their Project Gutenberg URLs
|
| 29 |
+
book_urls = {
|
| 30 |
+
"iliad": "https://www.gutenberg.org/files/6130/6130-0.txt",
|
| 31 |
+
"dorian": "https://www.gutenberg.org/files/174/174-0.txt"
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
# Use provided URL or default
|
| 35 |
+
if url is None:
|
| 36 |
+
url = book_urls.get(book)
|
| 37 |
+
if not url:
|
| 38 |
+
raise ValueError(f"Unknown book: {book}. Must be 'iliad' or 'dorian'.")
|
| 39 |
+
|
| 40 |
+
# Resolve output path (handles relative paths correctly)
|
| 41 |
+
out_path = Path(out_dir).resolve() / f"{book}.txt"
|
| 42 |
+
|
| 43 |
+
# Skip if file already exists
|
| 44 |
+
if out_path.exists():
|
| 45 |
+
print(f"File already exists: {out_path}")
|
| 46 |
+
return str(out_path)
|
| 47 |
+
|
| 48 |
+
# Download the book
|
| 49 |
+
print(f"Downloading {book} from {url}...")
|
| 50 |
+
response = requests.get(url, timeout=30)
|
| 51 |
+
response.raise_for_status()
|
| 52 |
+
|
| 53 |
+
# Save to file
|
| 54 |
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
| 55 |
+
out_path.write_text(response.text, encoding="utf-8")
|
| 56 |
+
print(f"Saved to: {out_path}")
|
| 57 |
+
|
| 58 |
+
return str(out_path)
|