-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvertio_client.py
More file actions
229 lines (195 loc) · 8.08 KB
/
convertio_client.py
File metadata and controls
229 lines (195 loc) · 8.08 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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
"""Simple client helpers for the Convertio API.
This file implements convenience functions to:
- start a conversion from a public URL
- start a conversion by uploading a local file (encoded as base64)
- check conversion status
- download the converted result (with heuristics for the API response)
Notes:
- The Convertio API has a few ways to provide input (url, raw/base64, upload).
Here we use `url` for remote files and `raw` (base64) for local files. This
avoids multipart upload endpoints which vary between API versions.
- The helper uses a few fallbacks to locate the resulting download URL — if the
exact endpoint shapes differ in your account, adapt the small heuristics.
"""
from typing import Optional, Dict, Any
import requests
import base64
import os
# Base API URL (official Convertio API)
BASE = "https://api.convertio.co"
def _post_json(path, payload, timeout=30):
try:
url = BASE.rstrip("/") + path
resp = requests.post(url, json=payload)
resp.raise_for_status() # raises requests.HTTPError on 4xx/5xx
# try to parse JSON if possible
try:
return True, resp.json()
except ValueError:
return True, resp.text
except requests.HTTPError as he:
# Server returned an error response
body = None
try:
body = he.response.json()
except Exception:
body = he.response.text
return False, {"status": he.response.status_code, "body": body}
except requests.RequestException as e:
# Network / timeout / DNS etc
return False, {"error": str(e)}
def start_conversion_from_file(apikey: str, filepath: str, filename: Optional[str] = None, outputformat: str = "hdr") -> str:
"""Start a conversion by sending the local file as base64 (input=raw).
This reads the file, base64-encodes it and sends it in the `file` field.
Some Convertio accounts may prefer multipart upload; adapt if needed.
"""
if not os.path.exists(filepath):
raise FileNotFoundError(filepath)
with open(filepath, "rb") as f:
b = f.read()
b64 = base64.b64encode(b).decode("ascii")
payload = {
"apikey": apikey,
"input": "url",
"file": "https://drive.google.com/uc?id=1rtgBcZ1TkhKPWdBPn0Ca8LJK9ta3B0lh",
"filename": "",
"outputformat": outputformat,
"options": ""
}
print({
"apikey": apikey,
"input": "raw",
"filename": filename or os.path.basename(filepath),
"outputformat": outputformat,
})
data = _post_json("/convert", payload)
print(data[1])
if data[0] == True:
d = data[1].get("data") or data
conv_id = d.get("id")
if not conv_id:
raise RuntimeError(f"Unexpected convert response: {data}")
return True, conv_id
def get_conversion_status(apikey: str, conv_id: str) -> Dict[str, Any]:
"""Query conversion status. Returns the parsed JSON response."""
try:
url = f"{BASE.rstrip('/')}/convert/{conv_id}/status"
resp = requests.get(url)
resp.raise_for_status()
return resp.json()
except requests.RequestException as e:
return {"error": str(e)}
def wait_for_completion(apikey: str, conv_id: str, output_dir: str, interval: int = 1, timeout: int = 300):
"""
Poll conversion status until step=="finish" then download the result.
Args:
apikey: API key
conv_id: Conversion ID
output_dir: Directory to save downloaded file
interval: Polling interval in seconds (default: 1)
timeout: Maximum wait time in seconds (default: 300)
"""
import time
from datetime import datetime, timedelta
if not os.path.exists(output_dir):
os.makedirs(output_dir)
deadline = datetime.now() + timedelta(seconds=timeout)
while datetime.now() < deadline:
status = get_conversion_status(apikey, conv_id)
if "error" in status:
print(f"Error checking status: {status['error']}")
return
data = status.get("data", {})
print(f"Status: step={data.get('step', 'unknown')}, percent={data.get('percent', 0)}%")
if data.get("step") == "finish":
# Download the converted file
output = data.get("output", {})
if isinstance(output, dict) and "url" in output:
url = output["url"]
filename = os.path.join(output_dir, f"converted_{conv_id}.hdr")
print(f"Downloading to {filename}")
try:
response = requests.get(url, stream=True)
response.raise_for_status()
with open(filename, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
print(f"Downloaded successfully to {filename}")
return filename
except Exception as e:
print(f"Download failed: {e}")
return None
else:
print("No download URL found in response")
return None
elif data.get("step") == "error":
print(f"Conversion failed: {data.get('message', 'Unknown error')}")
return None
time.sleep(interval)
print(f"Timeout after {timeout} seconds")
return None
def fetch_result_content(apikey: str, conv_id: str, dest_dir: str, filename: Optional[str] = None) -> str:
"""Fetch the converted file content for a conversion id and save it to dest_dir.
Tries multiple endpoints and response shapes:
- /convert/{id}/{filename}
- /convert/{id}/dl
- /convert/{id}
- direct file stream
On JSON responses, looks for base64 in data.content or data.output[*].content
or for a data.output.url to download.
"""
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
path = f"/convert/{conv_id}/dl"
last_err = None
try:
url = BASE.rstrip('/') + path
resp = requests.get(url, timeout=15)
# If JSON, look for base64 content or output.url
j = resp.json()
data = j.get('data') or j
# try direct content fields
content_b64 = None
url2 = None
if isinstance(data, dict):
content_b64 = data.get('content')
if content_b64:
raw = base64.b64decode(content_b64)
fname = filename or f"converted_{conv_id}.hdr"
out_path = os.path.join(dest_dir, fname)
with open(out_path, 'wb') as f:
f.write(raw)
return out_path
except Exception as e:
last_err = e
raise RuntimeError(f"Could not fetch converted content (last error: {last_err})")
if __name__ == "__main__":
# Small CLI example (requires requests)
import argparse
p = argparse.ArgumentParser()
p.add_argument("--apikey", default="0da5e396b6d961f1ee87c34d5a05f06c")
p.add_argument("--input", help="Local file to convert", default="./001/output/Img1.jpg")
p.add_argument("--out", help="Where to save output", default="output_hdrs")
p.add_argument("--format", help="Output format (hdr/png/jpg)", default="hdr")
args = p.parse_args()
# Start conversion
ok, conv_id = start_conversion_from_file(args.apikey, args.input, outputformat=args.format)
if not ok:
print(f"Failed to start conversion: {conv_id}")
raise SystemExit(1)
if not conv_id:
print(f"Could not get conversion id from: {conv_id}")
raise SystemExit(1)
print(f"Conversion started: {conv_id}")
# wait for completion
out_file = wait_for_completion(args.apikey, conv_id, args.out)
if out_file:
print(f"Downloaded during wait: {out_file}")
else:
# fallback: try to fetch content directly
try:
saved = fetch_result_content(args.apikey, conv_id, args.out)
print(f"Fetched result content to: {saved}")
except Exception as e:
print(f"Failed to fetch result content: {e}")