""" Upstage document layout inference. Uses Upstage's Document Parse API. """ import os import requests from base import HttpClientInference, create_argument_parser, parse_args_with_extra class UpstageInference(HttpClientInference): """Upstage document layout inference.""" def __init__( self, save_path, input_formats=None, output_formats=None, model=None, mode=None, concurrent_limit=None, sampling_rate=1.0, request_timeout=600, random_seed=None, group_by_document=False, file_ext_mapping=None, ocr=None, dpi=None, jpeg_quality=None, schema=None, ): """Initialize the UpstageInference class. Args: save_path (str): the json path to save the results input_formats (list, optional): the supported input file formats. output_formats (list, optional): the supported output formats. model (str, optional): the model name. Defaults to "document-parse-nightly". mode (str, optional): the parsing mode. Either "standard", "enhanced", or "auto". concurrent_limit (int, optional): maximum number of concurrent API requests sampling_rate (float, optional): fraction of files to process (0.0-1.0) request_timeout (float, optional): timeout in seconds for API requests random_seed (int, optional): random seed for reproducible sampling group_by_document (bool, optional): group per-page results into document-level file_ext_mapping (str or dict, optional): file extension mapping for grouping ocr (str, optional): OCR option (e.g. "auto", "force") dpi (int, optional): DPI value for the request jpeg_quality (int, optional): JPEG quality value for the request schema (str, optional): output schema (e.g. "ufso") """ super().__init__( save_path, input_formats, concurrent_limit, sampling_rate, request_timeout, random_seed, group_by_document, file_ext_mapping ) self.endpoint = os.getenv("UPSTAGE_ENDPOINT", "") self.api_key = os.getenv("UPSTAGE_API_KEY", "") if not all([self.endpoint, self.api_key]): raise ValueError("Please set the environment variables for Upstage") if output_formats is None: output_formats = ["text", "html", "markdown"] self.output_formats = output_formats self.headers = { "Authorization": f"Bearer {self.api_key}", "X-Upstage-Use-Cache": "false", } self.data = { "ocr": ocr or "force", "output_formats": f"{self.output_formats}", "mode": mode or "standard" } # Only include model if explicitly provided (hosted API requires it, local doesn't) if model: self.data["model"] = model if dpi is not None: self.data["dpi"] = str(dpi) if jpeg_quality is not None: self.data["jpeg_quality"] = str(jpeg_quality) if schema: self.data["schema"] = schema def post_process(self, data): """Post-process is not needed for Upstage - it returns data directly.""" return self._merge_processed_data(data) async def _call_api_async(self, filepath, client=None): """Make the actual async API call for a file. Args: filepath: Path object to the file client: httpx.AsyncClient instance Returns: dict: Raw API response data """ filename = filepath.name with open(filepath, "rb") as f: file_data = f.read() files = { "document": (filename, file_data, "application/pdf") } response = await client.post( self.endpoint, headers=self.headers, files=files, data=self.data, timeout=300.0 ) if response.status_code != 200: error_result = response.json() if response.headers.get("content-type", "").startswith("application/json") else {"error": response.text} raise Exception(f"HTTP {response.status_code}: {error_result}") return response.json() def _call_api_sync(self, filepath): """Make the actual sync API call for a file. Args: filepath: Path object to the file Returns: dict: Raw API response data """ filename = filepath.name files = { "document": open(filepath, "rb"), } try: response = requests.post( self.endpoint, headers=self.headers, files=files, data=self.data, timeout=300.0 ) if response.status_code != 200: error_result = response.json() if response.headers.get("content-type", "").startswith("application/json") else {"error": response.text} raise Exception(f"HTTP {response.status_code}: {error_result}") return response.json() finally: files["document"].close() if __name__ == "__main__": parser = create_argument_parser("Upstage document layout inference") parser.add_argument( "--output-formats", type=str, nargs='+', default=["text", "html", "markdown"], help="Output formats supported by the API" ) parser.add_argument( "--ocr", type=str, default=None, help="OCR option (e.g. 'auto', 'force'). Default: force" ) parser.add_argument( "--dpi", type=int, default=None, help="DPI value for the request" ) parser.add_argument( "--jpeg-quality", type=int, default=None, help="JPEG quality value for the request" ) parser.add_argument( "--schema", type=str, default=None, help="Output schema (e.g. 'ufso')" ) # Override --mode with Upstage-specific choices for action in parser._actions: if action.dest == 'mode': action.choices = ["standard", "enhanced", "auto"] action.help = "Parsing mode: 'standard' (default), 'enhanced', or 'auto'" break args = parse_args_with_extra(parser) upstage_inference = UpstageInference( args.save_path, input_formats=args.input_formats, output_formats=args.output_formats, model=args.model, mode=args.mode, concurrent_limit=args.concurrent, sampling_rate=args.sampling_rate, request_timeout=args.request_timeout, random_seed=args.random_seed, group_by_document=args.group_by_document, file_ext_mapping=args.file_ext_mapping, ocr=args.ocr, dpi=args.dpi, jpeg_quality=args.jpeg_quality, schema=args.schema, ) upstage_inference.infer(args.data_path)