Download models.py from hey-kick/PreOCR: direct link, hf CLI and curl.
- Browser
- Download file 7.22 kB
-
https://huggingface.co/spaces/hey-kick/PreOCR/resolve/main/models.py
- Command line
-
hf download hf://spaces/hey-kick/PreOCR/models.py
-
curl -L -o models.py https://huggingface.co/spaces/hey-kick/PreOCR/resolve/main/models.py
7.22 kB
| """Pydantic models for PreOCR API requests and responses.""" | |
| from typing import List, Optional, Union, Any, Dict | |
| from pydantic import BaseModel, Field, field_validator | |
| class PreOCRConfig(BaseModel): | |
| """PreOCR configuration parameters.""" | |
| min_text_length: Optional[int] = Field( | |
| None, | |
| description="Minimum text length threshold (default: 50)" | |
| ) | |
| min_office_text_length: Optional[int] = Field( | |
| None, | |
| description="Minimum text length for office documents (default: 100)" | |
| ) | |
| layout_refinement_threshold: Optional[float] = Field( | |
| None, | |
| description="Layout refinement threshold (0.0-1.0, default: 0.9)" | |
| ) | |
| decision_version: str = Field( | |
| default="intent-aware-v1", | |
| description="OCR decision engine version: 'intent-aware-v1' uses intent-aware planner (default)" | |
| ) | |
| class DetectRequest(BaseModel): | |
| """Request model for OCR detection endpoint.""" | |
| urls: Union[str, List[str]] = Field( | |
| ..., | |
| description="Single URL string or list of URLs to analyze for OCR detection" | |
| ) | |
| config: Optional[PreOCRConfig] = Field( | |
| None, | |
| description="Optional PreOCR configuration for custom detection thresholds" | |
| ) | |
| def normalize_urls(cls, v): | |
| """Normalize single URL to list format.""" | |
| if isinstance(v, str): | |
| return [v] | |
| return v | |
| def validate_urls(cls, v): | |
| """Validate URLs list.""" | |
| if not isinstance(v, list): | |
| return v | |
| if len(v) == 0: | |
| raise ValueError("At least one URL is required") | |
| if len(v) > 100: # Will use config value later | |
| raise ValueError(f"Too many URLs. Maximum 100 URLs per request, received {len(v)}") | |
| return v | |
| class AnalyzeRequest(BaseModel): | |
| """Request model for OCR detection + extraction endpoint.""" | |
| urls: Union[str, List[str]] = Field( | |
| ..., | |
| description="Single URL string or list of URLs to analyze and extract" | |
| ) | |
| config: Optional[PreOCRConfig] = Field( | |
| None, | |
| description="Optional PreOCR configuration for custom detection thresholds" | |
| ) | |
| output_format: Optional[str] = Field( | |
| default="pydantic", | |
| description="Output format for extracted data: 'pydantic' (Pydantic models), 'json' (JSON dictionary), or 'markdown' (markdown string)" | |
| ) | |
| def normalize_urls(cls, v): | |
| """Normalize single URL to list format.""" | |
| if isinstance(v, str): | |
| return [v] | |
| return v | |
| def validate_urls(cls, v): | |
| """Validate URLs list.""" | |
| if not isinstance(v, list): | |
| return v | |
| if len(v) == 0: | |
| raise ValueError("At least one URL is required") | |
| if len(v) > 100: # Will use config value later | |
| raise ValueError(f"Too many URLs. Maximum 100 URLs per request, received {len(v)}") | |
| return v | |
| class PageResult(BaseModel): | |
| """Page-wise OCR detection result.""" | |
| page_number: int = Field(..., description="Page number (1-indexed)") | |
| needs_ocr: bool = Field(..., description="Whether this page needs OCR") | |
| reason: str = Field(..., description="Reason code for the detection result") | |
| confidence: Optional[float] = Field(None, description="Confidence score if available") | |
| class ExtractedElement(BaseModel): | |
| """Extracted element from document.""" | |
| element_type: str = Field(..., description="Type of element (text, heading, etc.)") | |
| text: str = Field(..., description="Text content") | |
| confidence: Optional[float] = Field(None, description="Confidence score") | |
| bbox: Optional[List[float]] = Field(None, description="Bounding box coordinates") | |
| class ExtractedTable(BaseModel): | |
| """Extracted table from document.""" | |
| rows: int = Field(..., description="Number of rows") | |
| columns: int = Field(..., description="Number of columns") | |
| cells: List[Dict[str, Any]] = Field(default_factory=list, description="Table cells") | |
| class ExtractedData(BaseModel): | |
| """Structured data extracted from document.""" | |
| elements: List[ExtractedElement] = Field(default_factory=list, description="Text elements") | |
| tables: List[ExtractedTable] = Field(default_factory=list, description="Tables") | |
| forms: List[Dict[str, Any]] = Field(default_factory=list, description="Forms") | |
| images: List[Dict[str, Any]] = Field(default_factory=list, description="Images") | |
| markdown: Optional[str] = Field(None, description="Markdown content (when output_format='markdown')") | |
| class PageExtractedData(BaseModel): | |
| """Page-wise extracted data.""" | |
| page_number: int = Field(..., description="Page number (1-indexed)") | |
| elements: List[ExtractedElement] = Field(default_factory=list, description="Text elements for this page") | |
| tables: List[ExtractedTable] = Field(default_factory=list, description="Tables for this page") | |
| forms: List[Dict[str, Any]] = Field(default_factory=list, description="Forms for this page") | |
| images: List[Dict[str, Any]] = Field(default_factory=list, description="Images for this page") | |
| class DocumentDetectionResult(BaseModel): | |
| """Detection result for a single document.""" | |
| url: str = Field(..., description="Document URL") | |
| needs_ocr: bool = Field(..., description="Whether document needs OCR") | |
| reason: str = Field(..., description="Reason code for the detection result") | |
| pages: List[PageResult] = Field(default_factory=list, description="Page-wise detection results") | |
| class DocumentAnalysisResult(BaseModel): | |
| """Analysis result for a single document (detection + extraction).""" | |
| url: str = Field(..., description="Document URL") | |
| needs_ocr: bool = Field(..., description="Whether document needs OCR") | |
| reason: str = Field(..., description="Reason code for the detection result") | |
| pages: List[PageResult] = Field(default_factory=list, description="Page-wise detection results") | |
| extracted_data: Optional[ExtractedData] = Field( | |
| None, | |
| description="Extracted structured data aggregated across all pages (only if document is machine-readable)" | |
| ) | |
| page_extracted_data: List[PageExtractedData] = Field( | |
| default_factory=list, | |
| description="Page-wise extracted data (one entry per page that doesn't need OCR)" | |
| ) | |
| class DetectResponse(BaseModel): | |
| """Response model for detection endpoint.""" | |
| success: bool = Field(..., description="Whether the request was successful") | |
| results: List[DocumentDetectionResult] = Field(..., description="Detection results per document") | |
| metadata: Dict[str, Any] = Field(default_factory=dict, description="Response metadata") | |
| class AnalyzeResponse(BaseModel): | |
| """Response model for analyze endpoint.""" | |
| success: bool = Field(..., description="Whether the request was successful") | |
| results: List[DocumentAnalysisResult] = Field(..., description="Analysis results per document") | |
| metadata: Dict[str, Any] = Field(default_factory=dict, description="Response metadata") | |