Delete client_example.py
Browse files- client_example.py +0 -177
client_example.py
DELETED
|
@@ -1,177 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Example client script for Invoice Information Extractor API
|
| 3 |
-
Shows how to integrate the API into your application
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
import requests
|
| 7 |
-
from pathlib import Path
|
| 8 |
-
import json
|
| 9 |
-
from typing import List, Dict
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
class InvoiceExtractorClient:
|
| 13 |
-
"""Client for Invoice Information Extractor API"""
|
| 14 |
-
|
| 15 |
-
def __init__(self, base_url: str = "http://localhost:7860"):
|
| 16 |
-
"""
|
| 17 |
-
Initialize client
|
| 18 |
-
|
| 19 |
-
Args:
|
| 20 |
-
base_url: Base URL of the API (default: http://localhost:7860)
|
| 21 |
-
"""
|
| 22 |
-
self.base_url = base_url.rstrip('/')
|
| 23 |
-
self.session = requests.Session()
|
| 24 |
-
|
| 25 |
-
def health_check(self) -> Dict:
|
| 26 |
-
"""Check API health status"""
|
| 27 |
-
response = self.session.get(f"{self.base_url}/health")
|
| 28 |
-
response.raise_for_status()
|
| 29 |
-
return response.json()
|
| 30 |
-
|
| 31 |
-
def extract_invoice(self, image_path: str, doc_id: str = None) -> Dict:
|
| 32 |
-
"""
|
| 33 |
-
Extract information from a single invoice
|
| 34 |
-
|
| 35 |
-
Args:
|
| 36 |
-
image_path: Path to invoice image
|
| 37 |
-
doc_id: Optional document identifier
|
| 38 |
-
|
| 39 |
-
Returns:
|
| 40 |
-
Extraction results as dictionary
|
| 41 |
-
"""
|
| 42 |
-
with open(image_path, 'rb') as f:
|
| 43 |
-
files = {'file': f}
|
| 44 |
-
data = {'doc_id': doc_id} if doc_id else {}
|
| 45 |
-
|
| 46 |
-
response = self.session.post(
|
| 47 |
-
f"{self.base_url}/extract",
|
| 48 |
-
files=files,
|
| 49 |
-
data=data,
|
| 50 |
-
timeout=60
|
| 51 |
-
)
|
| 52 |
-
response.raise_for_status()
|
| 53 |
-
return response.json()
|
| 54 |
-
|
| 55 |
-
def extract_batch(self, image_paths: List[str]) -> List[Dict]:
|
| 56 |
-
"""
|
| 57 |
-
Extract information from multiple invoices
|
| 58 |
-
|
| 59 |
-
Args:
|
| 60 |
-
image_paths: List of paths to invoice images
|
| 61 |
-
|
| 62 |
-
Returns:
|
| 63 |
-
List of extraction results
|
| 64 |
-
"""
|
| 65 |
-
files = [('files', open(path, 'rb')) for path in image_paths]
|
| 66 |
-
|
| 67 |
-
try:
|
| 68 |
-
response = self.session.post(
|
| 69 |
-
f"{self.base_url}/extract_batch",
|
| 70 |
-
files=files,
|
| 71 |
-
timeout=120
|
| 72 |
-
)
|
| 73 |
-
response.raise_for_status()
|
| 74 |
-
return response.json()['results']
|
| 75 |
-
finally:
|
| 76 |
-
# Close all file handles
|
| 77 |
-
for _, file_handle in files:
|
| 78 |
-
file_handle.close()
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
# Example usage
|
| 82 |
-
if __name__ == "__main__":
|
| 83 |
-
# Initialize client
|
| 84 |
-
client = InvoiceExtractorClient("http://localhost:7860")
|
| 85 |
-
|
| 86 |
-
# Check health
|
| 87 |
-
print("Checking API health...")
|
| 88 |
-
health = client.health_check()
|
| 89 |
-
print(f"Status: {health['status']}")
|
| 90 |
-
print(f"Models loaded: {health['models_loaded']}\n")
|
| 91 |
-
|
| 92 |
-
# Example 1: Single invoice extraction
|
| 93 |
-
print("=" * 60)
|
| 94 |
-
print("Example 1: Single Invoice Extraction")
|
| 95 |
-
print("=" * 60)
|
| 96 |
-
|
| 97 |
-
# Replace with your invoice path
|
| 98 |
-
invoice_path = "sample_invoice.png"
|
| 99 |
-
|
| 100 |
-
if Path(invoice_path).exists():
|
| 101 |
-
try:
|
| 102 |
-
result = client.extract_invoice(invoice_path, doc_id="demo_001")
|
| 103 |
-
|
| 104 |
-
print(f"\n📄 Document ID: {result['doc_id']}")
|
| 105 |
-
print(f"✅ Confidence: {result['confidence']}")
|
| 106 |
-
print(f"⏱️ Processing Time: {result['processing_time_sec']}s")
|
| 107 |
-
print(f"💰 Cost Estimate: ${result['cost_estimate_usd']}")
|
| 108 |
-
|
| 109 |
-
print("\n📋 Extracted Fields:")
|
| 110 |
-
fields = result['fields']
|
| 111 |
-
print(f" Dealer Name: {fields['dealer_name']}")
|
| 112 |
-
print(f" Model Name: {fields['model_name']}")
|
| 113 |
-
print(f" Horse Power: {fields['horse_power']} HP")
|
| 114 |
-
print(f" Asset Cost: ₹{fields['asset_cost']:,}")
|
| 115 |
-
print(f" Signature: {'✓ Detected' if fields['signature']['present'] else '✗ Not found'}")
|
| 116 |
-
print(f" Stamp: {'✓ Detected' if fields['stamp']['present'] else '✗ Not found'}")
|
| 117 |
-
|
| 118 |
-
if result.get('warnings'):
|
| 119 |
-
print(f"\n⚠️ Warnings: {', '.join(result['warnings'])}")
|
| 120 |
-
|
| 121 |
-
except requests.exceptions.RequestException as e:
|
| 122 |
-
print(f"❌ Error: {e}")
|
| 123 |
-
else:
|
| 124 |
-
print(f"⚠️ Sample invoice not found at: {invoice_path}")
|
| 125 |
-
print(" Please provide a valid invoice image path.")
|
| 126 |
-
|
| 127 |
-
# Example 2: Batch processing
|
| 128 |
-
print("\n" + "=" * 60)
|
| 129 |
-
print("Example 2: Batch Invoice Processing")
|
| 130 |
-
print("=" * 60)
|
| 131 |
-
|
| 132 |
-
# Replace with your invoice paths
|
| 133 |
-
batch_paths = ["invoice_001.png", "invoice_002.png"]
|
| 134 |
-
|
| 135 |
-
existing_paths = [p for p in batch_paths if Path(p).exists()]
|
| 136 |
-
|
| 137 |
-
if existing_paths:
|
| 138 |
-
try:
|
| 139 |
-
results = client.extract_batch(existing_paths)
|
| 140 |
-
|
| 141 |
-
print(f"\n📦 Processed {len(results)} invoices")
|
| 142 |
-
|
| 143 |
-
for i, result in enumerate(results, 1):
|
| 144 |
-
if 'error' in result:
|
| 145 |
-
print(f"\n {i}. ❌ {result.get('filename', 'Unknown')}: {result['error']}")
|
| 146 |
-
else:
|
| 147 |
-
print(f"\n {i}. ✅ {result['doc_id']}")
|
| 148 |
-
print(f" Confidence: {result['confidence']}")
|
| 149 |
-
print(f" Dealer: {result['fields']['dealer_name']}")
|
| 150 |
-
print(f" Cost: ₹{result['fields']['asset_cost']:,}")
|
| 151 |
-
|
| 152 |
-
except requests.exceptions.RequestException as e:
|
| 153 |
-
print(f"❌ Error: {e}")
|
| 154 |
-
else:
|
| 155 |
-
print("⚠️ No valid invoice images found for batch processing")
|
| 156 |
-
|
| 157 |
-
# Example 3: Save results to JSON
|
| 158 |
-
print("\n" + "=" * 60)
|
| 159 |
-
print("Example 3: Save Results to JSON")
|
| 160 |
-
print("=" * 60)
|
| 161 |
-
|
| 162 |
-
if Path(invoice_path).exists():
|
| 163 |
-
try:
|
| 164 |
-
result = client.extract_invoice(invoice_path)
|
| 165 |
-
|
| 166 |
-
output_file = "extraction_result.json"
|
| 167 |
-
with open(output_file, 'w', encoding='utf-8') as f:
|
| 168 |
-
json.dump(result, f, indent=2, ensure_ascii=False)
|
| 169 |
-
|
| 170 |
-
print(f"\n✅ Results saved to: {output_file}")
|
| 171 |
-
|
| 172 |
-
except Exception as e:
|
| 173 |
-
print(f"❌ Error: {e}")
|
| 174 |
-
|
| 175 |
-
print("\n" + "=" * 60)
|
| 176 |
-
print("Examples complete!")
|
| 177 |
-
print("=" * 60)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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