Sync from GitHub via hub-sync
Browse filesFiles changed (25)
- abot-ocr.py+44-4
- deepseek-ocr-vllm.py+44-4
- deepseek-ocr.py+45-5
- deepseek-ocr2-vllm.py+33
- dots-mocr.py+33
- falcon-ocr.py+33
- firered-ocr.py+33
- glm-ocr-v2.py+35
- hunyuan-ocr.py+33
- lfm2-extract.py+34
- lfm2-vl-extract.py+34
- lift-extract.py+34
- lighton-ocr.py+33
- nanonets-ocr.py+49-7
- nuextract3.py+37
- numarkdown-ocr.py+33
- olmocr2-vllm.py+33
- paddleocr-vl-1.5.py+33
- paddleocr-vl-1.6.py+33
- paddleocr-vl.py+33
- pp-doclayout.py+30-1
- qianfan-ocr.py+33
- rolm-ocr.py+33
- smoldocling-ocr.py+33
- unlimited-ocr-vllm.py+33
95 unmodified lines96979899100101156 unmodified lines25825926026126226322 unmodified lines28628728828929029143 unmodified lines3353363373383393403413423431 unmodified line345346347348349350351181 unmodified lines53353453553653753817 unmodified lines55655755855956095 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def post_process_text(text: str, threshold: int = 8000) -> str:"""Trim runaway repetition loops that VLM OCR can fall into on dense pages.156 unmodified linesprivate: bool = False,shuffle: bool = False,seed: int = 42,verbose: bool = False,):"""Process images from a HF dataset through the ABot-OCR model."""22 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")43 unmodified lineslogger.error(f"Error processing batch: {e}")all_markdown.extend(["[OCR FAILED]"] * len(batch_images))# Add markdown column to datasetlogger.info("Adding markdown column to dataset")dataset = dataset.add_column("markdown", all_markdown)# Handle inference_info trackinglogger.info("Updating inference_info...")1 unmodified lineinference_entry = {"model_id": model,"model_name": "ABot-OCR","column_name": "markdown","timestamp": datetime.now().isoformat(),"batch_size": batch_size,"max_tokens": max_tokens,181 unmodified linesdefault=42,help="Random seed for shuffling (default: 42)",)parser.add_argument("--verbose",action="store_true",17 unmodified linesprivate=args.private,shuffle=args.shuffle,seed=args.seed,verbose=args.verbose,)95 unmodified lines96979899100101102103104105106107108109110111112113114115116117118119120121122123156 unmodified lines28028128228328428528628722 unmodified lines31031131231331431531631731843 unmodified lines3623633643653663673683693701 unmodified line372373374375376377378181 unmodified lines56056156256356456556656756856957057157257357457557617 unmodified lines59459559659759859960095 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def post_process_text(text: str, threshold: int = 8000) -> str:"""Trim runaway repetition loops that VLM OCR can fall into on dense pages.156 unmodified linesprivate: bool = False,shuffle: bool = False,seed: int = 42,output_column: str = "markdown",overwrite: bool = False,verbose: bool = False,):"""Process images from a HF dataset through the ABot-OCR model."""22 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")43 unmodified lineslogger.error(f"Error processing batch: {e}")all_markdown.extend(["[OCR FAILED]"] * len(batch_images))# Add output column to datasetlogger.info(f"Adding '{output_column}' column to dataset")dataset = dataset.add_column(output_column, all_markdown)# Handle inference_info trackinglogger.info("Updating inference_info...")1 unmodified lineinference_entry = {"model_id": model,"model_name": "ABot-OCR","column_name": output_column,"timestamp": datetime.now().isoformat(),"batch_size": batch_size,"max_tokens": max_tokens,181 unmodified linesdefault=42,help="Random seed for shuffling (default: 42)",)parser.add_argument("--output-column",default="markdown",help="Column name for the OCR output text (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--verbose",action="store_true",17 unmodified linesprivate=args.private,shuffle=args.shuffle,seed=args.seed,output_column=args.output_column,overwrite=args.overwrite,verbose=args.verbose,)
77 unmodified lines787980818283127 unmodified lines21121221321421521636 unmodified lines25325425525625725867 unmodified lines3263273283293303313323333341 unmodified line336337338339340341342226 unmodified lines56957057157257357419 unmodified lines59459559659759859977 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def to_pil(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:"""Convert various image formats to PIL Image."""if isinstance(image, Image.Image):127 unmodified linesprivate: bool = False,shuffle: bool = False,seed: int = 42,config: str = None,create_pr: bool = False,verbose: bool = False,36 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")67 unmodified linesprocessing_duration = datetime.now() - start_timeprocessing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"# Add markdown column to datasetlogger.info("Adding markdown column to dataset")dataset = dataset.add_column("markdown", all_markdown)# Handle inference_info trackinglogger.info("Updating inference_info...")1 unmodified lineinference_entry = {"model_id": model,"model_name": "DeepSeek-OCR","column_name": "markdown","timestamp": datetime.now().isoformat(),"prompt_mode": prompt_mode if prompt is None else "custom","batch_size": batch_size,226 unmodified linesdefault=42,help="Random seed for shuffling (default: 42)",)parser.add_argument("--verbose",action="store_true",19 unmodified linesprivate=args.private,shuffle=args.shuffle,seed=args.seed,config=args.config,create_pr=args.create_pr,verbose=args.verbose,77 unmodified lines78798081828384858687888990919293949596979899100101102103104105127 unmodified lines23323423523623723823924036 unmodified lines27727827928028128228328428567 unmodified lines3533543553563573583593603611 unmodified line363364365366367368369226 unmodified lines59659759859960060160260360460560660760860961061161219 unmodified lines63263363463563663763863977 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def to_pil(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:"""Convert various image formats to PIL Image."""if isinstance(image, Image.Image):127 unmodified linesprivate: bool = False,shuffle: bool = False,seed: int = 42,output_column: str = "markdown",overwrite: bool = False,config: str = None,create_pr: bool = False,verbose: bool = False,36 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")67 unmodified linesprocessing_duration = datetime.now() - start_timeprocessing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"# Add output column to datasetlogger.info(f"Adding '{output_column}' column to dataset")dataset = dataset.add_column(output_column, all_markdown)# Handle inference_info trackinglogger.info("Updating inference_info...")1 unmodified lineinference_entry = {"model_id": model,"model_name": "DeepSeek-OCR","column_name": output_column,"timestamp": datetime.now().isoformat(),"prompt_mode": prompt_mode if prompt is None else "custom","batch_size": batch_size,226 unmodified linesdefault=42,help="Random seed for shuffling (default: 42)",)parser.add_argument("--output-column",default="markdown",help="Column name for the OCR output text (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--verbose",action="store_true",19 unmodified linesprivate=args.private,shuffle=args.shuffle,seed=args.seed,output_column=args.output_column,overwrite=args.overwrite,config=args.config,create_pr=args.create_pr,verbose=args.verbose,
75 unmodified lines767778798081161 unmodified lines24324424524624724845 unmodified lines29429529629729829979 unmodified lines37938038138238338438538638738838939012 unmodified lines403404405406407408409171 unmodified lines58158258358458558613 unmodified lines60060160260375 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def create_dataset_card(source_dataset: str,model: str,161 unmodified linesprivate: bool = False,shuffle: bool = False,seed: int = 42,):"""Process images from HF dataset through DeepSeek-OCR model."""45 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")79 unmodified linestry:shutil.rmtree(temp_dir)shutil.rmtree(temp_output_dir)except:pass# Add markdown column to datasetlogger.info("Adding markdown column to dataset")dataset = dataset.add_column("markdown", all_markdown)# Handle inference_info trackinglogger.info("Updating inference_info...")12 unmodified lines# Add new inference infonew_info = {"column_name": "markdown","model_id": model,"processing_date": datetime.now().isoformat(),"resolution_mode": resolution_mode,171 unmodified linesdefault=42,help="Random seed for shuffling (default: 42)",)args = parser.parse_args()13 unmodified linesprivate=args.private,shuffle=args.shuffle,seed=args.seed,)75 unmodified lines767778798081828384858687888990919293949596979899100101102103161 unmodified lines26526626726826927027127245 unmodified lines31831932032132232332432532679 unmodified lines40640740840941041141241341441541641712 unmodified lines430431432433434435436171 unmodified lines60860961061161261361461561661761861962062162262362413 unmodified lines63863964064164264375 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def create_dataset_card(source_dataset: str,model: str,161 unmodified linesprivate: bool = False,shuffle: bool = False,seed: int = 42,output_column: str = "markdown",overwrite: bool = False,):"""Process images from HF dataset through DeepSeek-OCR model."""45 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")79 unmodified linestry:shutil.rmtree(temp_dir)shutil.rmtree(temp_output_dir)except Exception:pass# Add output column to datasetlogger.info(f"Adding '{output_column}' column to dataset")dataset = dataset.add_column(output_column, all_markdown)# Handle inference_info trackinglogger.info("Updating inference_info...")12 unmodified lines# Add new inference infonew_info = {"column_name": output_column,"model_id": model,"processing_date": datetime.now().isoformat(),"resolution_mode": resolution_mode,171 unmodified linesdefault=42,help="Random seed for shuffling (default: 42)",)parser.add_argument("--output-column",default="markdown",help="Column name for the OCR output text (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)args = parser.parse_args()13 unmodified linesprivate=args.private,shuffle=args.shuffle,seed=args.seed,output_column=args.output_column,overwrite=args.overwrite,)
85 unmodified lines868788899091133 unmodified lines22522622722822923036 unmodified lines267268269270271272301 unmodified lines57457557657757857940 unmodified lines62062162262362462585 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def to_pil(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:"""Convert various image formats to PIL Image."""if isinstance(image, Image.Image):133 unmodified linesshuffle: bool = False,seed: int = 42,output_column: str = "markdown",config: str = None,create_pr: bool = False,verbose: bool = False,36 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")301 unmodified linesdefault="markdown",help="Column name for OCR output (default: markdown). Use a different name to add alongside existing OCR.",)parser.add_argument("--shuffle",action="store_true",40 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,config=args.config,create_pr=args.create_pr,verbose=args.verbose,85 unmodified lines8687888990919293949596979899100101102103104105106107108109110111112113133 unmodified lines24724824925025125225336 unmodified lines290291292293294295296297298301 unmodified lines60060160260360460560660760860961061140 unmodified lines65265365465565665765885 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def to_pil(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:"""Convert various image formats to PIL Image."""if isinstance(image, Image.Image):133 unmodified linesshuffle: bool = False,seed: int = 42,output_column: str = "markdown",overwrite: bool = False,config: str = None,create_pr: bool = False,verbose: bool = False,36 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")301 unmodified linesdefault="markdown",help="Column name for OCR output (default: markdown). Use a different name to add alongside existing OCR.",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--shuffle",action="store_true",40 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,overwrite=args.overwrite,config=args.config,create_pr=args.create_pr,verbose=args.verbose,
114 unmodified lines115116117118119120160 unmodified lines28128228328428528631 unmodified lines318319320321322323341 unmodified lines66566666766866967041 unmodified lines712713714715716717114 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def make_ocr_message(image: Union[Image.Image, Dict[str, Any], str],prompt: str = PROMPT_TEMPLATES["ocr"],160 unmodified linesprompt_mode: str = "ocr",custom_prompt: str = None,output_column: str = "markdown",config: str = None,create_pr: bool = False,temperature: float = 0.1,31 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")341 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--config",help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",41 unmodified linesprompt_mode=args.prompt_mode,custom_prompt=args.custom_prompt,output_column=args.output_column,config=args.config,create_pr=args.create_pr,temperature=args.temperature,114 unmodified lines115116117118119120121122123124125126127128129130131132133134135136137138139140141142160 unmodified lines30330430530630730830931 unmodified lines341342343344345346347348349341 unmodified lines69169269369469569669769869970070170241 unmodified lines744745746747748749750114 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def make_ocr_message(image: Union[Image.Image, Dict[str, Any], str],prompt: str = PROMPT_TEMPLATES["ocr"],160 unmodified linesprompt_mode: str = "ocr",custom_prompt: str = None,output_column: str = "markdown",overwrite: bool = False,config: str = None,create_pr: bool = False,temperature: float = 0.1,31 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")341 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--config",help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",41 unmodified linesprompt_mode=args.prompt_mode,custom_prompt=args.custom_prompt,output_column=args.output_column,overwrite=args.overwrite,config=args.config,create_pr=args.create_pr,temperature=args.temperature,
73 unmodified lines74757677787965 unmodified lines14514614714814915025 unmodified lines176177178179180181204 unmodified lines38638738838939039132 unmodified lines42442542642742842973 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def prepare_image(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:if isinstance(image, Image.Image):pil_img = image65 unmodified linesshuffle: bool = False,seed: int = 42,output_column: str = "markdown",config: str = None,create_pr: bool = False,compile: bool = True,25 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")if shuffle:logger.info(f"Shuffling dataset with seed {seed}")dataset = dataset.shuffle(seed=seed)204 unmodified lines"--output-column", default="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--config",help="Config/subset name for Hub (for benchmarking multiple models)",32 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,config=args.config,create_pr=args.create_pr,compile=not args.no_compile,73 unmodified lines747576777879808182838485868788899091929394959697989910010165 unmodified lines16716816917017117217325 unmodified lines199200201202203204205206207204 unmodified lines41241341441541641741841942042142242332 unmodified lines45645745845946046146273 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def prepare_image(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:if isinstance(image, Image.Image):pil_img = image65 unmodified linesshuffle: bool = False,seed: int = 42,output_column: str = "markdown",overwrite: bool = False,config: str = None,create_pr: bool = False,compile: bool = True,25 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)if shuffle:logger.info(f"Shuffling dataset with seed {seed}")dataset = dataset.shuffle(seed=seed)204 unmodified lines"--output-column", default="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--config",help="Config/subset name for Hub (for benchmarking multiple models)",32 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,overwrite=args.overwrite,config=args.config,create_pr=args.create_pr,compile=not args.no_compile,
89 unmodified lines909192939495146 unmodified lines24224324424524624720 unmodified lines268269270271272273254 unmodified lines52852953053153253322 unmodified lines55655755855956056189 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def make_ocr_message(image: Union[Image.Image, Dict[str, Any], str],prompt: str = FIRERED_OCR_PROMPT,146 unmodified linesshuffle: bool = False,seed: int = 42,output_column: str = "markdown",config: str = None,create_pr: bool = False,):20 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")254 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--config",help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",22 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,config=args.config,create_pr=args.create_pr,)89 unmodified lines90919293949596979899100101102103104105106107108109110111112113114115116117146 unmodified lines26426526626726826927020 unmodified lines291292293294295296297298299254 unmodified lines55455555655755855956056156256356456522 unmodified lines58858959059159259359489 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def make_ocr_message(image: Union[Image.Image, Dict[str, Any], str],prompt: str = FIRERED_OCR_PROMPT,146 unmodified linesshuffle: bool = False,seed: int = 42,output_column: str = "markdown",overwrite: bool = False,config: str = None,create_pr: bool = False,):20 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")254 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--config",help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",22 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,overwrite=args.overwrite,config=args.config,create_pr=args.create_pr,)
135 unmodified lines136137138139140141244 unmodified lines38638738838939039146 unmodified lines438439440441442443511 unmodified lines95595695795895996038 unmodified lines99910001001100210031004135 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def make_ocr_message(image: Union[Image.Image, Dict[str, Any], str],task: str = "ocr",244 unmodified linesshuffle: bool = False,seed: int = 42,output_column: str = "markdown",verbose: bool = False,config: str = None,create_pr: bool = False,46 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")if shuffle:logger.info(f"Shuffling dataset with seed {seed}")dataset = dataset.shuffle(seed=seed)511 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--verbose",action="store_true",38 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,verbose=args.verbose,config=args.config,create_pr=args.create_pr,135 unmodified lines136137138139140141142143144145146147148149150151152153154155156157158159160161162163244 unmodified lines40840941041141241341446 unmodified lines461462463464465466467468469470471511 unmodified lines98398498598698798898999099199299399438 unmodified lines1033103410351036103710381039135 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def make_ocr_message(image: Union[Image.Image, Dict[str, Any], str],task: str = "ocr",244 unmodified linesshuffle: bool = False,seed: int = 42,output_column: str = "markdown",overwrite: bool = False,verbose: bool = False,config: str = None,create_pr: bool = False,46 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input column.# The incremental path derives batch datasets via dataset.select(...), so dropping# it here (on --overwrite) also keeps those per-batch add_columns clean.dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)if shuffle:logger.info(f"Shuffling dataset with seed {seed}")dataset = dataset.shuffle(seed=seed)511 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--verbose",action="store_true",38 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,overwrite=args.overwrite,verbose=args.verbose,config=args.config,create_pr=args.create_pr,
149 unmodified lines150151152153154155210 unmodified lines36636736836937037137 unmodified lines409410411412413414371 unmodified lines78678778878979079143 unmodified lines835836837838839840149 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def get_prompt(prompt_mode: str,use_chinese: bool = False,210 unmodified linesuse_chinese: bool = False,custom_prompt: str = None,output_column: str = "markdown",clean_output: bool = True,config: str = None,create_pr: bool = False,37 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")371 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--no-clean-output",action="store_true",43 unmodified linesuse_chinese=args.use_chinese_prompts,custom_prompt=args.custom_prompt,output_column=args.output_column,clean_output=not args.no_clean_output,config=args.config,create_pr=args.create_pr,149 unmodified lines150151152153154155156157158159160161162163164165166167168169170171172173174175176177210 unmodified lines38838939039139239339437 unmodified lines432433434435436437438439440371 unmodified lines81281381481581681781881982082182282343 unmodified lines867868869870871872873149 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def get_prompt(prompt_mode: str,use_chinese: bool = False,210 unmodified linesuse_chinese: bool = False,custom_prompt: str = None,output_column: str = "markdown",overwrite: bool = False,clean_output: bool = True,config: str = None,create_pr: bool = False,37 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")371 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--no-clean-output",action="store_true",43 unmodified linesuse_chinese=args.use_chinese_prompts,custom_prompt=args.custom_prompt,output_column=args.output_column,overwrite=args.overwrite,clean_output=not args.no_clean_output,config=args.config,create_pr=args.create_pr,
76 unmodified lines77787980818233 unmodified lines11611711811912012120 unmodified lines142143144145146147109 unmodified lines25725825926026126216 unmodified lines27928028128228328476 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name()}")def load_text_arg(value: str) -> str:"""Resolve --schema (inline text/JSON, URL, or file path) into a string."""text = value.strip()33 unmodified linesschema: str,text_column: str = "text",output_column: str = "extraction",output_format: str = "json",split: str = "train",max_samples: Optional[int] = None,20 unmodified lineslogger.info(f"Loading dataset: {input_dataset} (split={split})")dataset = load_dataset(input_dataset, split=split)if shuffle:dataset = dataset.shuffle(seed=seed)if max_samples:109 unmodified lines)parser.add_argument("--text-column", default="text", help="Text column (default: text)")parser.add_argument("--output-column", default="extraction", help="Output column (default: extraction)")parser.add_argument("--format", dest="output_format", default="json", choices=list(FORMATS),help="Output format (default: json)",16 unmodified linesschema=args.schema,text_column=args.text_column,output_column=args.output_column,output_format=args.output_format,split=args.split,max_samples=args.max_samples,76 unmodified lines777879808182838485868788899091929394959697989910010110210310433 unmodified lines13813914014114214314420 unmodified lines165166167168169170171172173174109 unmodified lines28428528628728828929029129229329429516 unmodified lines31231331431531631731876 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name()}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def load_text_arg(value: str) -> str:"""Resolve --schema (inline text/JSON, URL, or file path) into a string."""text = value.strip()33 unmodified linesschema: str,text_column: str = "text",output_column: str = "extraction",overwrite: bool = False,output_format: str = "json",split: str = "train",max_samples: Optional[int] = None,20 unmodified lineslogger.info(f"Loading dataset: {input_dataset} (split={split})")dataset = load_dataset(input_dataset, split=split)# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)if shuffle:dataset = dataset.shuffle(seed=seed)if max_samples:109 unmodified lines)parser.add_argument("--text-column", default="text", help="Text column (default: text)")parser.add_argument("--output-column", default="extraction", help="Output column (default: extraction)")parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--format", dest="output_format", default="json", choices=list(FORMATS),help="Output format (default: json)",16 unmodified linesschema=args.schema,text_column=args.text_column,output_column=args.output_column,overwrite=args.overwrite,output_format=args.output_format,split=args.split,max_samples=args.max_samples,
79 unmodified lines80818283848566 unmodified lines15215315415515615717 unmodified lines175176177178179180112 unmodified lines29329429529629729812 unmodified lines31131231331431531679 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name()}")def load_schema_arg(value: str) -> Dict[str, str]:"""Resolve --schema (inline JSON, URL, or file path) into a {field: description} dict."""text = value.strip()66 unmodified linesschema: str,image_column: str = "image",output_column: str = "extraction",split: str = "train",max_samples: Optional[int] = None,shuffle: bool = False,17 unmodified lineslogger.info(f"Loading dataset: {input_dataset} (split={split})")dataset = load_dataset(input_dataset, split=split)if shuffle:dataset = dataset.shuffle(seed=seed)if max_samples:112 unmodified lines)parser.add_argument("--image-column", default="image", help="Image column (default: image)")parser.add_argument("--output-column", default="extraction", help="Output column (default: extraction)")parser.add_argument("--split", default="train", help="Dataset split (default: train)")parser.add_argument("--max-samples", type=int, help="Limit number of samples")parser.add_argument("--shuffle", action="store_true", help="Shuffle before sampling")12 unmodified linesschema=args.schema,image_column=args.image_column,output_column=args.output_column,split=args.split,max_samples=args.max_samples,shuffle=args.shuffle,79 unmodified lines808182838485868788899091929394959697989910010110210310410510610766 unmodified lines17417517617717817918017 unmodified lines198199200201202203204205206207112 unmodified lines32032132232332432532632732832933033112 unmodified lines34434534634734834935079 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name()}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def load_schema_arg(value: str) -> Dict[str, str]:"""Resolve --schema (inline JSON, URL, or file path) into a {field: description} dict."""text = value.strip()66 unmodified linesschema: str,image_column: str = "image",output_column: str = "extraction",overwrite: bool = False,split: str = "train",max_samples: Optional[int] = None,shuffle: bool = False,17 unmodified lineslogger.info(f"Loading dataset: {input_dataset} (split={split})")dataset = load_dataset(input_dataset, split=split)# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)if shuffle:dataset = dataset.shuffle(seed=seed)if max_samples:112 unmodified lines)parser.add_argument("--image-column", default="image", help="Image column (default: image)")parser.add_argument("--output-column", default="extraction", help="Output column (default: extraction)")parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--split", default="train", help="Dataset split (default: train)")parser.add_argument("--max-samples", type=int, help="Limit number of samples")parser.add_argument("--shuffle", action="store_true", help="Shuffle before sampling")12 unmodified linesschema=args.schema,image_column=args.image_column,output_column=args.output_column,overwrite=args.overwrite,split=args.split,max_samples=args.max_samples,shuffle=args.shuffle,
110 unmodified lines111112113114115116306 unmodified lines42342442542642742849 unmodified lines478479480481482483220 unmodified lines70470570670770870982 unmodified lines792793794795796797110 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def load_schema_arg(value: str) -> Dict[str, Any]:"""Resolve --schema (inline JSON, a URL, or a file path) into a JSON Schema dict."""text = value.strip()306 unmodified linesimage_column: str = "image",pdf_column: Optional[str] = None,output_column: str = "extraction",method: str = "hf",page_range: Optional[str] = None,split: str = "train",49 unmodified linesf"Column '{source_column}' not found. Available: {dataset.column_names}")sys.exit(1)if shuffle:dataset = dataset.shuffle(seed=seed)if max_samples:220 unmodified linesdefault="extraction",help="Output column (default: extraction)",)parser.add_argument("--method",choices=["hf", "vllm"],82 unmodified linesimage_column=args.image_column,pdf_column=args.pdf_column,output_column=args.output_column,method=args.method,page_range=args.page_range,split=args.split,110 unmodified lines111112113114115116117118119120121122123124125126127128129130131132133134135136137138306 unmodified lines44544644744844945045149 unmodified lines501502503504505506507508509510220 unmodified lines73173273373473573673773873974074174282 unmodified lines825826827828829830831110 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def load_schema_arg(value: str) -> Dict[str, Any]:"""Resolve --schema (inline JSON, a URL, or a file path) into a JSON Schema dict."""text = value.strip()306 unmodified linesimage_column: str = "image",pdf_column: Optional[str] = None,output_column: str = "extraction",overwrite: bool = False,method: str = "hf",page_range: Optional[str] = None,split: str = "train",49 unmodified linesf"Column '{source_column}' not found. Available: {dataset.column_names}")sys.exit(1)# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)if shuffle:dataset = dataset.shuffle(seed=seed)if max_samples:220 unmodified linesdefault="extraction",help="Output column (default: extraction)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--method",choices=["hf", "vllm"],82 unmodified linesimage_column=args.image_column,pdf_column=args.pdf_column,output_column=args.output_column,overwrite=args.overwrite,method=args.method,page_range=args.page_range,split=args.split,
84 unmodified lines858687888990204 unmodified lines29529629729829930026 unmodified lines327328329330331332292 unmodified lines62562662762862963017 unmodified lines64864965065184 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def resize_image_to_target(image: Image.Image, target_size: int = 1540) -> Image.Image:"""Resize image so longest dimension is target_size while maintaining aspect ratio.204 unmodified linesshuffle: bool = False,seed: int = 42,output_column: str = "markdown",):"""Process images from HF dataset through LightOnOCR model."""26 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")292 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)args = parser.parse_args()17 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,)84 unmodified lines858687888990919293949596979899100101102103104105106107108109110111112204 unmodified lines31731831932032132232326 unmodified lines350351352353354355356357358292 unmodified lines65165265365465565665765865966066166217 unmodified lines68068168268368484 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def resize_image_to_target(image: Image.Image, target_size: int = 1540) -> Image.Image:"""Resize image so longest dimension is target_size while maintaining aspect ratio.204 unmodified linesshuffle: bool = False,seed: int = 42,output_column: str = "markdown",overwrite: bool = False,):"""Process images from HF dataset through LightOnOCR model."""26 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")292 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)args = parser.parse_args()17 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,overwrite=args.overwrite,)
60 unmodified lines616263646566141 unmodified lines2082092102112122132142 unmodified lines21721821922022122222 unmodified lines24524624724824925050 unmodified lines3013023033043053063073083091 unmodified line311312313314315316317148 unmodified lines46646746846947047147247330 unmodified lines50450550650750850917 unmodified lines52752852953053160 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def make_ocr_message(image: Union[Image.Image, Dict[str, Any], str],prompt: str = "Extract the text from the above document as if you were reading it naturally. Return the tables in html format. Return the equations in LaTeX representation. If there is an image in the document and image caption is not present, add a small description of the image inside the <img></img> tag; otherwise, add the image caption inside <img></img>. Watermarks should be wrapped in brackets. Ex: <watermark>OFFICIAL COPY</watermark>. Page numbers should be wrapped in brackets. Ex: <page_number>14</page_number> or <page_number>9/22</page_number>. Prefer using ☐ and ☑ for check boxes.",141 unmodified linesimage_column: str = "image",batch_size: int = 32,model: str = "nanonets/Nanonets-OCR-s",max_model_len: int = 8192,max_tokens: int = 15000,gpu_memory_utilization: float = 0.8,hf_token: str = None,2 unmodified linesprivate: bool = False,shuffle: bool = False,seed: int = 42,verbose: bool = False,):"""Process images from HF dataset through OCR model."""22 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")50 unmodified lines# Add error placeholders for failed batchall_markdown.extend(["[OCR FAILED]"] * len(batch_images))# Add markdown column to datasetlogger.info("Adding markdown column to dataset")dataset = dataset.add_column("markdown", all_markdown)# Handle inference_info trackinglogger.info("Updating inference_info...")1 unmodified lineinference_entry = {"model_id": model,"model_name": "Nanonets-OCR-s","column_name": "markdown","timestamp": datetime.now().isoformat(),"batch_size": batch_size,"max_tokens": max_tokens,148 unmodified linesparser.add_argument("--max-model-len",type=int,default=8192,help="Maximum model context length (default: 8192)",)parser.add_argument("--max-tokens",30 unmodified linesdefault=42,help="Random seed for shuffling (default: 42)",)parser.add_argument("--verbose",action="store_true",17 unmodified linesprivate=args.private,shuffle=args.shuffle,seed=args.seed,verbose=args.verbose,)60 unmodified lines61626364656667686970717273747576777879808182838485868788141 unmodified lines2302312322332342352362 unmodified lines23924024124224324424524622 unmodified lines26927027127227327427527627750 unmodified lines3283293303313323333343353361 unmodified line338339340341342343344148 unmodified lines49349449549649749849950050150230 unmodified lines53353453553653753853954054154254354454554654754854917 unmodified lines56756856957057157257360 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def make_ocr_message(image: Union[Image.Image, Dict[str, Any], str],prompt: str = "Extract the text from the above document as if you were reading it naturally. Return the tables in html format. Return the equations in LaTeX representation. If there is an image in the document and image caption is not present, add a small description of the image inside the <img></img> tag; otherwise, add the image caption inside <img></img>. Watermarks should be wrapped in brackets. Ex: <watermark>OFFICIAL COPY</watermark>. Page numbers should be wrapped in brackets. Ex: <page_number>14</page_number> or <page_number>9/22</page_number>. Prefer using ☐ and ☑ for check boxes.",141 unmodified linesimage_column: str = "image",batch_size: int = 32,model: str = "nanonets/Nanonets-OCR-s",max_model_len: int = 32768,max_tokens: int = 15000,gpu_memory_utilization: float = 0.8,hf_token: str = None,2 unmodified linesprivate: bool = False,shuffle: bool = False,seed: int = 42,output_column: str = "markdown",overwrite: bool = False,verbose: bool = False,):"""Process images from HF dataset through OCR model."""22 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")50 unmodified lines# Add error placeholders for failed batchall_markdown.extend(["[OCR FAILED]"] * len(batch_images))# Add output column to datasetlogger.info(f"Adding '{output_column}' column to dataset")dataset = dataset.add_column(output_column, all_markdown)# Handle inference_info trackinglogger.info("Updating inference_info...")1 unmodified lineinference_entry = {"model_id": model,"model_name": "Nanonets-OCR-s","column_name": output_column,"timestamp": datetime.now().isoformat(),"batch_size": batch_size,"max_tokens": max_tokens,148 unmodified linesparser.add_argument("--max-model-len",type=int,default=32768,help="Maximum model context length (default: 32768; must exceed --max-tokens ""15000 plus the image/prompt tokens — the old 8192 default couldn't hold the ""output budget). Model max is 128k, so there's ample room.",)parser.add_argument("--max-tokens",30 unmodified linesdefault=42,help="Random seed for shuffling (default: 42)",)parser.add_argument("--output-column",default="markdown",help="Column name for the OCR output text (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--verbose",action="store_true",17 unmodified linesprivate=args.private,shuffle=args.shuffle,seed=args.seed,output_column=args.output_column,overwrite=args.overwrite,verbose=args.verbose,)
92 unmodified lines939495969798196 unmodified lines29529629729829930031 unmodified lines332333334335336337375 unmodified lines71371471571671771824 unmodified lines74374474574674774892 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def load_template_arg(value: Optional[str]) -> Optional[Dict[str, Any]]:"""Load a NuExtract template/JSON Schema from inline JSON, a URL, or a file path."""if value is None:196 unmodified linesshuffle: bool = False,seed: int = 42,output_column: Optional[str] = None,verbose: bool = False,config: str = None,create_pr: bool = False,31 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")if shuffle:logger.info(f"Shuffling dataset with seed {seed}")dataset = dataset.shuffle(seed=seed)375 unmodified linesdefault=None,help="Column name for output (default: 'markdown' in OCR mode, 'extraction' in template mode)",)parser.add_argument("--verbose",action="store_true",24 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,verbose=args.verbose,config=args.config,create_pr=args.create_pr,92 unmodified lines93949596979899100101102103104105106107108109110111112113114115116117118119120196 unmodified lines31731831932032132232331 unmodified lines355356357358359360361362363364365366367375 unmodified lines74374474574674774874975075175275375424 unmodified lines77978078178278378478592 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def load_template_arg(value: Optional[str]) -> Optional[Dict[str, Any]]:"""Load a NuExtract template/JSON Schema from inline JSON, a URL, or a file path."""if value is None:196 unmodified linesshuffle: bool = False,seed: int = 42,output_column: Optional[str] = None,overwrite: bool = False,verbose: bool = False,config: str = None,create_pr: bool = False,31 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if an output column would collide with an existing input column.# With --enable-thinking the script also writes "{output_column}_reasoning".out_cols = [output_column]if enable_thinking:out_cols.append(f"{output_column}_reasoning")dataset = ensure_output_columns_free(dataset, out_cols, overwrite=overwrite)if shuffle:logger.info(f"Shuffling dataset with seed {seed}")dataset = dataset.shuffle(seed=seed)375 unmodified linesdefault=None,help="Column name for output (default: 'markdown' in OCR mode, 'extraction' in template mode)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--verbose",action="store_true",24 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,overwrite=args.overwrite,verbose=args.verbose,config=args.config,create_pr=args.create_pr,
74 unmodified lines757677787980236 unmodified lines31731831932032132238 unmodified lines361362363364365366333 unmodified lines70070170270370470531 unmodified lines73773873974074174274 unmodified linesreturn num_gpusdef validate_and_resize_image(image: Image.Image,min_pixels: int = 100 * 28 * 28,236 unmodified linestemperature: float = 0.0,custom_prompt: Optional[str] = None,output_column: str = "markdown",config: str = None,create_pr: bool = False,verbose: bool = False,38 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")333 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--config",help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",31 unmodified linestemperature=args.temperature,custom_prompt=args.custom_prompt,output_column=args.output_column,config=args.config,create_pr=args.create_pr,verbose=args.verbose,74 unmodified lines75767778798081828384858687888990919293949596979899100101102236 unmodified lines33934034134234334434538 unmodified lines384385386387388389390391392333 unmodified lines72672772872973073173273373473573673731 unmodified lines76977077177277377477574 unmodified linesreturn num_gpusdef ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def validate_and_resize_image(image: Image.Image,min_pixels: int = 100 * 28 * 28,236 unmodified linestemperature: float = 0.0,custom_prompt: Optional[str] = None,output_column: str = "markdown",overwrite: bool = False,config: str = None,create_pr: bool = False,verbose: bool = False,38 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")333 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--config",help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",31 unmodified linestemperature=args.temperature,custom_prompt=args.custom_prompt,output_column=args.output_column,overwrite=args.overwrite,config=args.config,create_pr=args.create_pr,verbose=args.verbose,
80 unmodified lines818283848586193 unmodified lines28028128228328428547 unmodified lines333334335336337338219 unmodified lines55855956056156256371 unmodified lines63563663763863964080 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def parse_yaml_frontmatter(text: str) -> tuple[dict, str]:"""Parse YAML front matter from olmOCR output.193 unmodified linesoutput_dataset: str,image_column: str = "image",output_column: str = "markdown",batch_size: int = 16,model: str = "allenai/olmOCR-2-7B-1025-FP8",max_model_len: int = 16384,47 unmodified lineslogger.info(f"Loading dataset: {input_dataset}")ds = load_dataset(input_dataset, split=split)# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")219 unmodified linesdefault="markdown",help="Column name for markdown output (default: markdown)",)parser.add_argument("--batch-size",type=int,71 unmodified linesoutput_dataset=args.output_dataset,image_column=args.image_column,output_column=args.output_column,batch_size=args.batch_size,model=args.model,max_model_len=args.max_model_len,80 unmodified lines81828384858687888990919293949596979899100101102103104105106107108193 unmodified lines30230330430530630730847 unmodified lines356357358359360361362363364219 unmodified lines58458558658758858959059159259359459571 unmodified lines66766866967067167267380 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def parse_yaml_frontmatter(text: str) -> tuple[dict, str]:"""Parse YAML front matter from olmOCR output.193 unmodified linesoutput_dataset: str,image_column: str = "image",output_column: str = "markdown",overwrite: bool = False,batch_size: int = 16,model: str = "allenai/olmOCR-2-7B-1025-FP8",max_model_len: int = 16384,47 unmodified lineslogger.info(f"Loading dataset: {input_dataset}")ds = load_dataset(input_dataset, split=split)# Fail fast if the output column would collide with an existing input columnds = ensure_output_columns_free(ds, [output_column], overwrite=overwrite)# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")219 unmodified linesdefault="markdown",help="Column name for markdown output (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--batch-size",type=int,71 unmodified linesoutput_dataset=args.output_dataset,image_column=args.image_column,output_column=args.output_column,overwrite=args.overwrite,batch_size=args.batch_size,model=args.model,max_model_len=args.max_model_len,
100 unmodified lines101102103104105106175 unmodified lines28228328428528628730 unmodified lines318319320321322323317 unmodified lines64164264364464564624 unmodified lines671672673674675676100 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def prepare_image(image: Union[Image.Image, Dict[str, Any], str],) -> Image.Image:175 unmodified linesshuffle: bool = False,seed: int = 42,output_column: str = "markdown",config: str = None,create_pr: bool = False,verbose: bool = False,30 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")317 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--config",help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",24 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,config=args.config,create_pr=args.create_pr,verbose=args.verbose,100 unmodified lines101102103104105106107108109110111112113114115116117118119120121122123124125126127128175 unmodified lines30430530630730830931030 unmodified lines341342343344345346347348349317 unmodified lines66766866967067167267367467567667767824 unmodified lines703704705706707708709100 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def prepare_image(image: Union[Image.Image, Dict[str, Any], str],) -> Image.Image:175 unmodified linesshuffle: bool = False,seed: int = 42,output_column: str = "markdown",overwrite: bool = False,config: str = None,create_pr: bool = False,verbose: bool = False,30 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")317 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--config",help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",24 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,overwrite=args.overwrite,config=args.config,create_pr=args.create_pr,verbose=args.verbose,
103 unmodified lines104105106107108109252 unmodified lines36236336436536636737 unmodified lines405406407408409410346 unmodified lines75775875976076176229 unmodified lines792793794795796797103 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def smart_resize(height: int,width: int,252 unmodified linesshuffle: bool = False,seed: int = 42,output_column: str = None,config: str = None,create_pr: bool = False,verbose: bool = False,37 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")346 unmodified lines"--output-column",help="Column name for output (default: markdown)",)parser.add_argument("--config",help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",29 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,config=args.config,create_pr=args.create_pr,verbose=args.verbose,103 unmodified lines104105106107108109110111112113114115116117118119120121122123124125126127128129130131252 unmodified lines38438538638738838939037 unmodified lines428429430431432433434435436346 unmodified lines78378478578678778878979079179279379429 unmodified lines824825826827828829830103 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def smart_resize(height: int,width: int,252 unmodified linesshuffle: bool = False,seed: int = 42,output_column: str = None,overwrite: bool = False,config: str = None,create_pr: bool = False,verbose: bool = False,37 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")346 unmodified lines"--output-column",help="Column name for output (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--config",help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",29 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,overwrite=args.overwrite,config=args.config,create_pr=args.create_pr,verbose=args.verbose,
92 unmodified lines939495969798238 unmodified lines33733833934034134242 unmodified lines385386387388389390315 unmodified lines70670770870971071120 unmodified lines73273373473573692 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def smart_resize(height: int,width: int,238 unmodified linesshuffle: bool = False,seed: int = 42,output_column: str = None,verbose: bool = False,):"""Process images from HF dataset through PaddleOCR-VL model."""42 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")315 unmodified lines"--output-column",help="Column name for output (default: markdown)",)parser.add_argument("--verbose",action="store_true",20 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,verbose=args.verbose,)92 unmodified lines93949596979899100101102103104105106107108109110111112113114115116117118119120238 unmodified lines35936036136236336436542 unmodified lines408409410411412413414415416315 unmodified lines73273373473573673773873974074174274320 unmodified lines76476576676776876992 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def smart_resize(height: int,width: int,238 unmodified linesshuffle: bool = False,seed: int = 42,output_column: str = None,overwrite: bool = False,verbose: bool = False,):"""Process images from HF dataset through PaddleOCR-VL model."""42 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")315 unmodified lines"--output-column",help="Column name for output (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--verbose",action="store_true",20 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,overwrite=args.overwrite,verbose=args.verbose,)
432 unmodified lines4334344354364374382 unmodified lines44144244344444544629 unmodified lines476477478479480481482408 unmodified lines89189289389489589614 unmodified lines911912913914915916246 unmodified lines116311641165116611671168432 unmodified linescreate_pr: bool,source_id: str,original_dataset=None,):self.repo_id = repo_idself.hf_token = hf_token2 unmodified linesself.create_pr = create_prself.source_id = source_idself.original_dataset = original_dataset# Used when original_dataset is None: row-by-row buffer.self._rows: List[Dict[str, Any]] = []# Used when original_dataset is set: ordered layouts aligned with dataset rows.29 unmodified lines# Pad to keep add_column happy.while len(self._layouts) < len(self.original_dataset):self._layouts.append("[]")ds = self.original_dataset.add_column("layout", self._layouts)else:if not self._rows:logger.warning("No rows produced; nothing to push.")408 unmodified linesseed=args.seed,max_samples=args.max_samples,)# ---------- sink ----------if is_bucket_url(args.output_target):14 unmodified linescreate_pr=args.create_pr,source_id=args.input_source,original_dataset=original_dataset,)completed = sink.already_done()246 unmodified linesaction="store_true",help="Create PR instead of direct push (dataset sink only)",)# Bucket-sink-specificp.add_argument("--shard-size",432 unmodified lines4334344354364374384392 unmodified lines44244344444544644744829 unmodified lines478479480481482483484485486487488489490491492493408 unmodified lines90290390490590690790890991091191291391491591691791814 unmodified lines933934935936937938939246 unmodified lines118611871188118911901191119211931194119511961197432 unmodified linescreate_pr: bool,source_id: str,original_dataset=None,overwrite: bool = False,):self.repo_id = repo_idself.hf_token = hf_token2 unmodified linesself.create_pr = create_prself.source_id = source_idself.original_dataset = original_datasetself.overwrite = overwrite# Used when original_dataset is None: row-by-row buffer.self._rows: List[Dict[str, Any]] = []# Used when original_dataset is set: ordered layouts aligned with dataset rows.29 unmodified lines# Pad to keep add_column happy.while len(self._layouts) < len(self.original_dataset):self._layouts.append("[]")base = self.original_datasetif "layout" in base.column_names:if not self.overwrite:raise ValueError("Output column 'layout' already exists in the input dataset; ""pass --overwrite to replace it.")logger.warning("--overwrite: replacing existing column 'layout'")base = base.remove_columns("layout")ds = base.add_column("layout", self._layouts)else:if not self._rows:logger.warning("No rows produced; nothing to push.")408 unmodified linesseed=args.seed,max_samples=args.max_samples,)# Fail fast, before minutes of inference, if the 'layout' output column would# collide with an existing input column. --overwrite opts in to replacing it.if original_dataset is not None and "layout" in original_dataset.column_names:if not args.overwrite:logger.error("Output column 'layout' already exists in the input dataset "f"(columns: {original_dataset.column_names}).")logger.error("Pass --overwrite to replace it.")sys.exit(1)logger.warning("--overwrite: will replace existing column 'layout'")# ---------- sink ----------if is_bucket_url(args.output_target):14 unmodified linescreate_pr=args.create_pr,source_id=args.input_source,original_dataset=original_dataset,overwrite=args.overwrite,)completed = sink.already_done()246 unmodified linesaction="store_true",help="Create PR instead of direct push (dataset sink only)",)p.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)# Bucket-sink-specificp.add_argument("--shard-size",
76 unmodified lines777879808182154 unmodified lines23723823924024124233 unmodified lines276277278279280281306 unmodified lines58858959059159259332 unmodified lines62662762862963063176 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def extract_content_from_thinking(text: str, include_thinking: bool = False) -> str:"""Extract final content from Qianfan-OCR's Layout-as-Thought output.154 unmodified linesinclude_thinking: bool = False,custom_prompt: str = None,output_column: str = "markdown",config: str = None,create_pr: bool = False,verbose: bool = False,33 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")if shuffle:logger.info(f"Shuffling dataset with seed {seed}")dataset = dataset.shuffle(seed=seed)306 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--config",help="Config/subset name when pushing to Hub (for benchmarking multiple models)",32 unmodified linesinclude_thinking=args.include_thinking,custom_prompt=args.custom_prompt,output_column=args.output_column,config=args.config,create_pr=args.create_pr,verbose=args.verbose,76 unmodified lines7778798081828384858687888990919293949596979899100101102103104154 unmodified lines25926026126226326426533 unmodified lines299300301302303304305306307306 unmodified lines61461561661761861962062162262362462532 unmodified lines65865966066166266366476 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def extract_content_from_thinking(text: str, include_thinking: bool = False) -> str:"""Extract final content from Qianfan-OCR's Layout-as-Thought output.154 unmodified linesinclude_thinking: bool = False,custom_prompt: str = None,output_column: str = "markdown",overwrite: bool = False,config: str = None,create_pr: bool = False,verbose: bool = False,33 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)if shuffle:logger.info(f"Shuffling dataset with seed {seed}")dataset = dataset.shuffle(seed=seed)306 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--config",help="Config/subset name when pushing to Hub (for benchmarking multiple models)",32 unmodified linesinclude_thinking=args.include_thinking,custom_prompt=args.custom_prompt,output_column=args.output_column,overwrite=args.overwrite,config=args.config,create_pr=args.create_pr,verbose=args.verbose,
60 unmodified lines616263646566142 unmodified lines20921021121221321428 unmodified lines243244245246247248253 unmodified lines50250350450550650727 unmodified lines53553653753853954060 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def make_ocr_message(image: Union[Image.Image, Dict[str, Any], str],prompt: str = "Return the plain text representation of this document as if you were reading it naturally.\n",142 unmodified linesmax_samples: int = None,private: bool = False,output_column: str = None,shuffle: bool = False,seed: int = 42,verbose: bool = False,28 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")253 unmodified linesdefault=None,help="Name of the output column for extracted text (default: markdown)",)parser.add_argument("--shuffle",action="store_true",27 unmodified linesmax_samples=args.max_samples,private=args.private,output_column=args.output_column,shuffle=args.shuffle,seed=args.seed,verbose=args.verbose,60 unmodified lines61626364656667686970717273747576777879808182838485868788142 unmodified lines23123223323423523623728 unmodified lines266267268269270271272273274253 unmodified lines52852953053153253353453553653753853927 unmodified lines56756856957057157257360 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def make_ocr_message(image: Union[Image.Image, Dict[str, Any], str],prompt: str = "Return the plain text representation of this document as if you were reading it naturally.\n",142 unmodified linesmax_samples: int = None,private: bool = False,output_column: str = None,overwrite: bool = False,shuffle: bool = False,seed: int = 42,verbose: bool = False,28 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")253 unmodified linesdefault=None,help="Name of the output column for extracted text (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--shuffle",action="store_true",27 unmodified linesmax_samples=args.max_samples,private=args.private,output_column=args.output_column,overwrite=args.overwrite,shuffle=args.shuffle,seed=args.seed,verbose=args.verbose,
64 unmodified lines656667686970157 unmodified lines22822923023123223325 unmodified lines259260261262263264306 unmodified lines57157257357457557647 unmodified lines62462562662762862964 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def prepare_llm_input(image: Union[Image.Image, Dict[str, Any], str],prompt_text: str = "Convert page to Docling.",157 unmodified linesmax_samples: int = None,private: bool = False,output_column: str = "markdown",output_format: str = "markdown",shuffle: bool = False,seed: int = 42,25 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Validate output formatif output_format not in ["markdown", "doctags"]:raise ValueError(306 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--output-format",default="markdown",47 unmodified linesmax_samples=args.max_samples,private=args.private,output_column=args.output_column,output_format=args.output_format,shuffle=args.shuffle,seed=args.seed,64 unmodified lines65666768697071727374757677787980818283848586878889909192157 unmodified lines25025125225325425525625 unmodified lines282283284285286287288289290306 unmodified lines59759859960060160260360460560660760847 unmodified lines65665765865966066166264 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def prepare_llm_input(image: Union[Image.Image, Dict[str, Any], str],prompt_text: str = "Convert page to Docling.",157 unmodified linesmax_samples: int = None,private: bool = False,output_column: str = "markdown",overwrite: bool = False,output_format: str = "markdown",shuffle: bool = False,seed: int = 42,25 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)# Validate output formatif output_format not in ["markdown", "doctags"]:raise ValueError(306 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--output-format",default="markdown",47 unmodified linesmax_samples=args.max_samples,private=args.private,output_column=args.output_column,overwrite=args.overwrite,output_format=args.output_format,shuffle=args.shuffle,seed=args.seed,
99 unmodified lines10010110210310410589 unmodified lines19519619719819920027 unmodified lines228229230231232233222 unmodified lines45645745845946046164 unmodified lines52652752852953053199 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def to_pil(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:"""Convert various dataset image cell formats to an RGB PIL image."""if isinstance(image, Image.Image):89 unmodified linesmodel: str = MODEL,image_column: str = "image",output_column: str = "markdown",grounding_column: Optional[str] = None,batch_size: int = 8,max_model_len: int = 32768,27 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")if shuffle:logger.info(f"Shuffling dataset with seed {seed}")dataset = dataset.shuffle(seed=seed)222 unmodified linesdefault="markdown",help="Output column name (default: markdown)",)parser.add_argument("--strip-grounding",action="store_true",64 unmodified linesmodel=args.model,image_column=args.image_column,output_column=args.output_column,grounding_column=args.grounding_column,batch_size=args.batch_size,max_model_len=args.max_model_len,99 unmodified lines10010110210310410510610710810911011111211311411511611711811912012112212312412512612789 unmodified lines21721821922022122222327 unmodified lines251252253254255256257258259222 unmodified lines48248348448548648748848949049149249364 unmodified lines55855956056156256356499 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def ensure_output_columns_free(dataset, columns, overwrite=False):"""Fail fast if an output column would collide with an existing input column.Adding a column that already exists silently overwrites it (e.g. a ground-truth`text`/`markdown` column) or crashes on push with a duplicate-column error only*after* inference has run. Catch it up front. With overwrite=True, drop the clashingcolumn(s) here instead (logged) so the later add_column is clean."""clash = [c for c in columns if c in dataset.column_names]if not clash:return datasetif overwrite:logger.warning(f"--overwrite: replacing existing column(s) {clash}")return dataset.remove_columns(clash)logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)def to_pil(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:"""Convert various dataset image cell formats to an RGB PIL image."""if isinstance(image, Image.Image):89 unmodified linesmodel: str = MODEL,image_column: str = "image",output_column: str = "markdown",overwrite: bool = False,grounding_column: Optional[str] = None,batch_size: int = 8,max_model_len: int = 32768,27 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)if shuffle:logger.info(f"Shuffling dataset with seed {seed}")dataset = dataset.shuffle(seed=seed)222 unmodified linesdefault="markdown",help="Output column name (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--strip-grounding",action="store_true",64 unmodified linesmodel=args.model,image_column=args.image_column,output_column=args.output_column,overwrite=args.overwrite,grounding_column=args.grounding_column,batch_size=args.batch_size,max_model_len=args.max_model_len,
abot-ocr.py+44-4
deepseek-ocr-vllm.py+44-4
deepseek-ocr.py+45-5
deepseek-ocr2-vllm.py+33
dots-mocr.py+33
falcon-ocr.py+33
firered-ocr.py+33
glm-ocr-v2.py+35
hunyuan-ocr.py+33
lfm2-extract.py+34
lfm2-vl-extract.py+34
lift-extract.py+34
lighton-ocr.py+33
nanonets-ocr.py+49-7
nuextract3.py+37
numarkdown-ocr.py+33
olmocr2-vllm.py+33
paddleocr-vl-1.5.py+33
paddleocr-vl-1.6.py+33
paddleocr-vl.py+33
pp-doclayout.py+30-1
qianfan-ocr.py+33
rolm-ocr.py+33
smoldocling-ocr.py+33
unlimited-ocr-vllm.py+33