demo setup (#1)
Browse files- demo setup (89834caddc84c9dca5d3e00720d599c967a1c3bd)
- ignore .json (fbdf4a4b404070876f8688c3cab7706168e30d30)
- removed .json (5df33cc7fb6dae275a63a981824b0d48b0b98f84)
Files changed (12)
- data/.gitignoreAdded+1
- data/1750/data-00000-of-00003.arrowAdded+3
- data/1750/data-00001-of-00003.arrowAdded+3
- data/1750/data-00002-of-00003.arrowAdded+3
- extract_data.pyAdded+477
- log/extract.logAdded+219
- log/problems_1919-1919.txtAdded+68
- pd_check/public_domain_data.parquetAdded+3
- pd_check/public_domain_files.txtAdded
- pd_check/select_pd.pyAdded+523
- scrape/da_people_large.parquetAdded+3
- scrape/scrape_large.pyAdded+306
1*.json123version https://git-lfs.github.com/spec/v1oid sha256:f00dc4c008c64560993420d2f4fc4e6ba78cb07f6989f85b3c0d190605028578size 4017191736123version https://git-lfs.github.com/spec/v1oid sha256:e2b06cc594e0c025a8bcfe8b68a61613e8e5032c5fb344280a06841538ef6699size 4354003752123version https://git-lfs.github.com/spec/v1oid sha256:ca0a355fc755b832b87f195ced311e69f72df1e4c5f39afa804a817e2fc95bebsize 2700984360123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477import osimport reimport stringimport jsonimport loggingimport shutilfrom datetime import datetimefrom tqdm import tqdm
import fitzfrom datasets import Dataset, load_datasetlogger = logging.getLogger(__name__)################################################ FILL MANUALLY ######################name of parquet filessource = "kb_books"#how many years should go in one parquet file (do not change!)n_chunks = 1#how many docs in 1 parquetn_batch = 5#pathsinput_path = os.path.join("..","..","kb-books","raw")output_path = os.path.join(".","data")logs = os.path.join(".","log")#first year to processstart_year = 1751#last year to processstop_year = 1752#misc folders in dataunwanted_folders = ("README.txt","logs")#demo run for testing, if true, only first page is readdemo = False#location of reference filenames for public domain documentsref_pd_location = os.path.join(".","pd_check","public_domain_files.txt")with open(ref_pd_location, 'r') as pd_files: ref_pd_list = pd_files.read().splitlines()############################################def find_author_json(data: dict[str,dict[str,dict[str,str]]]) -> str: """ A function for finding the author(s) from various possible locations in the json metadata. """ try: author = data.get("pnx").get("addata")["au"] except KeyError: author = [] try: add_author = data.get("pnx").get("addata")["addau"] except KeyError: add_author = []
authors = list(set(author)) + list(set(add_author)) authors = "; ".join(authors)
if len(authors) < 1: try: authors = data.get("pnx").get("sort")["author"] authors = "; ".join(authors) except KeyError: pass if len(authors) < 1: try: authors = data.get("pnx").get("display")["creator"] authors = "; ".join(authors) except KeyError: authors = "missing"
return (authors)
def find_title_json(data: dict[str,dict[str,dict[str,str]]]) -> str: """ A function for finding the title from various possible locations in the json metadata. """ try: title = data.get("pnx").get("display")["title"][0] except KeyError: title = [] if len(title) < 1: try: title = data.get("pnx").get("addata")["btitle"][0] except KeyError: pass else: pass if len(title) < 1: try: title = data.get("pnx").get("sort")["title"][0] except KeyError: pass if len(title) < 1: title = "missing" return(title)
def find_digitalization(data: dict[str,dict[str,dict[str,str]]]) -> str: """ A function for finding the digitalization date from various possible locations in the json metadata. """ try: digit = data.get("pnx").get("display")["creationdate"][0] #last 4 digit number in string digit = re.findall(r"\d{4}$",digit)[0] except KeyError: digit = [] if len(digit) < 1: try: digit = data.get("pnx").get("addata")["date"][1] digit = re.findall(r"\d{4}$",digit)[0] except KeyError: digit = "missing" return(digit)
def find_source(data: dict[str,dict[str,dict[str,str]]]) -> str: """ A function for finding source of the document from the json metadata. """ try: doc_source = data.get("pnx").get("display")["lds50"] #last 4 digit number in string doc_source = [i for i in doc_source if "Digi" not in i][0] except (KeyError, IndexError): doc_source = "missing" return doc_source
#filter alive and missing peopledef dead_70_yrs_ago(ds): """filter for the scraped authors to find ones who have died 70 years ago""" birth_miss = False death_miss = False try: birth_yr = int(ds["born"]) if birth_yr > 1955: birth = False else: birth = True except ValueError: birth = False birth_miss = True
try: death_yr = int(ds["died"]) if death_yr > 1955: death = False else: death = True except ValueError: death = False death_miss = True
if ((death and birth) or (death and birth_miss) or (death_miss and birth_yr < 1833) ): filtered = True else: filtered = False
return filtered
def extract_meta_data(pdf_file:str) -> dict[str,str|int]: """ A function for extracting meta data from the json files includes: - author(s) - title - published - digitalized - source """ try: #load in json json_file = pdf_file[:-3] + "json" f = open(json_file) data = json.load(f) #do stuff authors = find_author_json(data) title = find_title_json(data) digitalized = find_digitalization(data) doc_source = find_source(data) #close f.close() except BaseException: authors = "missing" title = "missing" digitalized = "missing" doc_source = "missing" return authors, title, digitalized, doc_source
def simplify_name(author:str) -> str: """ function for simplifying repeated single author name separated by ; eg. "Holck, J.; af J. Holck." -> Holck, J. """ simp = author if ";" in author: only_uppercase = [re.findall(r"[A-Z][a-z]*",i) for i in author.split(";")] if len(only_uppercase)==2: if sorted(only_uppercase[0]) == sorted(only_uppercase[1]): simp = re.findall(r"^[^;]*",author)[0] else: pass else: pass else: pass return simp
def separate_names(author:str) -> list[list[list[str]],int]: """ function for separating different authors and their - separates by ";" - matches strings starting with uppercase letters """ authors = re.findall(r"([^;]*)",author) authors = list(filter(None,authors)) authors = [re.findall(r"([A-Z]\w*)",i) for i in authors] n_author = len(authors) return authors, n_author
def check_copyright(pub_year:int, cover_page_text: str, filename: str, ref_filenames: list[str] ) -> bool: """ Function for checking public domain status based on: - year published, - if the digitalising party claims it is copyright free - if the filename can be matched to a name from an outside source """ if pub_year < 1833: public_domain = True elif ("free of copyright" in cover_page_text): public_domain = True elif filename in ref_filenames: public_domain = True else: public_domain = False
return public_domain
def convert_pdf_to_dataset(file_name: str, path_to_file: str, demo: bool = False) -> Dataset: """Converts pdf to image and a dataset with rows by page, based on: https://thepythoncode.com/article/convert-pdf-files-to-images-in-python """ #create path, create id input_file=os.path.join(path_to_file,file_name) #whitespaces to underscores, remove: punctuation, alma, pdf doc_id = re.sub(" ","_",file_name) doc_id = ''.join(filter(lambda x: x not in string.punctuation, doc_id)) doc_id = re.sub(r"alma|pdf","",doc_id) #get metadata pub_year = file_name[:4] #get metadata (from json) author, title, digitalized, doc_source = extract_meta_data(input_file) # Open the document pdfIn = fitz.open(input_file) data_list = [] # Iterate throughout the pages, set range for full doc or demo test runs if demo: page_range = 1 else: page_range = pdfIn.page_count
for pg in range(page_range): page = pdfIn[pg] #get page text page_text = page.get_text() #meta data from frontpage if still missing if pg == 0: #remove \n for easier regexing try: text_solid = re.sub("\n","",page_text) except TypeError: #if no text on frontpage text_solid = "missing"
if author == "missing": try: author = re.search(r"(?<=Author\(s\):)(.*?)(?=Titel)",text_solid)[0] #trying to clean it a bit author = simplify_name(author) #author, n_author = separate_names(author) except TypeError: #in case no cover page author = "missing" finally: #in case cover page present, but still no author if len(author) == 0: author = "missing" else: pass
if title == "missing": try: title = re.search(r"(?<=Title:)(.*?)(?=Udgivet)",text_solid)[0] except TypeError: title = "missing" #now that all possible meta data is gathered after first page, see copyright status copyright_free = check_copyright(int(pub_year), text_solid, file_name, ref_pd_list) else: #on other pages pass
if not copyright_free: #if public domain was not confirmed, end looking through pages break
#create page_image rotate = int(0) # 2, 2 (text should be readable) zoom_x = 2 zoom_y = 2 # Pre-rotate is to rotate if needed. mat = fitz.Matrix(zoom_x, zoom_y).prerotate(rotate) pix = page.get_pixmap(matrix=mat, alpha=False) page_img = pix.pil_image() page_id = f"{doc_id}_p{pg+1}" #assemble data_doc if type(author) == list: author = "; ".join(author) else: pass meta_data ={"doc_id" : doc_id, "page_id" : page_id, "page_image" : page_img, "page_text": page_text, "author": author, "title" : title, "published": pub_year, "digitalized": digitalized, "source": doc_source, "file_name": file_name} data_list.append(meta_data)
pdfIn.close()
if copyright_free: ds = Dataset.from_list(data_list) else: ds = "missing" return ds
def make_year_list(start_year: int, stop_year: int) -> list[str]: """make a list of file names based on years""" year_list = list(range(start_year, stop_year + 1)) year_list = [str(i) for i in year_list] return year_list
#source filter for ADL (they are not scanned pdfs)adl_filter = lambda ds: ds["source"] != "ADLFBI"
def split(a, n): "splits list into n roughly equal parts" k, m = divmod(len(a), n) return (a[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(n))
def remove(path): """ param <path> could either be relative or absolute. """ if os.path.isfile(path) or os.path.islink(path): os.remove(path) # remove the file elif os.path.isdir(path): shutil.rmtree(path) # remove dir and all contains else: raise ValueError("file {} is not a file or dir.".format(path)) def reorganize_data(output_path: str, shard_size: str = "5"): """ Loads the temporary data folders in the data path and creates 5GB shards for each year, deletes temporary files """ folders = os.listdir(output_path) temp_folders = [i for i in folders if "_t" in i] if len(temp_folders) == 0: print("DATA ORGANIZED") return print("REORGANIZING DATA...") for t_fold in tqdm(temp_folders): #load all separate parquets into 1 ds data_path = os.path.join(output_path,t_fold) data_set = load_dataset(data_path, split = "train") #save it to appropriately size chunks year_str = t_fold[:-2] new_data_path = os.path.join(output_path,year_str) data_set.save_to_disk(new_data_path, max_shard_size="5GB") #delete temp_folder try : remove(data_path) except PermissionError as e: print(f"{e}")
def main(): sub_folders = os.listdir(input_path) for u in unwanted_folders: sub_folders.remove(u) #select years to process year_list = make_year_list(start_year,stop_year) sub_folders = sorted([i for i in sub_folders if i in year_list]) #chunking because there's a lot of data chunks = [sub_folders[i:i + n_chunks] for i in range(0, len(sub_folders), n_chunks)]
logger.info(f"Extracting from PDFs...{sub_folders[0]}-{sub_folders[-1]}") for ch in tqdm(chunks): problem_list =[] for sfolder in ch: #sub folder path e.g /raw/1750 sfp = os.path.join(input_path,sfolder) files = [i for i in os.listdir(sfp) if ".pdf" in i] #further chunking because even 1 year is too much memory-wise #batched_files = list(split(files,10)) #limit files in 1 parquet batched_files = [files[i:i + n_batch] for i in range(0, len(files), n_batch)] for batch_nr, batch in enumerate(batched_files): ds=[] for i in batch: try: temporary_ds = convert_pdf_to_dataset(i,sfp,demo) if temporary_ds is None: pass else: print(temporary_ds[0]["file_name"]) for j in temporary_ds: ds.append(j)
except BaseException as e: logger.info(f"FILE ERROR: {os.path.join(sfp,i)}") logger.info(f"ERROR: {e}") problem_list.append(i)
logger.info(f"Assembling Dataset: {ch[0]}-{ch[-1]}, BATCH:{batch_nr}") #if no viable data was saved, do not make a parquet if len(ds) == 0: continue ds = Dataset.from_list(ds) #filter out certain files ds = ds.filter(adl_filter) ds = ds.remove_columns("source") #make subfolders by year _t for temporary, will be reorganized save_path = os.path.join(output_path,f"{sfolder}_t",f"{source}_{ch[0]}-{ch[-1]}_{batch_nr}.parquet") ds.to_parquet(save_path)
logger.info(f"FOLDER DONE: {sfolder}")
if len(problem_list) >= 1: with open(os.path.join(logs,f"problems_{ch[0]}-{ch[-1]}.txt"), 'w') as outfile: outfile.write('\n'.join(str(i) for i in problem_list)) else: pass #reorganize the data after running everything ds = None temporary_ds = None del ds del temporary_ds reorganize_data(output_path)
if __name__ == "__main__": log_path = os.path.join(logs,"extract.log") logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s", handlers=[ logging.StreamHandler(), logging.FileHandler(log_path), ], ) main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192025-08-07 10:58:00,739 - INFO - Extracting from PDFs...1750-17502025-08-07 11:12:13,530 - INFO - Assembling Dataset: 1750-1750, BATCH:02025-08-07 11:22:09,771 - INFO - Extracting from PDFs...1750-17502025-08-07 11:36:09,351 - INFO - Assembling Dataset: 1750-1750, BATCH:02025-08-07 13:27:04,947 - INFO - Extracting from PDFs...1750-17502025-08-07 13:55:40,145 - INFO - Assembling Dataset: 1750-1750, BATCH:02025-08-07 14:47:29,002 - INFO - Assembling Dataset: 1750-1750, BATCH:12025-08-07 15:19:31,498 - INFO - Assembling Dataset: 1750-1750, BATCH:22025-08-07 15:29:16,231 - INFO - Assembling Dataset: 1750-1750, BATCH:32025-08-07 15:32:22,518 - INFO - FOLDER DONE: 17502025-08-07 15:43:54,046 - INFO - Extracting from PDFs...1751-17522025-08-07 16:28:59,288 - INFO - Assembling Dataset: 1751-1751, BATCH:02025-08-07 17:14:19,777 - INFO - Extracting from PDFs...1919-19202025-08-07 17:14:23,075 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Foreløbig Beretning angaaende ..._alma99122800516705763.pdf2025-08-07 17:14:23,075 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:14:23,561 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Bestemmelser vedrørende Slesvi..._alma99121995648405763.pdf2025-08-07 17:14:23,561 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:14:24,220 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Prisniveaustigningen 1914-1919..._alma99122350600405763.pdf2025-08-07 17:14:24,220 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:14:26,469 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Guds Ord som Lyskaster under V..._alma99122350697005763.pdf2025-08-07 17:14:26,469 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:14:29,540 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Sangen om Sønderjylland - saml..._alma99122765957305763.pdf2025-08-07 17:14:29,540 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:14:30,332 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Vort Grænsespørgsmaal - Indled..._alma99122765952905763.pdf2025-08-07 17:14:30,332 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:14:31,523 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Udenrigsminister Scavenius og ..._alma99122209593305763.pdf2025-08-07 17:14:31,523 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:14:31,524 - INFO - Assembling Dataset: 1919-1919, BATCH:02025-08-07 17:14:35,081 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Indberetninger fra de vigtigst..._alma99122350688005763.pdf2025-08-07 17:14:35,082 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:15:35,442 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Kulturens Fallit _alma99122350703905763.pdf2025-08-07 17:15:35,442 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:15:36,883 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Fredsslutningen - i Belysning ..._alma99122350577605763.pdf2025-08-07 17:15:36,883 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:15:37,349 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Verdenskrigen og Fremtidens Un..._alma99122800382805763.pdf2025-08-07 17:15:37,349 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:15:40,008 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Flanderns Løve._alma99122350610105763.pdf2025-08-07 17:15:40,009 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:15:40,009 - INFO - Assembling Dataset: 1919-1919, BATCH:12025-08-07 17:16:31,412 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Oversigt over Maksimalpriser v..._alma99122350591205763.pdf2025-08-07 17:16:31,412 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:16:37,017 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_En Pilgrimsfærd til Nordfrankr..._alma99122754431905763.pdf2025-08-07 17:16:37,018 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:16:37,479 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Kirkens Velkommen til sønderjy..._alma99122350756505763.pdf2025-08-07 17:16:37,480 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:16:38,024 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Betragtninger over Tidens Begi..._alma99122765836405763.pdf2025-08-07 17:16:38,024 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:16:38,542 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Slien-Dannevirke._alma99122581035505763.pdf2025-08-07 17:16:38,542 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:16:39,098 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Mindegudstjenesten over de und..._alma99122209615005763.pdf2025-08-07 17:16:39,098 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:16:40,033 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Rigets Sydgrænse - tre histori..._alma99122765811005763.pdf2025-08-07 17:16:40,033 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:16:40,034 - INFO - Assembling Dataset: 1919-1919, BATCH:22025-08-07 17:16:41,816 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Operationerne paa Vestfronten ..._alma99121995481705763.pdf2025-08-07 17:16:41,816 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:16:46,099 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Sønderjylland vundet._alma99122765806805763.pdf2025-08-07 17:16:46,099 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:19:15,327 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_I Troens Lys - Begivenhederne ..._alma99122765830205763.pdf2025-08-07 17:19:15,327 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:23:26,768 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Det officielle Danmark i Krige..._alma99122350687105763.pdf2025-08-07 17:23:26,769 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:23:26,769 - INFO - Assembling Dataset: 1919-1919, BATCH:32025-08-07 17:27:37,060 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Sønderjylland - en Hilsen til ..._alma99122754284705763.pdf2025-08-07 17:27:37,060 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:28:51,461 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Regnskab _alma99121946921605763.pdf2025-08-07 17:28:51,461 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:28:51,942 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Verdenskrigen 1914-19 _alma99122350851205763.pdf2025-08-07 17:28:51,942 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:28:54,582 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Under Bolsjevikernes Diktatur ..._alma99122350867905763.pdf2025-08-07 17:28:54,583 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:45:01,025 - INFO - Assembling Dataset: 1919-1919, BATCH:42025-08-07 17:56:30,936 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Den fransk-russiske Alliance._alma99122765967505763.pdf2025-08-07 17:56:30,936 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:56:31,439 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Pax mundi - Verdensfredsmærket..._alma99122350599905763.pdf2025-08-07 17:56:31,439 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:56:32,213 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Samling III af Udvalgets Beslu..._alma99122350754805763.pdf2025-08-07 17:56:32,213 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:57:13,317 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Sønderjydske Krigsfanger i Eng..._alma99122765940705763.pdf2025-08-07 17:57:13,317 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:57:13,653 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Lov om Afvikling af de overord..._alma99122350691905763.pdf2025-08-07 17:57:13,653 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:57:13,654 - INFO - Assembling Dataset: 1919-1919, BATCH:52025-08-07 17:57:39,309 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Sandheden om Danmarks Spærring..._alma99122350751405763.pdf2025-08-07 17:57:39,310 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:57:40,779 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Statistisk aarbog 1919 - annua..._alma99122466365005763.pdf2025-08-07 17:57:40,780 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:57:41,178 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Hvad en ung Vestjyde kan genne..._alma99122350757605763.pdf2025-08-07 17:57:41,178 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:57:42,709 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Nogle bemærkninger om Feltarti..._alma99122350596505763.pdf2025-08-07 17:57:42,709 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:58:35,573 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Et af Krigens Ofre _alma99122800523105763.pdf2025-08-07 17:58:35,573 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 17:59:19,199 - INFO - Assembling Dataset: 1919-1919, BATCH:62025-08-07 18:00:19,823 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Det sønderjyske Spørgsmaal - e..._alma99121995602705763.pdf2025-08-07 18:00:19,823 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:00:21,288 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Danmarks Skibsfart under Verde..._alma99122350755305763.pdf2025-08-07 18:00:21,288 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:00:21,478 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Forelæsninger over første Bog ..._alma99122561704405763.pdf2025-08-07 18:00:21,478 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:00:29,850 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Vor Ret! - de tro Flensborgere..._alma99122925774605763.pdf2025-08-07 18:00:29,851 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:00:31,852 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Det slesvigske Regiment._alma99121936924105763.pdf2025-08-07 18:00:31,853 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:00:33,300 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Genforening af en Del af Slesv..._alma99122765823005763.pdf2025-08-07 18:00:33,301 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:00:33,301 - INFO - Assembling Dataset: 1919-1919, BATCH:72025-08-07 18:00:40,624 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Fest-Avis for Sundbyernes Unde..._alma99122896836605763.pdf2025-08-07 18:00:40,624 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:00:54,236 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Operationerne paa Vestfronten ..._alma99122765927405763.pdf2025-08-07 18:00:54,236 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:01:01,428 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Verdenskrigen 1914-1919._alma99122350691405763.pdf2025-08-07 18:01:01,429 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:01:01,884 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Grænseproblemet og Kanalproble..._alma99122209599805763.pdf2025-08-07 18:01:01,884 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:01:03,311 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Udenlandsk Litteratur vedrøren..._alma99122765943705763.pdf2025-08-07 18:01:03,311 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:01:03,311 - INFO - Assembling Dataset: 1919-1919, BATCH:82025-08-07 18:01:15,241 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Sønderjylland og de politiske ..._alma99122765844805763.pdf2025-08-07 18:01:15,241 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:01:16,700 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Helsingfors under det røde Reg..._alma99122350681805763.pdf2025-08-07 18:01:16,700 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:01:18,077 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Felttogene i Serbien i 1914-15..._alma99122350869305763.pdf2025-08-07 18:01:18,077 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:01:18,517 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Strenge Tider er for Haanden._alma99122350768105763.pdf2025-08-07 18:01:18,517 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:02:10,273 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Ernæringsraadet, oprettet i Fø..._alma99122800372705763.pdf2025-08-07 18:02:10,274 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:02:15,091 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Sønderjylland _alma99122539146305763.pdf2025-08-07 18:02:15,091 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:02:15,091 - INFO - Assembling Dataset: 1919-1919, BATCH:92025-08-07 18:02:51,760 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Krigsepidemiologiske Erfaringe..._alma99122350580605763.pdf2025-08-07 18:02:51,760 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:03:31,198 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Om Danmarks Fremtidsgrænse mod..._alma99122765969905763.pdf2025-08-07 18:03:31,199 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:04:14,472 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Krigen og Kurserne - 1. Bind._alma99122209606305763.pdf2025-08-07 18:04:14,473 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:04:15,385 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Fra de sønderjydske Krigsfange..._alma99122925948505763.pdf2025-08-07 18:04:15,386 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:04:15,890 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Wladimir Uljanoff Lenin - hans..._alma99121936949505763.pdf2025-08-07 18:04:15,891 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:04:15,891 - INFO - Assembling Dataset: 1919-1919, BATCH:102025-08-07 18:05:04,143 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_De sønderjydske Dage i Københa..._alma99122765812205763.pdf2025-08-07 18:05:04,144 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:05:04,719 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Sønderjylland tilbage til Danm..._alma99122765843705763.pdf2025-08-07 18:05:04,719 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:05:05,787 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Sønderjylland 1864-1919 - udgi..._alma99122765830905763.pdf2025-08-07 18:05:05,787 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:05:06,367 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_I Bolschewikernes Rusland - In..._alma99122350686205763.pdf2025-08-07 18:05:06,367 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:05:07,316 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Danske Røster Nord og Syd for ..._alma99122522037305763.pdf2025-08-07 18:05:07,316 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:05:08,337 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Betænkning fra -Det kirkelige ..._alma99122887328005763.pdf2025-08-07 18:05:08,338 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:05:23,299 - INFO - Assembling Dataset: 1919-1919, BATCH:112025-08-07 18:05:36,530 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_Beretning for Aarene... _alma99122022382005763.pdf2025-08-07 18:05:36,530 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:05:37,959 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_De danske Sønderjyder _alma99121995507405763.pdf2025-08-07 18:05:37,959 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:05:38,495 - INFO - FILE ERROR: ../../kb-books/raw/1919/1919_[Aktstykker vedrørende det søn..._alma99122554538005763.pdf2025-08-07 18:05:38,495 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:05:38,496 - INFO - Assembling Dataset: 1919-1919, BATCH:122025-08-07 18:05:38,496 - INFO - FOLDER DONE: 19192025-08-07 18:05:38,655 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Vor Brændselsforsyning - I hvi..._alma99125415640005763.pdf2025-08-07 18:05:38,656 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:05:38,939 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Samling af Love og Bestemmelse..._alma99125698448405763.pdf2025-08-07 18:05:38,939 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:06:22,314 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Studenter vi kaldes - - muntre..._alma99123915203105763.pdf2025-08-07 18:06:22,315 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:09:21,503 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Ardjun - en indisk Drengs Livs..._alma99125107098505763.pdf2025-08-07 18:09:21,504 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:14:09,705 - INFO - Assembling Dataset: 1920-1920, BATCH:02025-08-07 18:20:46,548 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_[Indberetning til Niels Neerga..._alma99122765960505763.pdf2025-08-07 18:20:46,549 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:20:46,670 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Odense Vin Kompagni - 1895 - 1..._alma99124696449805763.pdf2025-08-07 18:20:46,670 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:21:09,159 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Fribytterdrømme - Digte._alma99125224825805763.pdf2025-08-07 18:21:09,159 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:21:09,263 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Kaddara - Folkelivsbilleder fr..._alma99125224853505763.pdf2025-08-07 18:21:09,263 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:21:09,500 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Illustreret Havebog - 1.-3. De..._alma99125466829705763.pdf2025-08-07 18:21:09,501 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:21:09,501 - INFO - Assembling Dataset: 1920-1920, BATCH:12025-08-07 18:21:32,283 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Hvorfor vi bør have et Hushold..._alma99125466879005763.pdf2025-08-07 18:21:32,284 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:22:31,758 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Krigsfangerne i Rusland og Sib..._alma99122403446405763.pdf2025-08-07 18:22:31,759 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:22:32,052 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Hafis' Sange _alma99124018440005763.pdf2025-08-07 18:22:32,052 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:22:32,265 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Statshusmandsbevægelsen eller ..._alma99124018373405763.pdf2025-08-07 18:22:32,266 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:22:32,392 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Bibelhistorie med et Uddrag af..._alma99124095865405763.pdf2025-08-07 18:22:32,392 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:22:32,392 - INFO - Assembling Dataset: 1920-1920, BATCH:22025-08-07 18:23:12,144 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Smaatryk - udg. af Forening fo..._alma99125729443005763.pdf2025-08-07 18:23:12,144 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:23:12,302 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Spiritismen - Kan man sætte si..._alma99125415639805763.pdf2025-08-07 18:23:12,302 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:23:12,521 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Lolland-Falsters Forstmandsfor..._alma99123824393005763.pdf2025-08-07 18:23:12,521 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:23:12,677 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Nedgang og Genoprettelse - Hel..._alma99124088959005763.pdf2025-08-07 18:23:12,677 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:23:12,852 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Udvalgsbetænkning vedrørende d..._alma99123793057205763.pdf2025-08-07 18:23:12,853 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:23:13,010 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Christen Jensen, Vindt Mølle o..._alma99124095564405763.pdf2025-08-07 18:23:13,010 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:23:13,272 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Jødefaren. De verdensberygtede..._alma99124073618905763.pdf2025-08-07 18:23:13,272 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:23:13,272 - INFO - Assembling Dataset: 1920-1920, BATCH:32025-08-07 18:23:16,085 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Fodfolket - Organisation, Bevæ..._alma99122765839205763.pdf2025-08-07 18:23:16,085 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:23:16,311 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Jødefaren - Bevismateriale _alma99124073568105763.pdf2025-08-07 18:23:16,311 - INFO - ERROR: string indices must be integers, not 'str'2025-08-07 18:23:16,467 - INFO - FILE ERROR: ../../kb-books/raw/1920/1920_Vejledning til Anvendelse af L..._alma99122943569005763.pdf2025-08-07 18:23:16,468 - INFO - ERROR: string indices must be integers, not 'str'2025-08-11 13:27:55,385 - INFO - Extracting from PDFs...1751-17522025-08-11 14:20:16,074 - INFO - Assembling Dataset: 1751-1751, BATCH:02025-08-11 15:12:51,632 - INFO - Extracting from PDFs...1751-17522025-08-11 15:57:32,435 - INFO - Assembling Dataset: 1751-1751, BATCH:012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667681919_Foreløbig Beretning angaaende ..._alma99122800516705763.pdf1919_Bestemmelser vedrørende Slesvi..._alma99121995648405763.pdf1919_Prisniveaustigningen 1914-1919..._alma99122350600405763.pdf1919_Guds Ord som Lyskaster under V..._alma99122350697005763.pdf1919_Sangen om Sønderjylland - saml..._alma99122765957305763.pdf1919_Vort Grænsespørgsmaal - Indled..._alma99122765952905763.pdf1919_Udenrigsminister Scavenius og ..._alma99122209593305763.pdf1919_Indberetninger fra de vigtigst..._alma99122350688005763.pdf1919_Kulturens Fallit _alma99122350703905763.pdf1919_Fredsslutningen - i Belysning ..._alma99122350577605763.pdf1919_Verdenskrigen og Fremtidens Un..._alma99122800382805763.pdf1919_Flanderns Løve._alma99122350610105763.pdf1919_Oversigt over Maksimalpriser v..._alma99122350591205763.pdf1919_En Pilgrimsfærd til Nordfrankr..._alma99122754431905763.pdf1919_Kirkens Velkommen til sønderjy..._alma99122350756505763.pdf1919_Betragtninger over Tidens Begi..._alma99122765836405763.pdf1919_Slien-Dannevirke._alma99122581035505763.pdf1919_Mindegudstjenesten over de und..._alma99122209615005763.pdf1919_Rigets Sydgrænse - tre histori..._alma99122765811005763.pdf1919_Operationerne paa Vestfronten ..._alma99121995481705763.pdf1919_Sønderjylland vundet._alma99122765806805763.pdf1919_I Troens Lys - Begivenhederne ..._alma99122765830205763.pdf1919_Det officielle Danmark i Krige..._alma99122350687105763.pdf1919_Sønderjylland - en Hilsen til ..._alma99122754284705763.pdf1919_Regnskab _alma99121946921605763.pdf1919_Verdenskrigen 1914-19 _alma99122350851205763.pdf1919_Under Bolsjevikernes Diktatur ..._alma99122350867905763.pdf1919_Den fransk-russiske Alliance._alma99122765967505763.pdf1919_Pax mundi - Verdensfredsmærket..._alma99122350599905763.pdf1919_Samling III af Udvalgets Beslu..._alma99122350754805763.pdf1919_Sønderjydske Krigsfanger i Eng..._alma99122765940705763.pdf1919_Lov om Afvikling af de overord..._alma99122350691905763.pdf1919_Sandheden om Danmarks Spærring..._alma99122350751405763.pdf1919_Statistisk aarbog 1919 - annua..._alma99122466365005763.pdf1919_Hvad en ung Vestjyde kan genne..._alma99122350757605763.pdf1919_Nogle bemærkninger om Feltarti..._alma99122350596505763.pdf1919_Et af Krigens Ofre _alma99122800523105763.pdf1919_Det sønderjyske Spørgsmaal - e..._alma99121995602705763.pdf1919_Danmarks Skibsfart under Verde..._alma99122350755305763.pdf1919_Forelæsninger over første Bog ..._alma99122561704405763.pdf1919_Vor Ret! - de tro Flensborgere..._alma99122925774605763.pdf1919_Det slesvigske Regiment._alma99121936924105763.pdf1919_Genforening af en Del af Slesv..._alma99122765823005763.pdf1919_Fest-Avis for Sundbyernes Unde..._alma99122896836605763.pdf1919_Operationerne paa Vestfronten ..._alma99122765927405763.pdf1919_Verdenskrigen 1914-1919._alma99122350691405763.pdf1919_Grænseproblemet og Kanalproble..._alma99122209599805763.pdf1919_Udenlandsk Litteratur vedrøren..._alma99122765943705763.pdf1919_Sønderjylland og de politiske ..._alma99122765844805763.pdf1919_Helsingfors under det røde Reg..._alma99122350681805763.pdf1919_Felttogene i Serbien i 1914-15..._alma99122350869305763.pdf1919_Strenge Tider er for Haanden._alma99122350768105763.pdf1919_Ernæringsraadet, oprettet i Fø..._alma99122800372705763.pdf1919_Sønderjylland _alma99122539146305763.pdf1919_Krigsepidemiologiske Erfaringe..._alma99122350580605763.pdf1919_Om Danmarks Fremtidsgrænse mod..._alma99122765969905763.pdf1919_Krigen og Kurserne - 1. Bind._alma99122209606305763.pdf1919_Fra de sønderjydske Krigsfange..._alma99122925948505763.pdf1919_Wladimir Uljanoff Lenin - hans..._alma99121936949505763.pdf1919_De sønderjydske Dage i Københa..._alma99122765812205763.pdf1919_Sønderjylland tilbage til Danm..._alma99122765843705763.pdf1919_Sønderjylland 1864-1919 - udgi..._alma99122765830905763.pdf1919_I Bolschewikernes Rusland - In..._alma99122350686205763.pdf1919_Danske Røster Nord og Syd for ..._alma99122522037305763.pdf1919_Betænkning fra -Det kirkelige ..._alma99122887328005763.pdf1919_Beretning for Aarene... _alma99122022382005763.pdf1919_De danske Sønderjyder _alma99121995507405763.pdf1919_[Aktstykker vedrørende det søn..._alma99122554538005763.pdf123version https://git-lfs.github.com/spec/v1oid sha256:732ec80410a0cd94bc0a5362d16ab9efb4430058b3aa28164ff93eccf9f5eb02size 759609123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523import osimport reimport stringimport jsonimport loggingimport itertoolsfrom datetime import datetimefrom tqdm import tqdmfrom difflib import SequenceMatcher
import fitzfrom datasets import Dataset, load_dataset
def int_to_roman(number:int) -> str: """ integers to roman numerals""" ROMAN = [ (1000, "M"), ( 900, "CM"), ( 500, "D"), ( 400, "CD"), ( 100, "C"), ( 90, "XC"), ( 50, "L"), ( 40, "XL"), ( 10, "X"), ( 9, "IX"), ( 5, "V"), ( 4, "IV"), ( 1, "I"), ] result = [] for (arabic, roman) in ROMAN: (factor, number) = divmod(number, arabic) result.append(roman * factor) if number == 0: break return "".join(result)
def process_non_upper_names(author:str) -> str: """ returns the end of a name, in which there are non-uppercase parts 2 special cases - some middle name indicating a place "von,af,de etc... - some end name indicating a trait "den yngre, den ælder etc... 1 special case - some numeral used for royalty "Christian 1." """ mid_name_list = [' af ', ' da ', ' de ', ' du ', ' la ', ' le ', ' til ', ' van ', ' von ', ' zu ' ] end_name_list = [' den Gamle', ' den Hellige', ' den Store', ' den Unge', ' den eldre', ' den yngre', ' den yngste', ' den Ældre', ' den ældre', ' junior', ' the Younger' ] #get everythin after midname mid_name = [i for i in mid_name_list if i in author] if len(mid_name) != 0: mid_name = re.findall(rf"{mid_name[0]}.*", author) #get end, if midname already has it, don't end_name = [i for i in end_name_list if i in author] if len(end_name) != 0 and len(mid_name) != 0 and end_name[0] in mid_name[0]: end_name = [] full_name = [mid_name,end_name] full_name = "".join(sum(full_name, [])) return full_name
def monogram_list(author: str) -> list[str]: """ creates a list of first name abbreviations John Alex Sample --> [John Alex Sample, J Alex Sample, J A Sample, John A Sample]
special case endings added by process_non_upper_names(author:str) -> str: int_to_roman(number:int) -> str: """ #remove special cases, they will be re-added after the last name at the end spec_end = process_non_upper_names(author) author = author.replace(spec_end,"")
abbreviation_list = [author] #split on whitespace author = re.split(r"[\s]+",author) #-1 because last name stays long in_list = author[:-1] #get all combinations of list elements as sublists out_list = [c for i in range(len(in_list)) for c in itertools.combinations(in_list, i+1)] out_list = [x[0] if len(x) == 1 else list(x) for x in out_list] #make single entries into one item lists out_list = [["".join(list(x))] if type(x) is not list else x for x in out_list]
for name_combos in out_list: name_short = [] name_index = [] #for each list of combinations #the names in that combination will be shortened for name in name_combos: if name in author: #find the elements in that exact combination #replace the names with the first character og_index = author.index(name) abbreviation = name[0] #list indexes and replacements for those indexes name_index.append(og_index) name_short.append(abbreviation) #replace abbr_author = author.copy() for (name_index, name_short) in zip(name_index, name_short): abbr_author[name_index] = name_short abbreviation_list.append(" ".join(abbr_author)) #remove dupes, add special endings abbreviation_list = list(set(abbreviation_list))
if spec_end != "": spec_end_l = [i + spec_end for i in abbreviation_list] abbreviation_list = sum([abbreviation_list,spec_end_l],[]) if sum(1 for i in author if i.isdigit()) > 0: numeric = [i for i in author if i.isdigit()][0] rom_num = int_to_roman(int(numeric)) rom_num_l = [i.replace(numeric,rom_num) for i in abbreviation_list] abbreviation_list = sum([abbreviation_list,rom_num_l],[])
return abbreviation_list
def clean_names(authors:str) -> list[str]: """ Takes a string of author names separated by ";" and reformats - returns a list - switches surname firstname order if "," present - removes parentheses e.g from: " Jens Sample ; Example, Hans ; S. A. Ample (example)" to: ["Jens Sample","Hans Example","S. A. Ample"] """ authors = authors.split(";") #If "," --> split item, reverse it, rejoin it. Otherwise don't authors = ["".join(x.split(",")[::-1]) if "," in x else x for x in authors] #If parentheses, remove them. authors = [re.sub(r"[\(].*?[\)]", "", x) if ("(" or ")") in x else x for x in authors] #separate elements by char, make punctuation whitespace, join again, authors = ["".join([ch if ch not in string.punctuation else " " for ch in el]).strip() for el in authors] #If two uppercase characters are beside, separate them AB -> A B authors = ["".join([" " + ch if el[chr_count-1].isupper() and ch.isupper() else ch for chr_count, ch in enumerate(el)]) for el in authors] #remove excess spaces (inside and from the sides) and empty elements authors = [re.sub(' +', ' ', i).strip() for i in authors if i != ""] return authors
def lower_names(authors: list[str]) -> list[str]: """ Takes a list of author names lowercases them for easier comparison e.g from: ["Jens Sample","Hans Example","S. A. Ample"] to: ["jenssample","hansexample","saample"] """ #remove dots and spaces, lowercase authors = [x.replace(".","") for x in authors] authors = [x.replace(" ","") for x in authors] authors = [x.lower() for x in authors] return authors
def add_abbreviations(ds:Dataset)->Dataset: """add abbreviations to single author names in the scraped reference dataset""" #clean it first to remove parentheses ds["c_name"] = clean_names(ds["name"]) ds["abbrevs"] = monogram_list( clean_names(ds["name"])[0] ) return ds
def separate_authors(ds:Dataset)->Dataset: """separate authors in the pdf metadata""" ds["c_author"] = clean_names(ds["author"]) ds["n_author"] = len(ds["c_author"]) ds["abbrevs"] = [monogram_list(i) for i in ds["c_author"]]
return ds
def check_abbrevs(name:str) -> bool: """checks if there abbreviations in a name""" newstr = " "+ name #any whitespace any word any whitespace pattern match if re.match(r"\s\w\s",newstr) is None: return False else: return True
def dead_70_yrs_ago(ds): """filter for the scraped authors to find ones who have died 70 years ago""" birth_miss = False death_miss = False try: birth_yr = int(ds["born"]) if birth_yr > 1955: birth = False else: birth = True except ValueError: birth = False birth_miss = True
try: death_yr = int(ds["died"]) if death_yr > 1955: death = False else: death = True except ValueError: death = False death_miss = True
#both years are before 1955 and none of them are missing if (death and birth and not birth_miss and not death_miss): filtered = True else: filtered = False
return filtered
def match_by_name(name : str, ds_filt: dict[str|str]) -> list[list[str],list[str]] : """ Match a name to another list of meta data returns [name + birth and death dates], [reference link] """ ref_names = [x for xs in ds_filt["c_name"] for x in xs] name_matches = [] link_matches = [] #match the name to the list off all clean names, #get the more informative name from the ds based on index found_author = "".join(set([name]).intersection(ref_names)) found_names = [ds_filt["name_yr"][indx] for indx in [i for i in range(len(ref_names)) if ref_names[i]==found_author]] found_links = [ds_filt["link"][indx] for indx in [i for i in range(len(ref_names)) if ref_names[i]==found_author]] #append the elements, not the list for i in found_names: name_matches.append(i) for i in found_links: link_matches.append(i)
return name_matches, link_matches
def match_by_abbreviation(abbrev : str, ds_filt: dict[str|str]) -> list[list[str],list[str]] : """ Match a name with an abbreviated word in it to another list of meta data. returns [name + birth and death dates], [reference link] """ name_matches = [] link_matches = [] #find all occurrences of the abbreviation match a_m = [x["abbrevs"] for x in ds_filt if abbrev in x["abbrevs"]] #get the name_yr variable for those matches based on index found_names = [ds_filt[i]["name_yr"] for i in range(len(ds_filt)) for x in a_m if ds_filt[i]["abbrevs"] == x] #same with links found_links = [ds_filt[i]["link"] for i in range(len(ds_filt)) for x in a_m if ds_filt[i]["abbrevs"] == x] #remove duplicates found_names = list(set(found_names)) found_links = list(set(found_links)) #append the elements, not the list for i in found_names: name_matches.append(i) for i in found_links: link_matches.append(i) #remove duplicates name_matches = list(set(name_matches)) link_matches = list(set(link_matches))
return name_matches, link_matches
def find_author_json(data: dict[str,dict[str,dict[str,str]]]) -> str: """ A function for finding the author(s) from various possible locations in the json metadata. """ try: author = data.get("pnx").get("addata")["au"] except KeyError: author = [] try: add_author = data.get("pnx").get("addata")["addau"] except KeyError: add_author = []
authors = list(set(author)) + list(set(add_author)) authors = "; ".join(authors)
if len(authors) < 1: try: authors = data.get("pnx").get("sort")["author"] authors = "; ".join(authors) except KeyError: pass if len(authors) < 1: try: authors = data.get("pnx").get("display")["creator"] authors = "; ".join(authors) except KeyError: authors = "missing"
return (authors)
def find_title_json(data: dict[str,dict[str,dict[str,str]]]) -> str: """ A function for finding the title from various possible locations in the json metadata. """ try: title = data.get("pnx").get("display")["title"][0] except KeyError: title = [] if len(title) < 1: try: title = data.get("pnx").get("addata")["btitle"][0] except KeyError: pass else: pass if len(title) < 1: try: title = data.get("pnx").get("sort")["title"][0] except KeyError: pass if len(title) < 1: title = "missing" return(title)
def find_digitalization(data: dict[str,dict[str,dict[str,str]]]) -> str: """ A function for finding the digitalisation date from various possible locations in the json metadata. """ try: digit = data.get("pnx").get("display")["creationdate"][0] #last 4 digit number in string digit = re.findall(r"\d{4}$",digit)[0] except KeyError: digit = [] if len(digit) < 1: try: digit = data.get("pnx").get("addata")["date"][1] digit = re.findall(r"\d{4}$",digit)[0] except KeyError: digit = "missing" return(digit)
def find_source(data: dict[str,dict[str,dict[str,str]]]) -> str: """ A function for finding source of the document from the json metadata. """ try: doc_source = data.get("pnx").get("display")["lds50"] #last 4 digit number in string doc_source = [i for i in doc_source if "Digi" not in i][0] except (KeyError, IndexError): doc_source = "missing" return doc_source
def extract_meta_data(pdf_file:str) -> dict[str,str|int]: """ A function for extracting meta data from the json files includes: - author(s) - title - published - digitalized - source """ try: #load in json json_file = pdf_file[:-3] + "json" f = open(json_file) data = json.load(f) #do stuff authors = find_author_json(data) title = find_title_json(data) digitalized = find_digitalization(data) doc_source = find_source(data) #close f.close() except BaseException: authors = "missing" title = "missing" digitalized = "missing" doc_source = "missing" return authors, title, digitalized, doc_source
def make_metadata_ds(data_path:str) -> Dataset: """ Extracts Json metadata from all files in path and creates a ds """ ds_list = [] year_folders = os.listdir(data_path) #remove everythin thats not a year year_folders = [i for i in year_folders if len(i)==4] for year in tqdm(year_folders): for file in year: if "pdf" in file: input_file=os.path.join(data_path,year,file) #get metadata pub_year = year #get metadata (from json) author, title, _, _ = extract_meta_data(input_file)
meta_row = {"doc": file, "author": author, "title": title, "pub_year": pub_year} ds_list.append(meta_row) else: pass
meta_ds = Dataset.from_list(ds_list) #add author separation, and abbreviations meta_ds = meta_ds.map(separate_authors)
return meta_ds
def main(): #obtain scraped data ds_filtered = Dataset.from_parquet("..","scrape","da_people_large.parquet") ds_filtered = ds_filtered.map(add_abbreviations) ds_filtered = ds_filtered.filter(dead_70_yrs_ago) ##### get metadata from all pdfs into a dataset data_path = os.path.join("..","..","..","kb-books","raw") meta_ds = make_metadata_ds(data_path)
#match init_ds = {"doc": ["missing"], "author": ["missing"], "n_author": ["missing"], "title": ["missing"], "pub_year": ["missing"], "match": ["missing"], "link": ["missing"], "match_ratio": ["missing"], "pass":["missing"]} new_ds = Dataset.from_dict(init_ds) for i in tqdm(meta_ds): author_matches = [] link_matches = [] matched_authors = "missing" matched_link= "missing" publication_date = int(i["pub_year"]) #remove authors who were not more than 18 when published #they are probably just namesakes ds_filt = ds_filtered.filter(lambda ds: int(ds["born"]) + 18 < publication_date, desc= f"Year: {publication_date}")
for author in i["c_author"]: if check_abbrevs(author): name_list, link_list = match_by_abbreviation(author,ds_filt) else: name_list, link_list = match_by_name(author,ds_filt)
author_matches.append(name_list) link_matches.append(link_list)
if len(author_matches) > 0: matched_authors = author_matches matched_link = link_matches else: pass ########## evaluate matches #stringify the list like: #a1m1, a2m2; a2m1 , a2m2 (a1m1 = author 1 match 1)
str_auths = "; ".join([", ".join(i) for i in matched_authors]) str_links = "; ".join([", ".join(i) for i in matched_link]) #check if all authors have a match match_ratio = len([x for x in matched_authors if len(x) > 0]) / int(i["n_author"]) if match_ratio == 1: is_it_pd = True else: is_it_pd = False
#save info temp_ds = {"doc": i["doc"], ##Adjust for real data "author": "; ".join(i["c_author"]), "n_author": i["n_author"], "title": i["title"], "pub_year": i["pub_year"], "match":str_auths, "link": str_links, "match_ratio":match_ratio, "pass":is_it_pd} new_ds = new_ds.add_item(temp_ds) #filter confirmed passes new_ds = new_ds.filter(lambda ds: ds["pass"] == "true") passed_filenames = new_ds["doc"] #save whole dataset for checking new_ds.to_parquet("public_domain_data.parquet") #save only the filenames with open("public_domain_files.txt", 'w') as outfile: outfile.write('\n'.join(str(i) for i in passed_filenames))123version https://git-lfs.github.com/spec/v1oid sha256:5725ad3bc12770861cee958791af719672648f436d9ac7a5818fd3d97ce5455esize 476334123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306import osimport reimport requestsfrom tqdm import tqdmfrom datasets import Datasetfrom bs4 import BeautifulSoup
# try to find info def from_wiki_script(author_soup): try: text = str(author_soup.find_all("script")[0]) try: birth = re.findall(r"Født i \d{4}",text)[0] birth = re.findall(r"\d{4}",birth)[0] except IndexError: birth = None
try: death = re.findall(r"Døde i \d{4}",text)[0] death = re.findall(r"\d{4}",death)[0] except IndexError: death = None except KeyError: birth = None death = None return birth, death
def from_infobox(author_soup): #right infobox try: boxes = author_soup.find_all("table") try: boxes = [i for i in boxes if "biography" in i["class"]][0] try: #vals first 4 digit nr after string death = re.findall(r"(?<=Død).*?[^\d]*(\d{4})",str(boxes))[0] except IndexError: death = None try: birth = re.findall(r"(?<=Født).*?[^\d]*(\d{4})",str(boxes))[0] except IndexError: birth = None except IndexError: birth = None death = None except KeyError: birth = None death = None
return birth, death
#last resort, find first two 4 digit nums in first textboxdef from_wiki_text(author_soup): try: text = list(author_soup.find_all("p"))[0].get_text() try: birth = re.findall(r"\d{4}",text)[0] except IndexError: birth = None try: death = re.findall(r"\d{4}",text)[1] except IndexError: death = None except KeyError: birth = None death = None return birth, death
def none_to_q(val:str) -> str: """ If value is None replaces it with ?""" if val is None: val = "?" else: pass return val
def find_wiki_birth_death(author_soup): birth, death = from_wiki_script(author_soup) if birth is None and death is None: birth, death = from_infobox(author_soup) else: pass if birth is None and death is None: birth, death = from_wiki_text(author_soup) else: pass
birth = none_to_q(birth) death = none_to_q(death)
return birth, death
#filter for peopledef is_a_person(tag): return( (tag.has_attr('href')) and (tag.has_attr('title')) and (len(tag.attrs) == 2) and ("index" not in tag.get("href")) and (":") not in tag.get("href"))#filter for wikimedia commonsdef is_a_person_commons(tag): return( (tag.has_attr('href')) and (tag.has_attr('title')) and (len(tag.attrs) == 2) and ("index" not in tag.get("href")) and (("Writers" not in tag.get("title")) and ("ategories" not in tag.get("title")) and ("Denmark" not in tag.get("title"))) and ("Category" in tag.get("title")) )#filter for author subcategoriesdef is_a_subcategory(tag): return( (tag.has_attr('href')) and (tag.has_attr('title')) and ("Dansksprogede" in tag.get("title")) )
def flatten(twodlist :list[list,list]) -> list: """ flatten a list by 1 dimension""" onedlist = [x for xs in twodlist for x in xs] return onedlist
def extract_authors(people, authors:list[dict[str,str]], name_list:list[str] ) -> list[list[dict[str,str]], list[str]]: for i in people: author_name = i.get("title") author_link = i.get("href") if author_name not in name_list: #find their death author_page = requests.get(f"https://da.wikipedia.org{author_link}") author_soup = BeautifulSoup(author_page.content, 'html.parser') birth, death = find_wiki_birth_death(author_soup) author_row={ "link": f"https://da.wikipedia.org{author_link}", "name":author_name, "born":birth, "died":death, "name_yr":f"{author_name} ({birth}-{death})" } authors.append(author_row) name_list.append(author_name) else: pass return authors, name_list
def extract_authors_commons(people, authors:list[dict[str,str]], name_list:list[str] ) -> list[list[dict[str,str]], list[str]]: for i in people: author_name = i.get_text() author_link = i.get("href") if author_name not in name_list: #find their death author_page = requests.get(f"https://commons.wikimedia.org{author_link}") author_soup = BeautifulSoup(author_page.content, 'html.parser') boxes = author_soup.find_all("table") try: box = [i for i in boxes if "Date of birth" in str(i)][0] try: #vals first 4 digit nr after string death = re.findall(r"(?<=Date of death).*?[^\d]*(\d{4})",str(box))[0] except IndexError: death = None try: birth = re.findall(r"(?<=Date of birth).*?[^\d]*(\d{4})",str(box))[0] except IndexError: birth = None except IndexError: birth = None death = None
birth = none_to_q(birth) death = none_to_q(death) author_row={ "link": f"https://commons.wikimedia.org{author_link}", "name":author_name, "born":birth, "died":death, "name_yr":f"{author_name} ({birth}-{death})" } authors.append(author_row) name_list.append(author_name) else: pass return authors, name_list
def is_next_page(tag): return (tag.get_text() == "næste side")
def main(): authors = [] name_list = [] #people from main page print(f"https://da.wikipedia.org/wiki/Kategori:Dansksprogede_forfattere") page = requests.get(f"https://da.wikipedia.org/wiki/Kategori:Dansksprogede_forfattere") soup = BeautifulSoup(page.content, 'html.parser') #1 get all peeps from page people = list(soup.find_all("ul" and "li" and "a" and is_a_person)) authors, name_list = extract_authors( people, authors, name_list ) ##### go into subcategories sub_c = soup.find_all("ul" and "li" and "a" and is_a_subcategory) for i in sub_c: if "Danmark" not in i.get("title"): #if author not from denmark (more pages, less people) new_link = f"https://da.wikipedia.org/{i.get("href")}" page = requests.get(new_link) soup = BeautifulSoup(page.content, 'html.parser') people = list(soup.find_all("ul" and "li" and "a" and is_a_person)) authors, name_list = extract_authors( people, authors, name_list ) print(f"DONE: {i.get("title")}")
elif "Danmark" in i.get("title"): #if author from denmark (less pages, more people) print("Processing Authors from Denmark (alphabetic order)...\n") #alphabet_list = "A B".split() alphabet_list = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Æ Ø Å".split() for letter in tqdm(alphabet_list): page = requests.get(f"https://da.wikipedia.org/w/index.php?title=Kategori:Dansksprogede_forfattere_fra_Danmark&from={letter}") soup = BeautifulSoup(page.content, 'html.parser') people = list(soup.find_all("ul" and "li" and "a" and is_a_person)) authors, name_list = extract_authors( people, authors, name_list ) ###other webpages print(f"Processing https://commons.wikimedia.org/wiki/Category:Writers_from_Denmark_by_name") #abc_list = "A B".split() abc_list = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z".split() for abc in tqdm(abc_list): page = requests.get(f"https://commons.wikimedia.org/w/index.php?title=Category:Writers_from_Denmark_by_name&from={abc}") soup = BeautifulSoup(page.content, 'html.parser') people = list(soup.find_all("ul" and "li" and "a" and is_a_person_commons)) authors, name_list = extract_authors_commons( people, authors, name_list ) print(f"Processing https://da.wikipedia.org/wiki/Kategori:Personer_i_Dansk_Biografisk_Leksikon") #get names from page, next page, repeat for abc in tqdm(abc_list): page = requests.get(f"https://commons.wikimedia.org/w/index.php?title=Category:Writers_from_Denmark_by_name&from={abc}") soup = BeautifulSoup(page.content, 'html.parser') people = list(soup.find_all("ul" and "li" and "a" and is_a_person_commons)) authors, name_list = extract_authors_commons( people, authors, name_list ) #another webpage p_counter = 0 print(f"Processing https://da.wikipedia.org/wiki/Kategori:Personer_i_Dansk_Biografisk_Leksikon")
page = requests.get(f"https://da.wikipedia.org/wiki/Kategori:Personer_i_Dansk_Biografisk_Leksikon") soup = BeautifulSoup(page.content, 'html.parser') #get names from page, next page, repeat until no more next page while len(soup.find_all("a" and is_next_page)) > 0:
people = list(soup.find_all("ul" and "li" and "a" and is_a_person)) authors, name_list = extract_authors( people, authors, name_list ) p_counter += 1 new_page = soup.find_all("a" and is_next_page)[0]["href"] new_link = f"https://da.wikipedia.org/{new_page}" page = requests.get(new_link) soup = BeautifulSoup(page.content, 'html.parser') print(f"Scraped page {p_counter}/~30...") else: #last page print("Scraping last page...") people = list(soup.find_all("ul" and "li" and "a" and is_a_person)) authors, name_list = extract_authors( people, authors, name_list ) ds = Dataset.from_list(authors) ds.to_parquet(os.path.join(".","da_people_large.parquet"))
if __name__ == "__main__": main()data/.gitignoreAdded+1
data/1750/data-00000-of-00003.arrowAdded+3
data/1750/data-00001-of-00003.arrowAdded+3
data/1750/data-00002-of-00003.arrowAdded+3
extract_data.pyAdded+477
log/extract.logAdded+219
log/problems_1919-1919.txtAdded+68
pd_check/public_domain_data.parquetAdded+3
pd_check/public_domain_files.txtAdded
pd_check/select_pd.pyAdded+523
scrape/da_people_large.parquetAdded+3
scrape/scrape_large.pyAdded+306