Skip to content

Commit 2b8a771

Browse files
bazilinskyyclaude
andcommitted
add_video form: fixes from a review
- a blank field no longer overwrites the row's value (blanks saved height, median age and population as 0, and emptied the mortality) - a locality name several states have (221, e.g. Aberdeen MS/WA) asks for the state instead of taking the first; a match fills in its state - missing time of day or non-numeric times give a message, not a server error - saves read, change and write the file under its lock (two saves at once, or the hub's Merge, lost one) - a direct submit saves the upload date and channel it fetched - literal_eval instead of eval; exception text escaped; new id = max + 1 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 3525819 commit 2b8a771

1 file changed

Lines changed: 68 additions & 21 deletions

File tree

‎add_video.py‎

Lines changed: 68 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@
1515
import requests
1616
from requests.exceptions import RequestException
1717
import ast
18+
import contextlib
19+
import fcntl
20+
import html
1821
import io
1922
import json
2023
import math
@@ -873,8 +876,28 @@ def locate():
873876
return row
874877

875878

879+
@contextlib.contextmanager
880+
def mapping_lock(path=FILE_PATH):
881+
"""The lock propose_segments.plan_lock takes on a mapping file (<file>.lock): a save reads, changes and writes the
882+
file under it, so two saves at once, or the hub's Merge copying the merged mapping over mapping-pavlo.csv, lose
883+
nothing."""
884+
with open(path + '.lock', 'w') as f:
885+
fcntl.flock(f, fcntl.LOCK_EX)
886+
try:
887+
yield
888+
finally:
889+
fcntl.flock(f, fcntl.LOCK_UN)
890+
891+
876892
@app.route('/', methods=['GET', 'POST'])
877893
def form():
894+
if request.method == 'POST' and 'submit_data' in request.form:
895+
with mapping_lock():
896+
return _form()
897+
return _form()
898+
899+
900+
def _form():
878901
df = load_csv(FILE_PATH)
879902
message = ''
880903
locality = ''
@@ -1025,7 +1048,7 @@ def render_current_template():
10251048
except Exception as e:
10261049
return render_template(
10271050
"add_video.html",
1028-
message=f"Invalid YouTube URL: {e}",
1051+
message=f"Invalid YouTube URL: {html.escape(str(e))}",
10291052
df=df,
10301053
locality=locality,
10311054
country=country,
@@ -1046,13 +1069,22 @@ def render_current_template():
10461069
filtered_df = df[df['country'] == country]
10471070

10481071
existing_data = filtered_df[filtered_df.apply(lambda row: locality_matches(row, locality), axis=1)]
1072+
# without a state, a name several states have was taken from the first of them (Aberdeen: MS and WA; 221
1073+
# such names, 2026-11-28): the state is asked for instead
1074+
states = sorted({str(x) for x in existing_data['state'] if not _is_missing(x)})
1075+
if not state and len(states) > 1:
1076+
message = (f"{html.escape(str(locality))} is in more than one state of {html.escape(str(country))} "
1077+
f"({', '.join(map(html.escape, states))}): fill in the state and fetch again.")
1078+
return render_current_template()
10491079

10501080
if not existing_data.empty:
10511081
existing_data_row = existing_data.iloc[0].to_dict()
10521082
n_videos = len(_parse_videos_cell(existing_data_row.get('videos', '')))
10531083
message = f"Entry for locality found ({n_videos} videos). You can update data."
10541084
existing_data_row = existing_data.iloc[0].to_dict()
10551085
locality = existing_data_row.get('locality')
1086+
if not state and not _is_missing(existing_data_row.get('state')):
1087+
state = existing_data_row.get('state') # the save looks the row up by its state too
10561088

10571089
existing_video_state = get_video_state_from_row(existing_data_row, video_id)
10581090
if existing_video_state['upload_date_video']:
@@ -1166,10 +1198,15 @@ def render_current_template():
11661198
yt_channel = _fetch_channel_id_from_html(video_url)
11671199
if not yt_channel:
11681200
yt_channel = _fetch_channel_id_from_ytdlp(video_url)
1201+
# ... and saved with the video (they were fetched, then left out of the row)
1202+
if not upload_date_video and yt_upload_date:
1203+
upload_date_video = yt_upload_date.strftime('%d%m%Y')
1204+
if not channel_video and yt_channel:
1205+
channel_video = yt_channel
11691206
except Exception as e:
11701207
return render_template(
11711208
"add_video.html",
1172-
message=f"Invalid YouTube URL: {e}",
1209+
message=f"Invalid YouTube URL: {html.escape(str(e))}",
11731210
df=df,
11741211
locality=locality,
11751212
country=country,
@@ -1204,7 +1241,15 @@ def render_current_template():
12041241
if existing_video_state['time_of_day_video']:
12051242
time_of_day_video = existing_video_state['time_of_day_video']
12061243

1207-
if any(t not in ['0', '1'] for t in time_of_day):
1244+
try:
1245+
times = [(int(st), int(et)) for st, et in zip(start_time, end_time)]
1246+
except ValueError:
1247+
times = None
1248+
if not time_of_day or not start_time or not end_time:
1249+
message = "Time of day, start time and end time are all needed."
1250+
elif times is None or any(st < 0 for st, _ in times):
1251+
message = "Start and end times must be whole seconds, 0 or more."
1252+
elif any(t not in ['0', '1'] for t in time_of_day):
12081253
message = "Time of day must be either 0 or 1."
12091254
elif vehicle_type_video_int not in range(13):
12101255
message = "Type of vehicle must be one of: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12."
@@ -1268,9 +1313,9 @@ def render_current_template():
12681313
videos_list = df.at[idx, 'videos'].split(',') if pd.notna(df.at[idx, 'videos']) else [] # type: ignore # noqa: E501
12691314
videos_list = [video.strip('[]') for video in videos_list] # type: ignore
12701315

1271-
time_of_day_list = eval(df.at[idx, 'time_of_day']) if pd.notna(df.at[idx, 'time_of_day']) else [] # type: ignore # noqa: E501
1272-
start_time_list = eval(df.at[idx, 'start_time']) if pd.notna(df.at[idx, 'start_time']) else [] # type: ignore # noqa: E501
1273-
end_time_list = eval(df.at[idx, 'end_time']) if pd.notna(df.at[idx, 'end_time']) else [] # type: ignore # noqa: E501
1316+
time_of_day_list = _safe_literal_eval(df.at[idx, 'time_of_day'], [])
1317+
start_time_list = _safe_literal_eval(df.at[idx, 'start_time'], [])
1318+
end_time_list = _safe_literal_eval(df.at[idx, 'end_time'], [])
12741319

12751320
upload_date_list = df.at[idx, 'upload_date'].split(',') if pd.notna(df.at[idx, 'upload_date']) else [] # type: ignore # noqa: E501
12761321
upload_date_list = [upload_date.strip('[]') for upload_date in upload_date_list] # type: ignore # noqa: E501
@@ -1359,17 +1404,19 @@ def render_current_template():
13591404
df.at[idx, 'time_of_day'] = compact_nested_list(time_of_day_list)
13601405
df.at[idx, 'start_time'] = compact_nested_list(start_time_list)
13611406
df.at[idx, 'end_time'] = compact_nested_list(end_time_list)
1362-
df.at[idx, 'gmp'] = to_optional_float(gmp)
1363-
df.at[idx, 'population_locality'] = to_int_safe(population_locality)
1364-
df.at[idx, 'population_country'] = to_int_safe(population_country)
1365-
df.at[idx, 'traffic_mortality'] = to_optional_float(traffic_mortality)
1366-
df.at[idx, 'continent'] = continent
1367-
df.at[idx, 'locality_aka'] = locality_aka
1368-
df.at[idx, 'literacy_rate'] = to_optional_float(literacy_rate)
1369-
df.at[idx, 'avg_height'] = to_float_safe(avg_height)
1370-
df.at[idx, 'med_age'] = to_float_safe(med_age)
1371-
df.at[idx, 'lat'] = to_float_safe(lat)
1372-
df.at[idx, 'lon'] = to_float_safe(lon)
1407+
# a field left blank keeps the row's value: blanks were saved as 0 (Aberdeen WA's height,
1408+
# median age and population in a test, 2026-11-28), or emptied the mortality
1409+
for col, raw, conv in (
1410+
('gmp', gmp, to_optional_float),
1411+
('population_locality', population_locality, to_int_safe),
1412+
('population_country', population_country, to_int_safe),
1413+
('traffic_mortality', traffic_mortality, to_optional_float),
1414+
('continent', continent, str), ('locality_aka', locality_aka, str),
1415+
('literacy_rate', literacy_rate, to_optional_float),
1416+
('avg_height', avg_height, to_float_safe), ('med_age', med_age, to_float_safe),
1417+
('lat', lat, to_float_safe), ('lon', lon, to_float_safe)):
1418+
if not _is_missing(raw):
1419+
df.at[idx, col] = conv(raw)
13731420

13741421
for i in range(len(upload_date_list)):
13751422
if upload_date_list[i] != 'None' and upload_date_list[i]:
@@ -1384,13 +1431,13 @@ def render_current_template():
13841431
vehicle_type_list = [int(x) for x in vehicle_type_list]
13851432
df.at[idx, 'vehicle_type'] = compact_flat_list(vehicle_type_list)
13861433

1387-
df.at[idx, 'gini'] = to_optional_float(gini)
1388-
1389-
df.at[idx, 'traffic_index'] = to_optional_float(traffic_index)
1434+
for col, raw in (('gini', gini), ('traffic_index', traffic_index)):
1435+
if not _is_missing(raw):
1436+
df.at[idx, col] = to_optional_float(raw)
13901437

13911438
else:
13921439
new_row = {
1393-
'id': int(df.iloc[-1]['id'] + 1),
1440+
'id': int(df['id'].max() + 1) if len(df) else 1,
13941441
'locality': locality,
13951442
'locality_aka': locality_aka,
13961443
'state': state,

0 commit comments

Comments
 (0)