|
|
|
|
|
""" |
|
|
Fetch Ancient Legal Document Images and Texts |
|
|
|
|
|
Sources: |
|
|
- Wikimedia Commons (public domain images) |
|
|
- Yale Avalon Project (translations) |
|
|
- Internet Archive (scans) |
|
|
- Museum APIs (Louvre, British Museum, etc.) |
|
|
""" |
|
|
|
|
|
import os |
|
|
import json |
|
|
import requests |
|
|
import time |
|
|
from pathlib import Path |
|
|
from typing import Dict, List, Optional |
|
|
from dataclasses import dataclass, asdict |
|
|
from urllib.parse import urljoin |
|
|
import logging |
|
|
|
|
|
logging.basicConfig(level=logging.INFO, format='%(asctime)s | %(message)s') |
|
|
logger = logging.getLogger(__name__) |
|
|
|
|
|
|
|
|
BASE_DIR = Path(__file__).parent |
|
|
IMAGES_DIR = BASE_DIR / "images" |
|
|
TRANSCRIPTIONS_DIR = BASE_DIR / "transcriptions" |
|
|
TRANSLATIONS_DIR = BASE_DIR / "translations" |
|
|
|
|
|
|
|
|
IMAGES_DIR.mkdir(exist_ok=True) |
|
|
TRANSCRIPTIONS_DIR.mkdir(exist_ok=True) |
|
|
TRANSLATIONS_DIR.mkdir(exist_ok=True) |
|
|
|
|
|
|
|
|
@dataclass |
|
|
class AncientDocument: |
|
|
"""Metadata for an ancient legal document""" |
|
|
id: str |
|
|
title: str |
|
|
alternate_titles: List[str] |
|
|
date_composed: str |
|
|
language_original: str |
|
|
script: str |
|
|
physical_location: str |
|
|
image_sources: List[Dict[str, str]] |
|
|
translation_sources: List[Dict[str, str]] |
|
|
provisions_count: Optional[int] = None |
|
|
topics: List[str] = None |
|
|
significance: str = "" |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ANCIENT_DOCUMENTS = [ |
|
|
AncientDocument( |
|
|
id="hammurabi", |
|
|
title="Code of Hammurabi", |
|
|
alternate_titles=["Codex Hammurabi", "Laws of Hammurabi"], |
|
|
date_composed="-1754", |
|
|
language_original="akk", |
|
|
script="cuneiform", |
|
|
physical_location="Louvre Museum, Paris", |
|
|
provisions_count=282, |
|
|
topics=["property", "family", "commerce", "crime", "slavery", "wages"], |
|
|
significance="One of the oldest deciphered writings of significant length in the world", |
|
|
image_sources=[ |
|
|
{ |
|
|
"url": "https://upload.wikimedia.org/wikipedia/commons/6/64/Milkau_Oberer_Teil_der_Stele_mit_dem_Text_von_Hammurapis_Gesetzescode_369-2.jpg", |
|
|
"description": "Full stele showing Hammurabi receiving laws from Shamash" |
|
|
}, |
|
|
{ |
|
|
"url": "https://upload.wikimedia.org/wikipedia/commons/a/a7/Code_de_Hammurabi_1.jpg", |
|
|
"description": "Upper portion detail" |
|
|
}, |
|
|
{ |
|
|
"url": "https://upload.wikimedia.org/wikipedia/commons/e/e3/P1050771_Louvre_code_Hammurabi_face_rwk.JPG", |
|
|
"description": "Front face with cuneiform text" |
|
|
}, |
|
|
], |
|
|
translation_sources=[ |
|
|
{"url": "https://avalon.law.yale.edu/ancient/hamframe.asp", "language": "en"}, |
|
|
] |
|
|
), |
|
|
AncientDocument( |
|
|
id="ur_nammu", |
|
|
title="Code of Ur-Nammu", |
|
|
alternate_titles=["Laws of Ur-Nammu"], |
|
|
date_composed="-2100", |
|
|
language_original="sux", |
|
|
script="cuneiform", |
|
|
physical_location="Istanbul Archaeological Museums / University of Pennsylvania", |
|
|
provisions_count=57, |
|
|
topics=["murder", "robbery", "adultery", "injury", "slavery"], |
|
|
significance="Oldest known law code, predates Hammurabi by 300 years", |
|
|
image_sources=[ |
|
|
{ |
|
|
"url": "https://upload.wikimedia.org/wikipedia/commons/5/5e/Code_of_Ur-Nammu_%28Istanbul%29.jpg", |
|
|
"description": "Ur-Nammu tablet" |
|
|
}, |
|
|
], |
|
|
translation_sources=[ |
|
|
{"url": "https://www.ancient.eu/article/1000/the-ur-nammu-law-code/", "language": "en"}, |
|
|
] |
|
|
), |
|
|
AncientDocument( |
|
|
id="eshnunna", |
|
|
title="Laws of Eshnunna", |
|
|
alternate_titles=["Codex Eshnunna"], |
|
|
date_composed="-1930", |
|
|
language_original="akk", |
|
|
script="cuneiform", |
|
|
physical_location="Iraq Museum, Baghdad", |
|
|
provisions_count=60, |
|
|
topics=["prices", "wages", "family", "property", "slavery"], |
|
|
significance="Predates Hammurabi, shows Akkadian legal tradition", |
|
|
image_sources=[ |
|
|
{ |
|
|
"url": "https://upload.wikimedia.org/wikipedia/commons/8/8a/Law_tablet_Eshnunna_Louvre_AO6676.jpg", |
|
|
"description": "Eshnunna law tablet" |
|
|
}, |
|
|
], |
|
|
translation_sources=[] |
|
|
), |
|
|
AncientDocument( |
|
|
id="twelve_tables", |
|
|
title="Twelve Tables", |
|
|
alternate_titles=["Law of the Twelve Tables", "Lex Duodecim Tabularum"], |
|
|
date_composed="-450", |
|
|
language_original="la", |
|
|
script="latin", |
|
|
physical_location="Original destroyed; reconstructed from citations", |
|
|
provisions_count=100, |
|
|
topics=["procedure", "family", "property", "inheritance", "crime"], |
|
|
significance="Foundation of Roman law, basis of Western legal tradition", |
|
|
image_sources=[ |
|
|
{ |
|
|
"url": "https://upload.wikimedia.org/wikipedia/commons/0/0b/Twelve_Tables.jpg", |
|
|
"description": "Artistic reconstruction" |
|
|
}, |
|
|
], |
|
|
translation_sources=[ |
|
|
{"url": "https://avalon.law.yale.edu/ancient/twelve_tables.asp", "language": "en"}, |
|
|
] |
|
|
), |
|
|
AncientDocument( |
|
|
id="magna_carta", |
|
|
title="Magna Carta", |
|
|
alternate_titles=["Great Charter", "Magna Carta Libertatum"], |
|
|
date_composed="1215", |
|
|
language_original="la", |
|
|
script="latin", |
|
|
physical_location="British Library / Salisbury Cathedral / Lincoln Castle", |
|
|
provisions_count=63, |
|
|
topics=["rights", "justice", "taxation", "church", "feudal"], |
|
|
significance="Foundation of constitutional law and individual rights", |
|
|
image_sources=[ |
|
|
{ |
|
|
"url": "https://upload.wikimedia.org/wikipedia/commons/e/ee/Magna_Carta_%28British_Library_Cotton_MS_Augustus_II.106%29.jpg", |
|
|
"description": "British Library copy (Cotton MS Augustus II.106)" |
|
|
}, |
|
|
{ |
|
|
"url": "https://upload.wikimedia.org/wikipedia/commons/0/06/Magna_Carta_%28An_Emblematic_Picture%29.jpg", |
|
|
"description": "Emblematic picture" |
|
|
}, |
|
|
], |
|
|
translation_sources=[ |
|
|
{"url": "https://avalon.law.yale.edu/medieval/magframe.asp", "language": "en"}, |
|
|
] |
|
|
), |
|
|
AncientDocument( |
|
|
id="draco", |
|
|
title="Draconian Constitution", |
|
|
alternate_titles=["Laws of Draco", "Draco's Code"], |
|
|
date_composed="-621", |
|
|
language_original="grc", |
|
|
script="greek", |
|
|
physical_location="Lost; known only from later sources", |
|
|
topics=["homicide", "punishment", "debt"], |
|
|
significance="First written Athenian laws; notoriously harsh", |
|
|
image_sources=[], |
|
|
translation_sources=[] |
|
|
), |
|
|
AncientDocument( |
|
|
id="solon", |
|
|
title="Laws of Solon", |
|
|
alternate_titles=["Solonian Constitution"], |
|
|
date_composed="-594", |
|
|
language_original="grc", |
|
|
script="greek", |
|
|
physical_location="Lost; known from citations", |
|
|
topics=["debt", "citizenship", "courts", "assembly"], |
|
|
significance="Reformed Draconian laws; foundation of Athenian democracy", |
|
|
image_sources=[], |
|
|
translation_sources=[] |
|
|
), |
|
|
AncientDocument( |
|
|
id="hittite_laws", |
|
|
title="Hittite Laws", |
|
|
alternate_titles=["Code of the Nesilim"], |
|
|
date_composed="-1650", |
|
|
language_original="hit", |
|
|
script="cuneiform", |
|
|
physical_location="Various museums", |
|
|
provisions_count=200, |
|
|
topics=["homicide", "theft", "marriage", "land", "animals"], |
|
|
significance="Shows legal diversity in ancient Near East", |
|
|
image_sources=[ |
|
|
{ |
|
|
"url": "https://upload.wikimedia.org/wikipedia/commons/8/8a/Hittite_law_code.jpg", |
|
|
"description": "Hittite law tablet" |
|
|
}, |
|
|
], |
|
|
translation_sources=[] |
|
|
), |
|
|
AncientDocument( |
|
|
id="manu", |
|
|
title="Laws of Manu", |
|
|
alternate_titles=["Manusmriti", "Manava-Dharmasastra"], |
|
|
date_composed="-200", |
|
|
language_original="sa", |
|
|
script="devanagari", |
|
|
physical_location="Various manuscripts", |
|
|
provisions_count=2685, |
|
|
topics=["dharma", "caste", "ritual", "kingship", "punishment"], |
|
|
significance="Foundational Hindu legal text", |
|
|
image_sources=[ |
|
|
{ |
|
|
"url": "https://upload.wikimedia.org/wikipedia/commons/d/d6/Manusmriti.jpg", |
|
|
"description": "Manusmriti manuscript page" |
|
|
}, |
|
|
], |
|
|
translation_sources=[ |
|
|
{"url": "https://www.sacred-texts.com/hin/manu.htm", "language": "en"}, |
|
|
] |
|
|
), |
|
|
AncientDocument( |
|
|
id="justinian_digest", |
|
|
title="Digest of Justinian", |
|
|
alternate_titles=["Pandects", "Digesta"], |
|
|
date_composed="533", |
|
|
language_original="la", |
|
|
script="latin", |
|
|
physical_location="Various manuscripts", |
|
|
provisions_count=9000, |
|
|
topics=["persons", "property", "obligations", "succession", "procedure"], |
|
|
significance="Compilation of Roman legal writings; basis of civil law", |
|
|
image_sources=[ |
|
|
{ |
|
|
"url": "https://upload.wikimedia.org/wikipedia/commons/8/8f/Corpus_Iuris_Civilis_02.jpg", |
|
|
"description": "Medieval manuscript" |
|
|
}, |
|
|
], |
|
|
translation_sources=[] |
|
|
), |
|
|
] |
|
|
|
|
|
|
|
|
def download_image(url: str, save_path: Path, description: str = "") -> bool: |
|
|
"""Download an image from URL""" |
|
|
try: |
|
|
headers = {"User-Agent": "Mozilla/5.0 (research bot - ancient document collection)"} |
|
|
response = requests.get(url, headers=headers, timeout=60, stream=True) |
|
|
response.raise_for_status() |
|
|
|
|
|
with open(save_path, 'wb') as f: |
|
|
for chunk in response.iter_content(chunk_size=8192): |
|
|
f.write(chunk) |
|
|
|
|
|
logger.info(f" Downloaded: {save_path.name} ({description})") |
|
|
return True |
|
|
|
|
|
except Exception as e: |
|
|
logger.error(f" Failed to download {url}: {e}") |
|
|
return False |
|
|
|
|
|
|
|
|
def fetch_avalon_translation(url: str, save_path: Path) -> bool: |
|
|
"""Fetch translation from Yale Avalon Project""" |
|
|
try: |
|
|
from bs4 import BeautifulSoup |
|
|
|
|
|
headers = {"User-Agent": "Mozilla/5.0 (research bot)"} |
|
|
response = requests.get(url, headers=headers, timeout=30) |
|
|
response.raise_for_status() |
|
|
|
|
|
soup = BeautifulSoup(response.content, 'html.parser') |
|
|
|
|
|
|
|
|
content = soup.find('div', class_='document-content') |
|
|
if not content: |
|
|
content = soup.find('body') |
|
|
|
|
|
if content: |
|
|
text = content.get_text(separator='\n', strip=True) |
|
|
with open(save_path, 'w', encoding='utf-8') as f: |
|
|
f.write(text) |
|
|
logger.info(f" Saved translation: {save_path.name}") |
|
|
return True |
|
|
|
|
|
except Exception as e: |
|
|
logger.error(f" Failed to fetch translation from {url}: {e}") |
|
|
|
|
|
return False |
|
|
|
|
|
|
|
|
def fetch_document(doc: AncientDocument) -> Dict: |
|
|
"""Fetch all available resources for a document""" |
|
|
logger.info(f"\n{'='*60}") |
|
|
logger.info(f"Fetching: {doc.title} ({doc.date_composed})") |
|
|
logger.info(f"{'='*60}") |
|
|
|
|
|
result = { |
|
|
"id": doc.id, |
|
|
"title": doc.title, |
|
|
"images_downloaded": [], |
|
|
"translations_downloaded": [], |
|
|
"errors": [] |
|
|
} |
|
|
|
|
|
|
|
|
doc_images_dir = IMAGES_DIR / doc.id |
|
|
doc_images_dir.mkdir(exist_ok=True) |
|
|
|
|
|
|
|
|
for i, img_source in enumerate(doc.image_sources): |
|
|
url = img_source["url"] |
|
|
ext = url.split('.')[-1].split('?')[0][:4] |
|
|
if ext not in ['jpg', 'jpeg', 'png', 'gif', 'tif', 'tiff']: |
|
|
ext = 'jpg' |
|
|
|
|
|
filename = f"{doc.id}_{i+1:02d}.{ext}" |
|
|
save_path = doc_images_dir / filename |
|
|
|
|
|
if save_path.exists(): |
|
|
logger.info(f" Already exists: {filename}") |
|
|
result["images_downloaded"].append(filename) |
|
|
elif download_image(url, save_path, img_source.get("description", "")): |
|
|
result["images_downloaded"].append(filename) |
|
|
else: |
|
|
result["errors"].append(f"Failed: {url}") |
|
|
|
|
|
time.sleep(1) |
|
|
|
|
|
|
|
|
for trans_source in doc.translation_sources: |
|
|
url = trans_source["url"] |
|
|
lang = trans_source["language"] |
|
|
|
|
|
filename = f"{doc.id}_{lang}.txt" |
|
|
save_path = TRANSLATIONS_DIR / filename |
|
|
|
|
|
if save_path.exists(): |
|
|
logger.info(f" Already exists: {filename}") |
|
|
result["translations_downloaded"].append(filename) |
|
|
elif "avalon" in url: |
|
|
if fetch_avalon_translation(url, save_path): |
|
|
result["translations_downloaded"].append(filename) |
|
|
|
|
|
time.sleep(1) |
|
|
|
|
|
return result |
|
|
|
|
|
|
|
|
def save_metadata(): |
|
|
"""Save document metadata to JSON""" |
|
|
metadata = { |
|
|
"dataset": "ancient-law", |
|
|
"version": "1.0.0", |
|
|
"documents": [asdict(doc) for doc in ANCIENT_DOCUMENTS] |
|
|
} |
|
|
|
|
|
metadata_path = BASE_DIR / "metadata.json" |
|
|
with open(metadata_path, 'w', encoding='utf-8') as f: |
|
|
json.dump(metadata, f, indent=2, ensure_ascii=False) |
|
|
|
|
|
logger.info(f"\nSaved metadata to {metadata_path}") |
|
|
|
|
|
|
|
|
def main(): |
|
|
"""Run the fetch process""" |
|
|
print("=" * 70) |
|
|
print("ANCIENT LAW DOCUMENT FETCHER") |
|
|
print("Collecting document images and translations for HuggingFace") |
|
|
print("=" * 70) |
|
|
|
|
|
results = [] |
|
|
|
|
|
for doc in ANCIENT_DOCUMENTS: |
|
|
result = fetch_document(doc) |
|
|
results.append(result) |
|
|
|
|
|
|
|
|
save_metadata() |
|
|
|
|
|
|
|
|
print("\n" + "=" * 70) |
|
|
print("FETCH COMPLETE") |
|
|
print("=" * 70) |
|
|
|
|
|
total_images = sum(len(r["images_downloaded"]) for r in results) |
|
|
total_translations = sum(len(r["translations_downloaded"]) for r in results) |
|
|
total_errors = sum(len(r["errors"]) for r in results) |
|
|
|
|
|
print(f"Documents processed: {len(results)}") |
|
|
print(f"Images downloaded: {total_images}") |
|
|
print(f"Translations saved: {total_translations}") |
|
|
print(f"Errors: {total_errors}") |
|
|
|
|
|
return results |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
main() |
|
|
|