Download ocr_metadata/scripts/find_rep_pages.py from chcaa/kb-books: direct link, hf CLI and curl.
- Browser
- Download file 2.75 kB
-
https://huggingface.co/datasets/chcaa/kb-books/resolve/main/ocr_metadata/scripts/find_rep_pages.py
- Command line
-
hf download hf://datasets/chcaa/kb-books/ocr_metadata/scripts/find_rep_pages.py
-
curl -L -o find_rep_pages.py https://huggingface.co/datasets/chcaa/kb-books/resolve/main/ocr_metadata/scripts/find_rep_pages.py
2.75 kB
| import os | |
| import logging | |
| from datasets import Dataset , concatenate_datasets, disable_progress_bars | |
| from tqdm import tqdm | |
| from u_func import * | |
| from page_mix import * | |
| logging.basicConfig(filename="repr_meta.log", | |
| format='%(asctime)s %(levelname)s: %(message)s', | |
| filemode='a') | |
| logger = logging.getLogger() | |
| logger.setLevel(logging.INFO) | |
| def main(): | |
| logger.info("START...") | |
| disable_progress_bars() | |
| #metadata | |
| meta_data = Dataset.from_json("../token_count/meta_data.json") | |
| #separate years | |
| year_list = sorted(list(set(meta_data["published"]))) | |
| for year in tqdm(year_list,desc="YEARS "): | |
| logger.info(f"{year} : ") | |
| year_ds_list = [] | |
| #filter each year | |
| year_meta_data = meta_data.filter(lambda ds,year:ds["published"] == year, num_proc= 10, fn_kwargs={"year":year}) | |
| #separate documents | |
| document_list = sorted(list(set(year_meta_data["file_name"]))) | |
| for document in tqdm(document_list, | |
| leave=False, | |
| desc="DOCS "): | |
| doc_meta_data = year_meta_data.filter(lambda ds,document:ds["file_name"] == document, fn_kwargs={"document":document}) | |
| if len(doc_meta_data)<10: | |
| small_doc = True | |
| else: | |
| small_doc = False | |
| #remove first page (it is a cover by the library, and not part of the ocr) | |
| doc_meta_data = doc_meta_data.filter(lambda ds: ds["page_id"][-3:] != "_p1") | |
| #find the pages which are more representative of the whole ocr | |
| #meaning they have no outlier amount of tokens | |
| doc_toks = list(doc_meta_data["page_text_n_tokens"]) | |
| try: | |
| doc_meta_data = doc_meta_data.filter(representative_pages, | |
| fn_kwargs={"doc_toks":doc_toks, | |
| "column":"page_text_n_tokens"}) | |
| except (EmptyDocumentError,NoMixError,LowProportionError) as e: | |
| logger.error(f"{document} problem, small_doc:{small_doc} ,{e}") | |
| if "EmptyDocumentError" in e.message: | |
| continue | |
| else: | |
| #if no denoizing could be done, mark all pages as representative, the problem is logged | |
| pass | |
| #temporary ds added to to large ds | |
| year_ds_list.append(doc_meta_data) | |
| #save by year | |
| year_ds = concatenate_datasets(year_ds_list) | |
| fp = os.path.join(".","repr_meta",f"{year}_pages.json") | |
| year_ds.to_json(fp) | |
| if __name__ == "__main__": | |
| main() | |