-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert_csv.py
More file actions
383 lines (329 loc) Β· 13.7 KB
/
Copy pathconvert_csv.py
File metadata and controls
383 lines (329 loc) Β· 13.7 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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import csv
import json
import base64
import sys
import os
from datetime import datetime
from urllib.parse import urlparse, parse_qs
# ===============================================
# 1. Increase field size limit (for large files)
# ===============================================
try:
csv.field_size_limit(sys.maxsize)
except OverflowError:
csv.field_size_limit(2147483647)
def decode_base64_safe(data):
"""Base64 decoding safely"""
if not data or not isinstance(data, str):
return ""
try:
decoded = base64.b64decode(data)
return decoded.decode('utf-8', errors='replace')
except Exception:
return data
def parse_http_headers(raw_text):
"""Extracting my HTTP request/response headers"""
headers = []
if not raw_text or not isinstance(raw_text, str):
return headers
try:
lines = raw_text.split('\r\n')
for line in lines[1:]:
if not line.strip():
break
if ':' in line:
parts = line.split(':', 1)
if len(parts) == 2:
headers.append({
"name": parts[0].strip(),
"value": parts[1].strip()
})
except Exception:
pass
return headers
def parse_cookies_from_headers(headers):
"""Extracting cookies from headers"""
cookies = []
for header in headers:
if header.get('name', '').lower() in ['cookie', 'set-cookie']:
cookie_str = header.get('value', '')
# Simple analysis of cookies
for cookie_part in cookie_str.split(';'):
if '=' in cookie_part:
name, value = cookie_part.split('=', 1)
cookies.append({
"name": name.strip(),
"value": value.strip()
})
return cookies
def extract_http_version(raw_text):
"""Extract the HTTP version"""
if not raw_text or not isinstance(raw_text, str):
return "HTTP/1.1"
try:
first = raw_text.split('\r\n')[0] if '\r\n' in raw_text else raw_text.split('\n')[0]
if 'HTTP/2' in first:
return 'HTTP/2'
elif 'HTTP/1.0' in first:
return 'HTTP/1.0'
elif 'HTTP/1.1' in first:
return 'HTTP/1.1'
except:
pass
return 'HTTP/1.1'
def extract_status_text(raw_response):
"""Extract response status text (eg OK, Not Found)"""
if not raw_response or not isinstance(raw_response, str):
return ""
try:
first = raw_response.split('\r\n')[0] if '\r\n' in raw_response else raw_response.split('\n')[0]
parts = first.split(' ', 2)
if len(parts) >= 3:
return parts[2].strip()
except:
pass
return ""
def extract_body(raw_text):
"""Extract the body of the request or response"""
if not raw_text or not isinstance(raw_text, str):
return ""
try:
if '\r\n\r\n' in raw_text:
return raw_text.split('\r\n\r\n', 1)[1]
elif '\n\n' in raw_text:
return raw_text.split('\n\n', 1)[1]
except:
pass
return ""
def extract_query_string(url):
"""Extracting query parameters from the URL"""
if not url:
return []
try:
parsed = urlparse(url)
params = parse_qs(parsed.query, keep_blank_values=True)
query_list = []
for key, values in params.items():
for value in values:
query_list.append({"name": key, "value": value})
return query_list
except:
return []
def calculate_headers_size(headers):
"""Approximate header size calculation"""
if not headers:
return -1
try:
total = 0
for h in headers:
total += len(h.get('name', '')) + len(h.get('value', '')) + 4 # name: value\r\n
return total
except:
return -1
def safe_int(value, default=0):
"""Safe conversion to integer"""
if value is None or value == '':
return default
try:
clean = str(value).strip().replace(',', '')
if clean.replace('-', '').replace('.', '').isdigit():
return int(float(clean))
except:
pass
return default
def safe_float(value, default=0.0):
"""Safe conversion to float"""
if value is None or value == '':
return default
try:
clean = str(value).strip().replace(',', '')
return float(clean)
except:
pass
return default
def calculate_timings(row):
"""Calculate timings accurately from available data"""
start = safe_float(row.get('Start response timer'))
end = safe_float(row.get('End response timer'))
wait_time = max(0, end - start) if (start and end) else 0
# Try to extract additional timings if they exist
send = safe_float(row.get('Send time'), 0)
receive = safe_float(row.get('Receive time'), 0)
return {
"blocked": -1,
"dns": -1,
"connect": -1,
"send": send,
"wait": wait_time,
"receive": receive,
"ssl": -1
}
def get_mime_type_from_headers(headers):
"""Extract MIME type from Content-Type header"""
for header in headers:
if header.get('name', '').lower() == 'content-type':
value = header.get('value', '')
# Extract the first part before;
return value.split(';')[0].strip()
return ""
def convert_csv_to_har_stream(csv_file_path, output_har_path, preserve_all_data=True):
"""
Convert huge CSV to HAR while saving all data without exception.
Args:
csv_file_path: CSV file path
output_har_path: Path of the output HAR file
preserve_all_data: Save all original columns in a custom field
"""
if not os.path.exists(csv_file_path):
print(f" File not found: {csv_file_path}")
return False
processed_count = 0
error_count = 0
try:
with open(csv_file_path, 'r', encoding='utf-8', errors='replace') as f_in, \
open(output_har_path, 'w', encoding='utf-8') as f_out:
reader = csv.DictReader(f_in)
# Print the column names to check
if reader.fieldnames:
print(f"π Available columns: {', '.join(reader.fieldnames)}")
# Write the beginning of the HAR file
f_out.write('{\n "log": {\n')
f_out.write(' "version": "1.2",\n')
f_out.write(' "creator": {\n')
f_out.write(' "name": "Complete CSV to HAR Converter",\n')
f_out.write(' "version": "4.0",\n')
f_out.write(' "comment": "Preserves all original CSV data"\n')
f_out.write(' },\n')
f_out.write(' "entries": [\n')
first_entry = True
print("π Start processing(Streaming Mode)...")
print("=" * 60)
for idx, row in enumerate(reader, 1):
try:
# Decryption if present
raw_req = decode_base64_safe(row.get('Request', ''))
raw_res = decode_base64_safe(row.get('Response', ''))
# Extract Headers
req_headers = parse_http_headers(raw_req)
res_headers = parse_http_headers(raw_res)
# Extract Cookies
req_cookies = parse_cookies_from_headers(req_headers)
res_cookies = parse_cookies_from_headers(res_headers)
# Extract Bodies
req_body = extract_body(raw_req)
res_body = extract_body(raw_res)
# Extract MIME type from headers or CSV
response_mime = get_mime_type_from_headers(res_headers) or row.get('MIME type', '').strip()
# Built Request
method = row.get('Method', 'GET').strip() or 'GET'
url = row.get('URL', '').strip()
request_obj = {
"method": method,
"url": url,
"httpVersion": extract_http_version(raw_req),
"cookies": req_cookies,
"headers": req_headers,
"queryString": extract_query_string(url),
"headersSize": calculate_headers_size(req_headers),
"bodySize": len(req_body.encode('utf-8')) if req_body else 0
}
# Add postData if it exists
if req_body and method.upper() in ["POST", "PUT", "PATCH", "DELETE"]:
request_mime = get_mime_type_from_headers(req_headers) or "application/octet-stream"
request_obj["postData"] = {
"mimeType": request_mime,
"text": req_body,
"params": []
}
# Build Response
status_code = safe_int(row.get('Status code'))
content_size = safe_int(row.get('Length'), -1)
response_obj = {
"status": status_code,
"statusText": extract_status_text(raw_res),
"httpVersion": extract_http_version(raw_res) if raw_res else extract_http_version(raw_req),
"cookies": res_cookies,
"headers": res_headers,
"content": {
"size": content_size,
"mimeType": response_mime,
"text": res_body,
"encoding": "utf-8"
},
"redirectURL": row.get('Redirect URL', '').strip(),
"headersSize": calculate_headers_size(res_headers),
"bodySize": content_size
}
# Calculate time
timings = calculate_timings(row)
total_time = sum(v for v in timings.values() if v > 0)
# Build Entry
entry = {
"startedDateTime": row.get('Time', datetime.now().isoformat()),
"time": total_time,
"request": request_obj,
"response": response_obj,
"cache": {},
"timings": timings,
"serverIPAddress": row.get('IP', '').strip(),
"connection": row.get('Connection ID', '').strip()
}
# Save all original data (very important!)
if preserve_all_data:
entry["_csvOriginalData"] = {k: v for k, v in row.items()}
# Write the item
if not first_entry:
f_out.write(',\n')
f_out.write(' ')
json.dump(entry, f_out, ensure_ascii=False, indent=2)
first_entry = False
processed_count += 1
# Progress report
if idx % 500 == 0:
print(f"β³ proccess: {idx:,} ...", end='\r')
except Exception as e:
error_count += 1
if error_count <= 5: # Print only the first 5 errors
print(f"\nβ οΈ Row error {idx}: {str(e)[:100]}")
continue
# Close the HAR file
f_out.write('\n ]\n }\n}')
# The report is final
print("\n" + "=" * 60)
print(f"β
Conversion completed successfully!")
print(f"π Total records processed: {processed_count:,}")
if error_count > 0:
print(f"β οΈ Number of errors (skipped): {error_count:,}")
print(f"π Output file: {output_har_path}")
# File size
file_size = os.path.getsize(output_har_path)
if file_size > 1024*1024*1024:
print(f"πΎ File size: {file_size/(1024*1024*1024):.2f} GB")
elif file_size > 1024*1024:
print(f"πΎ File size: {file_size/(1024*1024):.2f} MB")
else:
print(f"πΎ File size: {file_size/1024:.2f} KB")
return True
except Exception as e:
print(f"\nβ Serious error: {e}")
import traceback
traceback.print_exc()
return False
if __name__ == "__main__":
print("=" * 60)
print("π CSV to HAR Converter - Complete Edition")
print("=" * 60)
if len(sys.argv) < 2:
print("\nπ Usage:")
print(" python script.py <input.csv> [output.har]")
print("\nExample:")
print(" python script.py data.csv result.har")
sys.exit(1)
input_csv = sys.argv[1]
output_har = sys.argv[2] if len(sys.argv) >= 3 else f"{os.path.splitext(input_csv)[0]}_complete.har"
success = convert_csv_to_har_stream(input_csv, output_har, preserve_all_data=True)
if success:
print("\n⨠Done! You can now open the file in any HAR Viewer")
else:
print("\nβ Conversion failed. See errors above.")
sys.exit(1)