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 lines96979899100101102103104105106107108109110111112113114115116117118119120121122123156 unmodified lines28028128228328428528628722 unmodified lines31031131231331431531631731843 unmodified lines3623633643383393403653663673683693701 unmodified line372373374348375376377378181 unmodified lines56056156256356456556656756856957057157257357457557617 unmodified lines59459559659759859960095 unmodified lines logger.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 clashing column(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 dataset if 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 lines private: 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 lines f"Column '{image_column}' not found. Available: {dataset.column_names}" )
# Fail fast if the output column would collide with an existing input column dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
# Shuffle if requested if shuffle: logger.info(f"Shuffling dataset with seed {seed}")43 unmodified lines logger.error(f"Error processing batch: {e}") all_markdown.extend(["[OCR FAILED]"] * len(batch_images))
# Add markdown column to dataset logger.info("Adding markdown column to dataset") dataset = dataset.add_column("markdown", all_markdown) # Add output column to dataset logger.info(f"Adding '{output_column}' column to dataset") dataset = dataset.add_column(output_column, all_markdown)
# Handle inference_info tracking logger.info("Updating inference_info...")1 unmodified line inference_entry = { "model_id": model, "model_name": "ABot-OCR", "column_name": "markdown", "column_name": output_column, "timestamp": datetime.now().isoformat(), "batch_size": batch_size, "max_tokens": max_tokens,181 unmodified lines default=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 lines private=args.private, shuffle=args.shuffle, seed=args.seed, output_column=args.output_column, overwrite=args.overwrite, verbose=args.verbose, )77 unmodified lines78798081828384858687888990919293949596979899100101102103104105127 unmodified lines23323423523623723823924036 unmodified lines27727827928028128228328428567 unmodified lines3533543553293303313563573583593603611 unmodified line363364365339366367368369226 unmodified lines59659759859960060160260360460560660760860961061161219 unmodified lines63263363463563663763863977 unmodified lines logger.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 clashing column(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 dataset if 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 lines private: 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 lines f"Column '{image_column}' not found. Available: {dataset.column_names}" )
# Fail fast if the output column would collide with an existing input column dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
# Shuffle if requested if shuffle: logger.info(f"Shuffling dataset with seed {seed}")67 unmodified lines processing_duration = datetime.now() - start_time processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
# Add markdown column to dataset logger.info("Adding markdown column to dataset") dataset = dataset.add_column("markdown", all_markdown) # Add output column to dataset logger.info(f"Adding '{output_column}' column to dataset") dataset = dataset.add_column(output_column, all_markdown)
# Handle inference_info tracking logger.info("Updating inference_info...")1 unmodified line inference_entry = { "model_id": model, "model_name": "DeepSeek-OCR", "column_name": "markdown", "column_name": output_column, "timestamp": datetime.now().isoformat(), "prompt_mode": prompt_mode if prompt is None else "custom", "batch_size": batch_size,226 unmodified lines default=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 lines private=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 lines767778798081828384858687888990919293949596979899100101102103161 unmodified lines26526626726826927027127245 unmodified lines31831932032132232332432532679 unmodified lines40640740838240941041138538638741241341441541641712 unmodified lines430431432406433434435436171 unmodified lines60860961061161261361461561661761861962062162262362413 unmodified lines63863964064164264375 unmodified lines logger.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 clashing column(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 dataset if 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 lines private: 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 lines f"Column '{image_column}' not found. Available: {dataset.column_names}" )
# Fail fast if the output column would collide with an existing input column dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
# Shuffle if requested if shuffle: logger.info(f"Shuffling dataset with seed {seed}")79 unmodified lines try: shutil.rmtree(temp_dir) shutil.rmtree(temp_output_dir) except: except Exception: pass
# Add markdown column to dataset logger.info("Adding markdown column to dataset") dataset = dataset.add_column("markdown", all_markdown) # Add output column to dataset logger.info(f"Adding '{output_column}' column to dataset") dataset = dataset.add_column(output_column, all_markdown)
# Handle inference_info tracking logger.info("Updating inference_info...")12 unmodified lines
# Add new inference info new_info = { "column_name": "markdown", "column_name": output_column, "model_id": model, "processing_date": datetime.now().isoformat(), "resolution_mode": resolution_mode,171 unmodified lines default=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 lines private=args.private, shuffle=args.shuffle, seed=args.seed, output_column=args.output_column, overwrite=args.overwrite, )85 unmodified lines8687888990919293949596979899100101102103104105106107108109110111112113133 unmodified lines24724824925025125225336 unmodified lines290291292293294295296297298301 unmodified lines60060160260360460560660760860961061140 unmodified lines65265365465565665765885 unmodified lines logger.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 clashing column(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 dataset if 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 lines 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 lines f"Column '{image_column}' not found. Available: {dataset.column_names}" )
# Fail fast if the output column would collide with an existing input column dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
# Shuffle if requested if shuffle: logger.info(f"Shuffling dataset with seed {seed}")301 unmodified lines default="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 lines 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,114 unmodified lines115116117118119120121122123124125126127128129130131132133134135136137138139140141142160 unmodified lines30330430530630730830931 unmodified lines341342343344345346347348349341 unmodified lines69169269369469569669769869970070170241 unmodified lines744745746747748749750114 unmodified lines logger.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 clashing column(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 dataset if 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 lines prompt_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 lines f"Column '{image_column}' not found. Available: {dataset.column_names}" )
# Fail fast if the output column would collide with an existing input column dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
# Shuffle if requested if shuffle: logger.info(f"Shuffling dataset with seed {seed}")341 unmodified lines 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 when pushing to Hub (for benchmarking multiple models in one repo)",41 unmodified lines prompt_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 lines747576777879808182838485868788899091929394959697989910010165 unmodified lines16716816917017117217325 unmodified lines199200201202203204205206207204 unmodified lines41241341441541641741841942042142242332 unmodified lines45645745845946046146273 unmodified lines logger.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 clashing column(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 dataset if 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 lines shuffle: bool = False, seed: int = 42, output_column: str = "markdown", overwrite: bool = False, config: str = None, create_pr: bool = False, compile: bool = True,25 unmodified lines f"Column '{image_column}' not found. Available: {dataset.column_names}" )
# Fail fast if the output column would collide with an existing input column 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)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 lines shuffle=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 lines90919293949596979899100101102103104105106107108109110111112113114115116117146 unmodified lines26426526626726826927020 unmodified lines291292293294295296297298299254 unmodified lines55455555655755855956056156256356456522 unmodified lines58858959059159259359489 unmodified lines logger.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 clashing column(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 dataset if 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 lines shuffle: bool = False, seed: int = 42, output_column: str = "markdown", overwrite: bool = False, config: str = None, create_pr: bool = False,):20 unmodified lines f"Column '{image_column}' not found. Available: {dataset.column_names}" )
# Fail fast if the output column would collide with an existing input column dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
# Shuffle if requested if shuffle: logger.info(f"Shuffling dataset with seed {seed}")254 unmodified lines 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 when pushing to Hub (for benchmarking multiple models in one repo)",22 unmodified lines shuffle=args.shuffle, seed=args.seed, output_column=args.output_column, overwrite=args.overwrite, config=args.config, create_pr=args.create_pr, )135 unmodified lines136137138139140141142143144145146147148149150151152153154155156157158159160161162163244 unmodified lines40840941041141241341446 unmodified lines461462463464465466467468469470471511 unmodified lines98398498598698798898999099199299399438 unmodified lines1033103410351036103710381039135 unmodified lines logger.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 clashing column(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 dataset if 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 lines shuffle: bool = False, seed: int = 42, output_column: str = "markdown", overwrite: bool = False, verbose: bool = False, config: str = None, create_pr: bool = False,46 unmodified lines f"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 lines 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( "--verbose", action="store_true",38 unmodified lines shuffle=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 lines150151152153154155156157158159160161162163164165166167168169170171172173174175176177210 unmodified lines38838939039139239339437 unmodified lines432433434435436437438439440371 unmodified lines81281381481581681781881982082182282343 unmodified lines867868869870871872873149 unmodified lines logger.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 clashing column(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 dataset if 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 lines use_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 lines f"Column '{image_column}' not found. Available: {dataset.column_names}" )
# Fail fast if the output column would collide with an existing input column dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
# Shuffle if requested if shuffle: logger.info(f"Shuffling dataset with seed {seed}")371 unmodified lines 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( "--no-clean-output", action="store_true",43 unmodified lines use_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 lines777879808182838485868788899091929394959697989910010110210310433 unmodified lines13813914014114214314420 unmodified lines165166167168169170171172173174109 unmodified lines28428528628728828929029129229329429516 unmodified lines31231331431531631731876 unmodified lines logger.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 clashing column(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 dataset if 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 lines schema: 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 lines
logger.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 column dataset = 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 lines schema=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 lines808182838485868788899091929394959697989910010110210310410510610766 unmodified lines17417517617717817918017 unmodified lines198199200201202203204205206207112 unmodified lines32032132232332432532632732832933033112 unmodified lines34434534634734834935079 unmodified lines logger.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 clashing column(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 dataset if 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 lines schema: 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 lines
logger.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 column dataset = 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 lines schema=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 lines111112113114115116117118119120121122123124125126127128129130131132133134135136137138306 unmodified lines44544644744844945045149 unmodified lines501502503504505506507508509510220 unmodified lines73173273373473573673773873974074174282 unmodified lines825826827828829830831110 unmodified lines logger.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 clashing column(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 dataset if 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 lines image_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 lines f"Column '{source_column}' not found. Available: {dataset.column_names}" ) sys.exit(1)
# Fail fast if the output column would collide with an existing input column dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
if shuffle: dataset = dataset.shuffle(seed=seed) if max_samples:220 unmodified lines 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( "--method", choices=["hf", "vllm"],82 unmodified lines image_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 lines858687888990919293949596979899100101102103104105106107108109110111112204 unmodified lines31731831932032132232326 unmodified lines350351352353354355356357358292 unmodified lines65165265365465565665765865966066166217 unmodified lines68068168268368484 unmodified lines logger.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 clashing column(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 dataset if 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 lines shuffle: bool = False, seed: int = 42, output_column: str = "markdown", overwrite: bool = False,): """Process images from HF dataset through LightOnOCR model."""
26 unmodified lines f"Column '{image_column}' not found. Available: {dataset.column_names}" )
# Fail fast if the output column would collide with an existing input column dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
# Shuffle if requested if shuffle: logger.info(f"Shuffling dataset with seed {seed}")292 unmodified lines 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).", )
args = parser.parse_args()
17 unmodified lines shuffle=args.shuffle, seed=args.seed, output_column=args.output_column, overwrite=args.overwrite, )60 unmodified lines61626364656667686970717273747576777879808182838485868788141 unmodified lines2302312322112332342352362 unmodified lines23924024124224324424524622 unmodified lines26927027127227327427527627750 unmodified lines3283293303043053063313323333343353361 unmodified line338339340314341342343344148 unmodified lines49349449546947049649749849950050150230 unmodified lines53353453553653753853954054154254354454554654754854917 unmodified lines56756856957057157257360 unmodified lines logger.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 clashing column(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 dataset if 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 lines image_column: str = "image", batch_size: int = 32, model: str = "nanonets/Nanonets-OCR-s", max_model_len: int = 8192, max_model_len: int = 32768, max_tokens: int = 15000, gpu_memory_utilization: float = 0.8, hf_token: str = None,2 unmodified lines private: 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 lines f"Column '{image_column}' not found. Available: {dataset.column_names}" )
# Fail fast if the output column would collide with an existing input column dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
# Shuffle if requested if shuffle: logger.info(f"Shuffling dataset with seed {seed}")50 unmodified lines # Add error placeholders for failed batch all_markdown.extend(["[OCR FAILED]"] * len(batch_images))
# Add markdown column to dataset logger.info("Adding markdown column to dataset") dataset = dataset.add_column("markdown", all_markdown) # Add output column to dataset logger.info(f"Adding '{output_column}' column to dataset") dataset = dataset.add_column(output_column, all_markdown)
# Handle inference_info tracking logger.info("Updating inference_info...")1 unmodified line inference_entry = { "model_id": model, "model_name": "Nanonets-OCR-s", "column_name": "markdown", "column_name": output_column, "timestamp": datetime.now().isoformat(), "batch_size": batch_size, "max_tokens": max_tokens,148 unmodified lines parser.add_argument( "--max-model-len", type=int, default=8192, help="Maximum model context length (default: 8192)", 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 lines default=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 lines private=args.private, shuffle=args.shuffle, seed=args.seed, output_column=args.output_column, overwrite=args.overwrite, verbose=args.verbose, )92 unmodified lines93949596979899100101102103104105106107108109110111112113114115116117118119120196 unmodified lines31731831932032132232331 unmodified lines355356357358359360361362363364365366367375 unmodified lines74374474574674774874975075175275375424 unmodified lines77978078178278378478592 unmodified lines logger.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 clashing column(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 dataset if 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 lines shuffle: 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 lines f"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 lines default=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 lines shuffle=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 lines75767778798081828384858687888990919293949596979899100101102236 unmodified lines33934034134234334434538 unmodified lines384385386387388389390391392333 unmodified lines72672772872973073173273373473573673731 unmodified lines76977077177277377477574 unmodified lines return num_gpus
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 clashing column(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 dataset if 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 lines temperature: 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 lines f"Column '{image_column}' not found. Available: {dataset.column_names}" )
# Fail fast if the output column would collide with an existing input column dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
# Shuffle if requested if shuffle: logger.info(f"Shuffling dataset with seed {seed}")333 unmodified lines 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 when pushing to Hub (for benchmarking multiple models in one repo)",31 unmodified lines temperature=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 lines81828384858687888990919293949596979899100101102103104105106107108193 unmodified lines30230330430530630730847 unmodified lines356357358359360361362363364219 unmodified lines58458558658758858959059159259359459571 unmodified lines66766866967067167267380 unmodified lines logger.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 clashing column(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 dataset if 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 lines output_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 lines logger.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 column ds = ensure_output_columns_free(ds, [output_column], overwrite=overwrite)
# Shuffle if requested if shuffle: logger.info(f"Shuffling dataset with seed {seed}")219 unmodified lines default="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 lines output_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 lines101102103104105106107108109110111112113114115116117118119120121122123124125126127128175 unmodified lines30430530630730830931030 unmodified lines341342343344345346347348349317 unmodified lines66766866967067167267367467567667767824 unmodified lines703704705706707708709100 unmodified lines logger.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 clashing column(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 dataset if 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 lines shuffle: bool = False, seed: int = 42, output_column: str = "markdown", overwrite: bool = False, config: str = None, create_pr: bool = False, verbose: bool = False,30 unmodified lines f"Column '{image_column}' not found. Available: {dataset.column_names}" )
# Fail fast if the output column would collide with an existing input column dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
# Shuffle if requested if shuffle: logger.info(f"Shuffling dataset with seed {seed}")317 unmodified lines 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 when pushing to Hub (for benchmarking multiple models in one repo)",24 unmodified lines 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,103 unmodified lines104105106107108109110111112113114115116117118119120121122123124125126127128129130131252 unmodified lines38438538638738838939037 unmodified lines428429430431432433434435436346 unmodified lines78378478578678778878979079179279379429 unmodified lines824825826827828829830103 unmodified lines logger.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 clashing column(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 dataset if 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 lines shuffle: bool = False, seed: int = 42, output_column: str = None, overwrite: bool = False, config: str = None, create_pr: bool = False, verbose: bool = False,37 unmodified lines f"Column '{image_column}' not found. Available: {dataset.column_names}" )
# Fail fast if the output column would collide with an existing input column dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
# Shuffle if requested if 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 lines 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,92 unmodified lines93949596979899100101102103104105106107108109110111112113114115116117118119120238 unmodified lines35936036136236336436542 unmodified lines408409410411412413414415416315 unmodified lines73273373473573673773873974074174274320 unmodified lines76476576676776876992 unmodified lines logger.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 clashing column(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 dataset if 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 lines shuffle: 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 lines f"Column '{image_column}' not found. Available: {dataset.column_names}" )
# Fail fast if the output column would collide with an existing input column dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
# Shuffle if requested if 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 lines shuffle=args.shuffle, seed=args.seed, output_column=args.output_column, overwrite=args.overwrite, verbose=args.verbose, )432 unmodified lines4334344354364374384392 unmodified lines44244344444544644744829 unmodified lines478479480481482483484485486487488489479490491492493408 unmodified lines90290390490590690790890991091191291391491591691791814 unmodified lines933934935936937938939246 unmodified lines118611871188118911901191119211931194119511961197432 unmodified lines create_pr: bool, source_id: str, original_dataset=None, overwrite: bool = False, ): self.repo_id = repo_id self.hf_token = hf_token2 unmodified lines self.create_pr = create_pr self.source_id = source_id self.original_dataset = original_dataset self.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_dataset if "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 = self.original_dataset.add_column("layout", self._layouts) ds = base.add_column("layout", self._layouts) else: if not self._rows: logger.warning("No rows produced; nothing to push.")408 unmodified lines seed=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 lines create_pr=args.create_pr, source_id=args.input_source, original_dataset=original_dataset, overwrite=args.overwrite, )
completed = sink.already_done()246 unmodified lines action="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-specific p.add_argument( "--shard-size",76 unmodified lines7778798081828384858687888990919293949596979899100101102103104154 unmodified lines25926026126226326426533 unmodified lines299300301302303304305306307306 unmodified lines61461561661761861962062162262362462532 unmodified lines65865966066166266366476 unmodified lines logger.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 clashing column(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 dataset if 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 lines include_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 lines f"Column '{image_column}' not found. Available: {dataset.column_names}" )
# Fail fast if the output column would collide with an existing input column 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)306 unmodified lines 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 when pushing to Hub (for benchmarking multiple models)",32 unmodified lines include_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 lines61626364656667686970717273747576777879808182838485868788142 unmodified lines23123223323423523623728 unmodified lines266267268269270271272273274253 unmodified lines52852953053153253353453553653753853927 unmodified lines56756856957057157257360 unmodified lines logger.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 clashing column(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 dataset if 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 lines max_samples: int = None, private: bool = False, output_column: str = None, overwrite: bool = False, shuffle: bool = False, seed: int = 42, verbose: bool = False,28 unmodified lines f"Column '{image_column}' not found. Available: {dataset.column_names}" )
# Fail fast if the output column would collide with an existing input column dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
# Shuffle if requested if shuffle: logger.info(f"Shuffling dataset with seed {seed}")253 unmodified lines default=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 lines max_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 lines65666768697071727374757677787980818283848586878889909192157 unmodified lines25025125225325425525625 unmodified lines282283284285286287288289290306 unmodified lines59759859960060160260360460560660760847 unmodified lines65665765865966066166264 unmodified lines logger.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 clashing column(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 dataset if 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 lines max_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 lines f"Column '{image_column}' not found. Available: {dataset.column_names}" )
# Fail fast if the output column would collide with an existing input column dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
# Validate output format if output_format not in ["markdown", "doctags"]: raise ValueError(306 unmodified lines 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( "--output-format", default="markdown",47 unmodified lines max_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 lines10010110210310410510610710810911011111211311411511611711811912012112212312412512612789 unmodified lines21721821922022122222327 unmodified lines251252253254255256257258259222 unmodified lines48248348448548648748848949049149249364 unmodified lines55855956056156256356499 unmodified lines logger.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 clashing column(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 dataset if 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 lines model: 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 lines f"Column '{image_column}' not found. Available: {dataset.column_names}" )
# Fail fast if the output column would collide with an existing input column 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)222 unmodified lines default="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 lines model=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