-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_image_url_api.py
More file actions
195 lines (162 loc) · 6.17 KB
/
test_image_url_api.py
File metadata and controls
195 lines (162 loc) · 6.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
#!/usr/bin/env python3
"""
Test script for the image URL transcription API endpoint.
This script demonstrates how to use the /transcribe-image-url endpoint.
"""
import requests
import json
import sys
from typing import Dict, Any
def test_image_url_transcription(url: str, api_base: str = "http://localhost:8000") -> Dict[str, Any]:
"""Test image URL transcription via API."""
endpoint = f"{api_base}/transcribe-image-url"
# Prepare the request data
data = {"url": url}
try:
print(f"Sending request to: {endpoint}")
print(f"Image URL: {url}")
print("Processing...")
# Make the API request
response = requests.post(
endpoint,
json=data,
headers={"Content-Type": "application/json"},
timeout=60 # 60 second timeout for processing
)
# Check if request was successful
response.raise_for_status()
# Parse the JSON response
result = response.json()
return result
except requests.exceptions.RequestException as e:
return {
"success": False,
"error": f"Request failed: {str(e)}",
"title": None,
"description": None,
"extracted_text": None
}
def print_results(result: Dict[str, Any]) -> None:
"""Print the transcription results in a formatted way."""
print("\n" + "="*60)
print("IMAGE TRANSCRIPTION RESULTS")
print("="*60)
if result.get('success', False):
print(f"✅ Status: SUCCESS")
print(f"🆔 File ID: {result.get('file_id', 'N/A')}")
print(f"⚙️ Processor: {result.get('processor_used', 'N/A')}")
print(f"⏱️ Processing Time: {result.get('processing_time', 0):.2f}s")
print(f"\n📄 File Info:")
file_info = result.get('file_info', {})
print(f" Name: {file_info.get('name', 'N/A')}")
print(f" Size: {file_info.get('size_mb', 0):.2f} MB")
print(f" Type: {file_info.get('mime_type', 'N/A')}")
print(f" URL: {file_info.get('url', 'N/A')}")
print(f"\n🏷️ Title:")
print(f" {result.get('title', 'No title generated')}")
print(f"\n📝 Description:")
description = result.get('description', 'No description generated')
# Wrap long descriptions
if len(description) > 80:
words = description.split()
lines = []
current_line = ""
for word in words:
if len(current_line + word) > 80:
lines.append(current_line.strip())
current_line = word + " "
else:
current_line += word + " "
if current_line:
lines.append(current_line.strip())
print(" " + "\n ".join(lines))
else:
print(f" {description}")
print(f"\n🔤 Extracted Text:")
extracted_text = result.get('extracted_text', '')
if extracted_text:
# Show extracted text with line breaks preserved
for line in extracted_text.split('\n'):
print(f" {line}")
else:
print(" No text found in image")
else:
print(f"❌ Status: FAILED")
print(f"💥 Error: {result.get('error', 'Unknown error')}")
print("="*60)
def main():
"""Main function to test image URL transcription."""
# Test image URLs - you can replace these with your own
test_urls = [
# Example URLs (replace with real image URLs)
"https://picsum.photos/800/600", # Random photo
"https://via.placeholder.com/400x300/0066CC/FFFFFF?text=Sample+Image", # Placeholder with text
]
# Parse command line arguments
if len(sys.argv) > 1:
# Use provided URL
test_urls = [sys.argv[1]]
elif len(sys.argv) == 1:
print("Image URL Transcription API Test")
print("="*40)
print()
print("Usage:")
print(f" {sys.argv[0]} <image_url>")
print()
print("Example:")
print(f" {sys.argv[0]} https://example.com/photo.jpg")
print()
print("Default test URLs will be used if no URL is provided.")
print()
# Ask user if they want to continue with default URLs
response = input("Continue with default test URLs? (y/n): ").lower().strip()
if response not in ['y', 'yes']:
print("Exiting...")
return
# Test each URL
for i, url in enumerate(test_urls, 1):
if len(test_urls) > 1:
print(f"\n🧪 Test {i}/{len(test_urls)}")
result = test_image_url_transcription(url)
print_results(result)
# Save result to JSON file
if result.get('success'):
filename = f"image_transcription_result_{i}.json"
with open(filename, 'w', encoding='utf-8') as f:
json.dump(result, f, indent=2, ensure_ascii=False)
print(f"💾 Result saved to: {filename}")
def test_with_custom_filename():
"""Test with a custom filename."""
url = "https://picsum.photos/600/400"
data = {
"url": url,
"filename": "custom_test_image.jpg"
}
print("Testing with custom filename...")
try:
response = requests.post(
"http://localhost:8000/transcribe-image-url",
json=data,
headers={"Content-Type": "application/json"},
timeout=60
)
response.raise_for_status()
result = response.json()
print(f"Custom filename test - Success: {result.get('success')}")
print(f"Filename used: {result.get('file_info', {}).get('name')}")
except Exception as e:
print(f"Custom filename test failed: {e}")
if __name__ == "__main__":
try:
print("🚀 Starting Image URL Transcription API Test")
print("📡 Make sure the API server is running on http://localhost:8000")
print()
main()
# Run additional test with custom filename
print("\n" + "="*60)
test_with_custom_filename()
except KeyboardInterrupt:
print("\n\n⛔ Test interrupted by user")
except Exception as e:
print(f"\n\n💥 Unexpected error: {e}")
sys.exit(1)