Repository navigation
Expand file tree
/
Copy pathuploader.py
More file actions
192 lines (174 loc) · 6.16 KB
/
Copy pathuploader.py
File metadata and controls
192 lines (174 loc) · 6.16 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
"""
Cloud Upload Module for Smart Helmet
Uploads: video file + start_location + stop_location + location(JSON string)
Does NOT rename files (main.py handles renaming)
"""
import os
import logging
import requests
import datetime
UPLOAD_URL = os.getenv("CENTRIX_UPLOAD_URL", "https://centrix.co.in/v_api/upload")
API_KEY = os.getenv("CENTRIX_API_KEY", os.getenv("API_KEY", ""))
def _extract_times_from_filename(filename: str):
"""
Extract start/end time from names like:
video_20251225_211046_chunk000.mp4
uploaded_20251225_211046_chunk000.mp4
failed_upload_20251225_211046_chunk000.mp4
Returns (start_time, end_time) as 'YYYY-MM-DD HH:MM:SS'
"""
try:
base = os.path.basename(filename)
# find first occurrence of YYYYMMDD_HHMMSS
import re
m = re.search(r"(\d{8}_\d{6})", base)
if not m:
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
return now, now
dt = datetime.datetime.strptime(m.group(1), "%Y%m%d_%H%M%S")
ts = dt.strftime("%Y-%m-%d %H:%M:%S")
return ts, ts
except Exception:
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
return now, now
def upload_to_cloud(
*,
video_path: str,
device_id: str,
start_location: str = None,
stop_location: str = None,
location_json_string: str = "",
site_id: str = None
):
"""
Upload video and location payload to cloud.
Args:
video_path: absolute/relative path to mp4
device_id: device identifier string
start_location: "lat,lon" or None
stop_location: "lat,lon" or None
location_json_string: JSON string (entire file content) or ""
site_id: the site_id extracted from beacons
Returns:
(success: bool, message: str)
"""
try:
if not os.path.exists(video_path):
return False, "Video file not found"
filename = os.path.basename(video_path)
start_time, end_time = _extract_times_from_filename(filename)
try:
mtime = os.path.getmtime(video_path)
end_time = datetime.datetime.fromtimestamp(mtime).strftime("%Y-%m-%d %H:%M:%S")
# We now rely on init.py to construct the final local filename before upload.
except Exception as e:
logging.warning(f"Error fetching mtime: {e}")
data = {
"device_id": device_id,
"file_type": "video",
"start_time": start_time,
"end_time": end_time,
}
# Your required keys:
if start_location:
data["start_location"] = str(start_location)
if stop_location:
data["stop_location"] = str(stop_location)
if site_id:
data["site_id"] = str(site_id)
# Store entire JSON as a string under "location"
if location_json_string is None:
location_json_string = ""
data["location"] = str(location_json_string)
headers = {"X-API-KEY": API_KEY}
with open(video_path, "rb") as vf:
files = {
"video": (filename, vf, "video/mp4")
}
resp = requests.post(
UPLOAD_URL,
headers=headers,
files=files,
data=data,
timeout=180
)
# Try JSON response
try:
result = resp.json()
except Exception:
# Non-JSON response
if resp.status_code == 200:
return True, f"Success HTTP 200: {resp.text}"
return False, f"Failed HTTP {resp.status_code}: {resp.text}"
if result.get("status") == "success" or resp.status_code == 200:
return True, "Success"
else:
return False, str(result.get("message", "Upload failed"))
except Exception as e:
logging.error(f"Upload error {filename}: {e}")
return False, str(e)
def upload_image_to_cloud(
*,
image_path: str,
device_id: str,
start_location: str = None,
stop_location: str = None,
location_json_string: str = "",
site_id: str = None
):
try:
if not os.path.exists(image_path):
return False, "Image file not found"
filename = os.path.basename(image_path)
start_time, end_time = _extract_times_from_filename(filename)
try:
mtime = os.path.getmtime(image_path)
end_time = datetime.datetime.fromtimestamp(mtime).strftime("%Y-%m-%d %H:%M:%S")
except Exception:
pass
data = {
"device_id": device_id,
"file_type": "image",
"start_time": start_time,
"end_time": end_time,
}
if start_location:
data["start_location"] = str(start_location)
if stop_location:
data["stop_location"] = str(stop_location)
if site_id:
data["site_id"] = str(site_id)
if location_json_string is None:
location_json_string = ""
data["location"] = str(location_json_string)
headers = {"X-API-KEY": API_KEY}
with open(image_path, "rb") as f:
files = {
"video": (filename, f, "image/jpeg")
}
resp = requests.post(
UPLOAD_URL,
headers=headers,
files=files,
data=data,
timeout=180
)
try:
result = resp.json()
except Exception:
if resp.status_code == 200:
return True, "Upload successful"
return False, f"HTTP {resp.status_code}: {resp.text[:200]}"
if resp.status_code != 200:
msg = result.get("message") or f"HTTP {resp.status_code}"
return False, msg
if bool(result.get("success")):
return True, result.get("message") or "Upload successful"
return False, result.get("message") or "Upload failed"
except requests.exceptions.Timeout:
return False, "Timeout"
except requests.exceptions.ConnectionError:
return False, "Connection error"
except Exception as e:
logging.exception("[UPLOAD] Unexpected error")
return False, str(e)