offlinestreetview 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4 @@
1
+ """offlinestreetview - offline street-level image + map dashboard."""
2
+ from .config import __version__
3
+
4
+ __all__ = ["__version__"]
@@ -0,0 +1,4 @@
1
+ from .app import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1,275 @@
1
+ """app.py - MAIN entry point of the Offline Street View dashboard.
2
+
3
+ Builds the layout, registers the callbacks and starts the server.
4
+ All heavy lifting is imported from utils.py / tiles.py / plots.py / callbacks.py.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import pathlib
10
+
11
+ import dash
12
+ from dash import dcc, html
13
+
14
+ from .callbacks import register_callbacks
15
+ from .config import (APP_NAME, DEFAULT_BAR_COLS, DEFAULT_BAR_HEIGHT_VH,
16
+ DEFAULT_CSV_NAME, DEFAULT_CSV_PATH, DEFAULT_IMG_HEIGHT_VH,
17
+ DEFAULT_IMG_WIDTH_PCT, DEFAULT_MAP_OPACITY,
18
+ DEFAULT_PANEL_PCT, DEFAULT_TILE_DIR, DEFAULT_TILE_ZOOM,
19
+ DEFAULT_X_OFFSET_PX, DEFAULT_Y_OFFSET_PX)
20
+ from .tiles import register_tile_server
21
+
22
+
23
+ # --------------------------------------------------------------------------- #
24
+ # LAYOUT
25
+ # --------------------------------------------------------------------------- #
26
+ def _config_screen():
27
+ """First screen: ask for data source, numeric columns and image size."""
28
+ return html.Div(id="config-screen", children=[
29
+ html.Div(style={"maxWidth": "900px", "margin": "0 auto",
30
+ "padding": "20px", "border": "1px solid #ddd",
31
+ "borderRadius": "8px", "backgroundColor": "#fafafa"},
32
+ children=[
33
+ html.H2(f"{APP_NAME} - Setup", style={"textAlign": "center"}),
34
+
35
+ html.H3("1) Data source"),
36
+ html.Label("CSV folder:"),
37
+ dcc.Input(id="cfg-csv-path", type="text", value=DEFAULT_CSV_PATH,
38
+ placeholder="e.g. /data/my_survey/",
39
+ style={"width": "100%", "marginBottom": "10px"}),
40
+ html.Label("CSV filename:"),
41
+ dcc.Input(id="cfg-csv-name", type="text", value=DEFAULT_CSV_NAME,
42
+ placeholder="e.g. 20211203.csv",
43
+ style={"width": "40%", "marginBottom": "10px"}),
44
+
45
+ html.H3("2) Numeric columns for the bar plot (load ONLY these)"),
46
+ html.Label("Comma-separated column names:"),
47
+ dcc.Input(id="cfg-bar-cols", type="text",
48
+ value=", ".join(DEFAULT_BAR_COLS),
49
+ style={"width": "100%", "marginBottom": "10px"}),
50
+ html.Div(id="cfg-error", style={"color": "red", "fontWeight": "bold"}),
51
+
52
+ html.H3("3) Image frame - position & size (applied before loading)"),
53
+ html.Label("Images panel width (% of screen):"),
54
+ dcc.Slider(id="cfg-panel-pct", min=15, max=70, step=5, value=DEFAULT_PANEL_PCT,
55
+ marks={15: "15%", 40: "40%", 70: "70%"}),
56
+ html.Label(f"Image width inside its frame (%): default {DEFAULT_IMG_WIDTH_PCT}%"),
57
+ dcc.Slider(id="cfg-img-width-pct", min=10, max=100, step=5,
58
+ value=DEFAULT_IMG_WIDTH_PCT,
59
+ marks={10: "10%", 50: "50%", 100: "100%"}),
60
+ html.Label(f"Image height (vh): default {DEFAULT_IMG_HEIGHT_VH}vh"),
61
+ dcc.Slider(id="cfg-img-height-vh", min=5, max=90, step=5,
62
+ value=DEFAULT_IMG_HEIGHT_VH,
63
+ marks={5: "5", 45: "45", 90: "90"}),
64
+ html.Div([
65
+ html.Div([
66
+ html.Label("X offset (px):", style={"fontWeight": "bold"}),
67
+ dcc.Input(id="cfg-img-x-offset", type="number", value=DEFAULT_X_OFFSET_PX,
68
+ style={"width": "90px", "marginLeft": "8px"}),
69
+ ], style={"display": "inline-block", "marginRight": "40px"}),
70
+ html.Div([
71
+ html.Label("Y offset (px):", style={"fontWeight": "bold"}),
72
+ dcc.Input(id="cfg-img-y-offset", type="number", value=DEFAULT_Y_OFFSET_PX,
73
+ style={"width": "90px", "marginLeft": "8px"}),
74
+ ], style={"display": "inline-block"}),
75
+ ], style={"margin": "10px 0"}),
76
+
77
+ # ---- CHANGE 4: bar plot WIDTH slider removed, only HEIGHT kept ----
78
+ html.H3("4) Bar plot height"),
79
+ html.Label(f"Bar plot height (vh): default {DEFAULT_BAR_HEIGHT_VH}vh"),
80
+ dcc.Slider(id="cfg-bar-height-vh", min=10, max=60, step=5,
81
+ value=DEFAULT_BAR_HEIGHT_VH,
82
+ marks={10: "10", 25: "25", 60: "60"}),
83
+
84
+ html.H3("5) Offline OpenStreetMap tiles (optional)"),
85
+ dcc.Checklist(
86
+ id="cfg-offline",
87
+ options=[{"label": " Use offline tiles (works without internet)",
88
+ "value": "on"}],
89
+ value=[],
90
+ style={"marginBottom": "10px"},
91
+ ),
92
+ html.Label("Tile zoom level (higher = more detail, more tiles):"),
93
+ dcc.Slider(id="cfg-tile-zoom", min=10, max=19, step=1, value=DEFAULT_TILE_ZOOM,
94
+ marks={10: "10", 14: "14", 18: "18", 19: "19"}),
95
+
96
+ html.Button("Load dashboard", id="cfg-load-btn", n_clicks=0,
97
+ style={"marginTop": "20px", "padding": "10px 30px",
98
+ "fontSize": "16px", "backgroundColor": "#007BFF",
99
+ "color": "white", "border": "none",
100
+ "borderRadius": "4px"}),
101
+ ]),
102
+ ])
103
+
104
+
105
+ def _dashboard_screen():
106
+ """Second screen: the viewer (row selector, map, bar chart, images, shifts)."""
107
+ return html.Div(id="dashboard-screen", style={"display": "none"}, children=[
108
+
109
+ # -------- header with "Change Settings" button ---------------------
110
+ html.Div(
111
+ html.Button(
112
+ "⚙️ Change Settings",
113
+ id="back-to-config-btn",
114
+ n_clicks=0,
115
+ style={"backgroundColor": "#6C757D", "color": "white",
116
+ "border": "none", "padding": "6px 16px",
117
+ "borderRadius": "4px"},
118
+ ),
119
+ style={"textAlign": "right", "padding": "5px 20px"},
120
+ ),
121
+
122
+ # ================= CHANGE 5: row / timestamp selector on TOP =======
123
+ html.Div([
124
+ dcc.Slider(
125
+ id="image-slider",
126
+ min=0, max=0, step=1, value=0,
127
+ marks={}, # <-- no tick labels any more
128
+ tooltip={"placement": "bottom"},
129
+ ),
130
+ html.Div(
131
+ id="bar-subheading",
132
+ style={"textAlign": "center", "fontWeight": "bold",
133
+ "fontSize": "16px", "margin": "10px 0 4px 0"},
134
+ ),
135
+ ], style={"width": "95%", "margin": "5px auto 10px auto"}),
136
+
137
+ # -------- middle: map + bar plot (left), images (right) -----------
138
+ html.Div(style={"width": "100%", "display": "flex"}, children=[
139
+ html.Div(id="plots-column", style={"width": "60%", "float": "left"},
140
+ children=[
141
+
142
+ # ============ CHANGE 3: map transparency ABOVE the map ====
143
+ html.Div([
144
+ html.Label("Map transparency (0 = transparent, 1 = opaque):",
145
+ style={"fontWeight": "bold", "display": "block",
146
+ "marginBottom": "0"}),
147
+ dcc.Slider(
148
+ id="map-opacity-slider",
149
+ min=0, max=1, step=0.05,
150
+ value=DEFAULT_MAP_OPACITY,
151
+ marks={0: "Transparent", 0.5: "Semi", 1: "Opaque"},
152
+ ),
153
+ ], style={"width": "100%", "textAlign": "center",
154
+ "margin": "0 0 8px 0"}),
155
+
156
+ dcc.Graph(id="map", style={"width": "100%", "height": "50vh"}),
157
+
158
+ # ============ CHANGE 2: "Bubble color column" dropdown removed
159
+ html.Div([
160
+ dcc.Checklist(
161
+ id="show-all-points",
162
+ options=[{"label": " Show all data points (bubble / heatmap)",
163
+ "value": "on"}],
164
+ value=[],
165
+ style={"display": "inline-block"},
166
+ ),
167
+ ], style={"textAlign": "center", "margin": "5px", "width": "100%"}),
168
+
169
+ dcc.Dropdown(id="bar-dropdown", clearable=False,
170
+ placeholder="Select a numeric column"),
171
+ dcc.Graph(id="bar-plot", style={"width": "100%", "height": "25vh"}),
172
+ ]),
173
+ html.Div(id="images-column", style={"width": "40%"}, children=[
174
+ html.Img(id="image1"),
175
+ html.Img(id="image2"),
176
+ ]),
177
+ ]),
178
+
179
+ # -------- shift controls -----------------------------------------
180
+ html.Div([
181
+ html.H4("Image Shift Controls", style={"textAlign": "center",
182
+ "marginTop": "20px"}),
183
+ html.Div([
184
+ html.Div([
185
+ html.Label("Image 1 Shift:", style={"fontWeight": "bold"}),
186
+ dcc.Input(id="image1-shift-input", type="number", value=0, step=1,
187
+ style={"width": "80px", "marginLeft": "10px"}),
188
+ html.Button("Apply Shift 1", id="apply-shift1-btn", n_clicks=0,
189
+ style={"marginLeft": "10px", "backgroundColor": "#007BFF",
190
+ "color": "white", "border": "none",
191
+ "padding": "5px 10px", "borderRadius": "3px"}),
192
+ ], style={"display": "inline-block", "marginRight": "30px"}),
193
+ html.Div([
194
+ html.Label("Image 2 Shift:", style={"fontWeight": "bold"}),
195
+ dcc.Input(id="image2-shift-input", type="number", value=0, step=1,
196
+ style={"width": "80px", "marginLeft": "10px"}),
197
+ html.Button("Apply Shift 2", id="apply-shift2-btn", n_clicks=0,
198
+ style={"marginLeft": "10px", "backgroundColor": "#28A745",
199
+ "color": "white", "border": "none",
200
+ "padding": "5px 10px", "borderRadius": "3px"}),
201
+ ], style={"display": "inline-block", "marginRight": "30px"}),
202
+ html.Div([
203
+ html.Button("Reset Shifts", id="reset-shifts-btn", n_clicks=0,
204
+ style={"backgroundColor": "#FFC107", "color": "black",
205
+ "border": "none", "padding": "5px 15px",
206
+ "borderRadius": "3px"}),
207
+ ], style={"display": "inline-block", "marginRight": "30px"}),
208
+ html.Div([
209
+ html.Button("Export Changes", id="export-btn", n_clicks=0,
210
+ style={"backgroundColor": "#DC3545", "color": "white",
211
+ "border": "none", "padding": "5px 15px",
212
+ "borderRadius": "3px"}),
213
+ ], style={"display": "inline-block"}),
214
+ html.Div([
215
+ html.Button("Download OSM Tiles (offline)", id="download-tiles-btn",
216
+ n_clicks=0,
217
+ style={"backgroundColor": "#6F42C1", "color": "white",
218
+ "border": "none", "padding": "5px 15px",
219
+ "borderRadius": "3px"}),
220
+ ], style={"display": "inline-block", "marginLeft": "30px"}),
221
+ ], style={"textAlign": "center", "margin": "10px"}),
222
+
223
+ html.Div(id="shift-status", style={"textAlign": "center", "margin": "6px",
224
+ "fontWeight": "bold"}),
225
+ html.Div(id="export-status", style={"textAlign": "center", "margin": "6px",
226
+ "fontWeight": "bold"}),
227
+ html.Div(id="tile-status", style={"textAlign": "center", "margin": "6px",
228
+ "fontWeight": "bold", "color": "#6F42C1"}),
229
+ ]),
230
+
231
+ # -------- hidden stores -------------------------------------------
232
+ dcc.Store(id="data-store"),
233
+ dcc.Store(id="config-store"),
234
+ dcc.Store(id="shift-store", data={"image1_shift": 0, "image2_shift": 0}),
235
+ ])
236
+
237
+
238
+ def make_layout():
239
+ return html.Div([
240
+ html.H1(APP_NAME, style={"textAlign": "center"}),
241
+ _config_screen(),
242
+ _dashboard_screen(),
243
+ ])
244
+
245
+
246
+ # --------------------------------------------------------------------------- #
247
+ # MAIN
248
+ # --------------------------------------------------------------------------- #
249
+ def main(argv=None):
250
+ parser = argparse.ArgumentParser(prog="offlinestreetview",
251
+ description=f"{APP_NAME} dashboard")
252
+ parser.add_argument("--host", default="127.0.0.1", help="host to bind")
253
+ parser.add_argument("--port", default=8050, type=int, help="port to bind")
254
+ parser.add_argument("--debug", action="store_true", help="run in debug mode")
255
+ parser.add_argument("--tile-dir", default=None,
256
+ help="folder for offline OSM tiles (default: user data dir)")
257
+ args = parser.parse_args(argv)
258
+
259
+ tile_dir = pathlib.Path(args.tile_dir).expanduser() if args.tile_dir else DEFAULT_TILE_DIR
260
+
261
+ app = dash.Dash(__name__, title=APP_NAME)
262
+
263
+ register_tile_server(app, tile_dir)
264
+
265
+ app.layout = make_layout()
266
+ register_callbacks(app)
267
+
268
+ print(f" * {APP_NAME}: http://{args.host}:{args.port}")
269
+ print(f" * Offline tiles folder: {tile_dir}")
270
+ run = getattr(app, "run", None) or app.run_server # dash >= 2.17 renamed it
271
+ run(host=args.host, port=args.port, debug=args.debug, use_reloader=False)
272
+
273
+
274
+ if __name__ == "__main__":
275
+ main()
@@ -0,0 +1,364 @@
1
+ """callbacks.py - all Dash callbacks (wiring layout, utils, plots and tiles)."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import traceback
6
+ import io
7
+ import dash
8
+ import pandas as pd
9
+ from dash.dependencies import Input, Output, State
10
+ from dash.exceptions import PreventUpdate
11
+
12
+ from .config import (DEFAULT_BAR_COLS, DEFAULT_BAR_HEIGHT_VH, DEFAULT_CSV_NAME,
13
+ DEFAULT_CSV_PATH, DEFAULT_EXPORT_DIR, DEFAULT_IMG_HEIGHT_VH,
14
+ DEFAULT_IMG_WIDTH_PCT, DEFAULT_MAP_OPACITY, DEFAULT_PANEL_PCT,
15
+ DEFAULT_TILE_DIR, DEFAULT_TILE_ZOOM, DEFAULT_X_OFFSET_PX,
16
+ DEFAULT_Y_OFFSET_PX)
17
+ from .plots import bar_figure, map_figure
18
+ from .tiles import download_tiles_for_bbox
19
+ from .utils import (encode_image, export_shifted_csv, load_dashboard_data,
20
+ shifted_image_path)
21
+
22
+
23
+ # =========================================================================== #
24
+ # CONFIG SCREEN <-> DASHBOARD (ONE callback, two triggers - no duplicate outputs)
25
+ # =========================================================================== #
26
+ def register_config_callback(app):
27
+
28
+ @app.callback(
29
+ [Output("data-store", "data"),
30
+ Output("config-store", "data"),
31
+ Output("config-screen", "style"),
32
+ Output("dashboard-screen", "style"),
33
+ Output("bar-dropdown", "options"),
34
+ Output("bar-dropdown", "value"),
35
+ Output("image-slider", "max"),
36
+ Output("cfg-csv-path", "value"),
37
+ Output("cfg-csv-name", "value"),
38
+ Output("cfg-bar-cols", "value"),
39
+ Output("cfg-panel-pct", "value"),
40
+ Output("cfg-img-width-pct", "value"),
41
+ Output("cfg-img-height-vh", "value"),
42
+ Output("cfg-img-x-offset", "value"),
43
+ Output("cfg-img-y-offset", "value"),
44
+ Output("cfg-offline", "value"),
45
+ Output("cfg-tile-zoom", "value"),
46
+ Output("cfg-bar-height-vh", "value"),
47
+ Output("cfg-error", "children")],
48
+ [Input("cfg-load-btn", "n_clicks"),
49
+ Input("back-to-config-btn", "n_clicks")],
50
+ [State("cfg-csv-path", "value"),
51
+ State("cfg-csv-name", "value"),
52
+ State("cfg-bar-cols", "value"),
53
+ State("cfg-panel-pct", "value"),
54
+ State("cfg-img-width-pct", "value"),
55
+ State("cfg-img-height-vh", "value"),
56
+ State("cfg-img-x-offset", "value"),
57
+ State("cfg-img-y-offset", "value"),
58
+ State("cfg-offline", "value"),
59
+ State("cfg-tile-zoom", "value"),
60
+ State("cfg-bar-height-vh", "value"),
61
+ State("config-store", "data")],
62
+ prevent_initial_call=True,
63
+ )
64
+ def handle_config(load_clicks, back_clicks,
65
+ csv_path, csv_name, bar_cols,
66
+ panel_pct, img_w, img_h, x_off, y_off,
67
+ offline, tile_zoom, bar_h, cfg):
68
+ ctx = dash.callback_context
69
+ if not ctx.triggered:
70
+ raise PreventUpdate
71
+ button = ctx.triggered[0]["prop_id"].split(".")[0]
72
+
73
+ NO = dash.no_update
74
+ NOTHING = (NO,) * 11 # outputs 8..18 (form values)
75
+ cfg = cfg or {}
76
+
77
+ # ------------------------------------------------------------------ #
78
+ # A) "Change Settings" -> back to config, pre-filled
79
+ # ------------------------------------------------------------------ #
80
+ if button == "back-to-config-btn" and back_clicks:
81
+ return (
82
+ NO, NO,
83
+ {"display": "block"}, {"display": "none"},
84
+ NO, NO, NO,
85
+ cfg.get("csv_path", DEFAULT_CSV_PATH),
86
+ cfg.get("csv_name", DEFAULT_CSV_NAME),
87
+ ", ".join(cfg.get("loaded_bar_columns", DEFAULT_BAR_COLS)),
88
+ cfg.get("panel_pct", DEFAULT_PANEL_PCT),
89
+ cfg.get("img_width_pct", DEFAULT_IMG_WIDTH_PCT),
90
+ cfg.get("img_height_vh", DEFAULT_IMG_HEIGHT_VH),
91
+ cfg.get("x_offset", DEFAULT_X_OFFSET_PX),
92
+ cfg.get("y_offset", DEFAULT_Y_OFFSET_PX),
93
+ ["on"] if cfg.get("use_offline", False) else [],
94
+ cfg.get("tile_zoom", DEFAULT_TILE_ZOOM),
95
+ cfg.get("bar_height_vh", DEFAULT_BAR_HEIGHT_VH),
96
+ "",
97
+ )
98
+
99
+ # ------------------------------------------------------------------ #
100
+ # B) "Load dashboard" -> read CSV, build dashboard
101
+ # ------------------------------------------------------------------ #
102
+ if button == "cfg-load-btn" and load_clicks:
103
+ bar_columns = [c.strip() for c in str(bar_cols or "").split(",") if c.strip()]
104
+ if not bar_columns:
105
+ return (NO,) * 18 + ("⚠️ Please enter at least one numeric column.",)
106
+
107
+ try:
108
+ df, loaded, missing = load_dashboard_data(csv_path, csv_name, bar_columns)
109
+ except Exception as exc:
110
+ traceback.print_exc()
111
+ return (NO,) * 18 + (f"❌ Load failed: {exc}",)
112
+
113
+ if df.empty:
114
+ return (NO,) * 18 + ("❌ The CSV produced an empty table.",)
115
+
116
+ new_config = {
117
+ "panel_pct": int(panel_pct or 40),
118
+ "img_width_pct": int(img_w or 100),
119
+ "img_height_vh": int(img_h or 45),
120
+ "x_offset": int(x_off or 0),
121
+ "y_offset": int(y_off or 0),
122
+ "bar_height_vh": int(bar_h or DEFAULT_BAR_HEIGHT_VH),
123
+ "use_offline": bool(offline),
124
+ "tile_zoom": int(tile_zoom or 18),
125
+ "loaded_bar_columns": loaded,
126
+ "csv_path": csv_path,
127
+ "csv_name": csv_name,
128
+ }
129
+
130
+ error = ""
131
+ if new_config["use_offline"]:
132
+ try:
133
+ download_tiles_for_bbox(
134
+ float(df["lat"].min()), float(df["lat"].max()),
135
+ float(df["lon"].min()), float(df["lon"].max()),
136
+ new_config["tile_zoom"],
137
+ )
138
+ except Exception as exc:
139
+ traceback.print_exc()
140
+ error = (f"⚠️ Offline tiles could not be downloaded ({exc}). "
141
+ f"Press 'Download OSM Tiles' on the dashboard.")
142
+
143
+ n_rows = len(df)
144
+ options = [{"label": c, "value": c} for c in loaded]
145
+ value = loaded[0] if loaded else None
146
+
147
+ if missing:
148
+ miss_msg = f"⚠️ Columns not found and ignored: {', '.join(missing)}"
149
+ error = f"{error} {miss_msg}" if error else miss_msg
150
+
151
+ return (
152
+ df.to_json(date_format="iso", orient="split"),
153
+ new_config,
154
+ {"display": "none"}, {"display": "block"},
155
+ options, value,
156
+ n_rows - 1,
157
+ ) + NOTHING + (error,)
158
+
159
+ raise PreventUpdate
160
+
161
+
162
+ # =========================================================================== #
163
+ # IMAGE SHIFTS
164
+ # =========================================================================== #
165
+ def register_shift_callbacks(app):
166
+
167
+ @app.callback(
168
+ [Output("shift-store", "data"),
169
+ Output("shift-status", "children")],
170
+ [Input("apply-shift1-btn", "n_clicks"),
171
+ Input("apply-shift2-btn", "n_clicks"),
172
+ Input("reset-shifts-btn", "n_clicks")],
173
+ [State("image1-shift-input", "value"),
174
+ State("image2-shift-input", "value"),
175
+ State("shift-store", "data")],
176
+ )
177
+ def update_shifts(s1, s2, reset, v1, v2, store):
178
+ shifts = dict(store or {"image1_shift": 0, "image2_shift": 0})
179
+ ctx = dash.callback_context
180
+ if not ctx.triggered:
181
+ return shifts, (f"Current shifts - Image 1: {shifts['image1_shift']}, "
182
+ f"Image 2: {shifts['image2_shift']}")
183
+
184
+ button = ctx.triggered[0]["prop_id"].split(".")[0]
185
+ if button == "apply-shift1-btn" and s1:
186
+ shifts["image1_shift"] = int(v1 or 0)
187
+ elif button == "apply-shift2-btn" and s2:
188
+ shifts["image2_shift"] = int(v2 or 0)
189
+ elif button == "reset-shifts-btn" and reset:
190
+ shifts = {"image1_shift": 0, "image2_shift": 0}
191
+
192
+ status = (f"Image 1 shift: {shifts['image1_shift']} | "
193
+ f"Image 2 shift: {shifts['image2_shift']}")
194
+ if button == "apply-shift1-btn" and s1:
195
+ status = (f"Image 1 shift applied: {shifts['image1_shift']} | "
196
+ f"Image 2: {shifts['image2_shift']}")
197
+ elif button == "apply-shift2-btn" and s2:
198
+ status = (f"Image 1: {shifts['image1_shift']} | "
199
+ f"Image 2 shift applied: {shifts['image2_shift']}")
200
+ elif button == "reset-shifts-btn" and reset:
201
+ status = "All shifts reset to 0"
202
+ return shifts, status
203
+
204
+
205
+ # =========================================================================== #
206
+ # EXPORT
207
+ # =========================================================================== #
208
+ def register_export_callback(app):
209
+
210
+ @app.callback(
211
+ Output("export-status", "children"),
212
+ Input("export-btn", "n_clicks"),
213
+ [State("data-store", "data"),
214
+ State("shift-store", "data")],
215
+ prevent_initial_call=True,
216
+ )
217
+ def export_changes(n_clicks, data_json, shifts):
218
+ if not n_clicks:
219
+ return ""
220
+ try:
221
+ df = pd.read_json(io.StringIO(data_json), orient="split")
222
+ sh = shifts or {}
223
+ csv_path, fr, bk = export_shifted_csv(
224
+ df,
225
+ shift1=int(sh.get("image1_shift", 0)),
226
+ shift2=int(sh.get("image2_shift", 0)),
227
+ out_root=str(DEFAULT_EXPORT_DIR),
228
+ )
229
+ return (f"✅ Export successful! CSV saved to: {csv_path} | "
230
+ f"Changes: {fr} file_fr, {bk} file_bk")
231
+ except Exception as exc:
232
+ traceback.print_exc()
233
+ return f"❌ Export failed: {str(exc)}"
234
+
235
+
236
+ # =========================================================================== #
237
+ # MAIN DASHBOARD (images + map + bar chart + map opacity)
238
+ # =========================================================================== #
239
+ def register_dashboard_callback(app):
240
+
241
+ @app.callback(
242
+ [Output("image1", "src"),
243
+ Output("image2", "src"),
244
+ Output("plots-column", "style"),
245
+ Output("images-column", "style"),
246
+ Output("image1", "style"),
247
+ Output("image2", "style"),
248
+ Output("map", "figure"),
249
+ Output("bar-plot", "figure"),
250
+ Output("bar-subheading", "children"),
251
+ Output("bar-plot", "style")],
252
+ [Input("image-slider", "value"),
253
+ Input("bar-dropdown", "value"),
254
+ Input("apply-shift1-btn", "n_clicks"),
255
+ Input("apply-shift2-btn", "n_clicks"),
256
+ Input("reset-shifts-btn", "n_clicks"),
257
+ Input("map-opacity-slider", "value"),
258
+ Input("show-all-points", "value")],
259
+ [State("data-store", "data"),
260
+ State("config-store", "data"),
261
+ State("shift-store", "data")],
262
+ )
263
+ def update_dashboard(row, column, s1, s2, reset, map_opacity,
264
+ show_all, data_json, config, shifts):
265
+ if not data_json:
266
+ raise PreventUpdate
267
+
268
+ try:
269
+ df = pd.read_json(io.StringIO(data_json), orient="split")
270
+ cfg = config or {}
271
+ sh = shifts or {"image1_shift": 0, "image2_shift": 0}
272
+ shift1, shift2 = int(sh.get("image1_shift", 0)), int(sh.get("image2_shift", 0))
273
+ row = int(row)
274
+
275
+ # ---- image shifts ----------------------------------------------
276
+ image1_src = encode_image(shifted_image_path(df, row, shift1, "image_path1"))
277
+ image2_src = encode_image(shifted_image_path(df, row, shift2, "image_path2"))
278
+
279
+ # ---- frame position & size (set on the config screen) ----------
280
+ panel_pct = int(cfg.get("panel_pct", 40))
281
+ plots_style = {"width": f"{max(15, 100 - panel_pct)}%", "float": "left"}
282
+ images_style = {"width": f"{panel_pct}%", "display": "flex",
283
+ "flexDirection": "column", "alignItems": "center"}
284
+ img_style = {
285
+ "width": f"{int(cfg.get('img_width_pct', 100))}%",
286
+ "height": f"{int(cfg.get('img_height_vh', 45))}vh",
287
+ "objectFit": "contain",
288
+ "marginLeft": f"{int(cfg.get('x_offset', 0))}px",
289
+ "marginTop": f"{int(cfg.get('y_offset', 0))}px",
290
+ }
291
+
292
+ # ---- bar plot: width fixed at 100%, only height is adjustable ---
293
+ bar_style = {
294
+ "width": "100%",
295
+ "height": f"{int(cfg.get('bar_height_vh', DEFAULT_BAR_HEIGHT_VH))}vh",
296
+ }
297
+
298
+ # ---- map (dot + optional bubbles) + bar chart -------------------
299
+ use_offline = bool(cfg.get("use_offline", False))
300
+ zoom = int(cfg.get("tile_zoom", 18))
301
+ opacity = DEFAULT_MAP_OPACITY if map_opacity is None else float(map_opacity)
302
+
303
+ # CHANGE 2: the bubble dropdown is gone -> colour by the selected column
304
+ map_fig = map_figure(
305
+ df, row,
306
+ use_offline=use_offline, zoom=zoom, map_opacity=opacity,
307
+ show_all_points=bool(show_all), bubble_column=column,
308
+ )
309
+ bar_fig = bar_figure(df, row, column)
310
+
311
+ ts = df.iloc[row]["adj_time"]
312
+ shift_info = (f" | Shifts Applied - Img1: {shift1}, Img2: {shift2}"
313
+ if (shift1 or shift2) else "")
314
+ subheading = f"Row: {row} | Timestamp: {ts}{shift_info}"
315
+
316
+ return (image1_src, image2_src, plots_style, images_style,
317
+ img_style, img_style, map_fig, bar_fig, subheading, bar_style)
318
+
319
+ except Exception as exc:
320
+ traceback.print_exc()
321
+ return ((dash.no_update,) * 8
322
+ + (f"❌ ERROR: {exc}", # bar-subheading -> children, str is fine
323
+ dash.no_update)) # bar-plot style -> must remain a dict
324
+
325
+
326
+ # =========================================================================== #
327
+ # OFFLINE TILE DOWNLOAD
328
+ # =========================================================================== #
329
+ def register_tile_download_callback(app):
330
+
331
+ @app.callback(
332
+ Output("tile-status", "children"),
333
+ Input("download-tiles-btn", "n_clicks"),
334
+ [State("data-store", "data"),
335
+ State("config-store", "data")],
336
+ prevent_initial_call=True,
337
+ )
338
+ def download_tiles(n_clicks, data_json, config):
339
+ if not n_clicks or not data_json:
340
+ return ""
341
+ try:
342
+ df = pd.read_json(io.StringIO(data_json), orient="split")
343
+ zoom = int((config or {}).get("tile_zoom", 18))
344
+ dl, cached = download_tiles_for_bbox(
345
+ float(df["lat"].min()), float(df["lat"].max()),
346
+ float(df["lon"].min()), float(df["lon"].max()),
347
+ zoom,
348
+ )
349
+ return (f"🗺️ Offline tiles ready: {dl} downloaded, {cached} cached "
350
+ f"(zoom {zoom}). Stored in: {DEFAULT_TILE_DIR}")
351
+ except Exception as exc:
352
+ traceback.print_exc()
353
+ return f"❌ Tile download failed: {str(exc)}"
354
+
355
+
356
+ # --------------------------------------------------------------------------- #
357
+ # register everything
358
+ # --------------------------------------------------------------------------- #
359
+ def register_callbacks(app):
360
+ register_config_callback(app)
361
+ register_shift_callbacks(app)
362
+ register_export_callback(app)
363
+ register_dashboard_callback(app)
364
+ register_tile_download_callback(app)
@@ -0,0 +1,74 @@
1
+ """config.py - centralised configuration for Offline Street View."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import pathlib
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ APP_NAME = "Offline Street View"
10
+ PACKAGE_NAME = "offlinestreetview"
11
+
12
+
13
+ # --------------------------------------------------------------------------- #
14
+ # user data (tiles, exports) - never write inside site-packages
15
+ # --------------------------------------------------------------------------- #
16
+ def _user_data_dir() -> pathlib.Path:
17
+ env = os.environ.get("OFFLINESTREETVIEW_HOME")
18
+ if env:
19
+ return pathlib.Path(env).expanduser()
20
+ if os.name == "nt":
21
+ base = pathlib.Path(os.environ.get("LOCALAPPDATA") or pathlib.Path.home())
22
+ else:
23
+ base = pathlib.Path(os.environ.get("XDG_DATA_HOME")
24
+ or (pathlib.Path.home() / ".local" / "share"))
25
+ return base / PACKAGE_NAME
26
+
27
+
28
+ USER_DATA_DIR = _user_data_dir()
29
+ DEFAULT_TILE_DIR = USER_DATA_DIR / "osm_tiles"
30
+ DEFAULT_EXPORT_DIR = USER_DATA_DIR / "exports"
31
+
32
+ # --- data source defaults (overridable on the configuration screen) ---
33
+ DEFAULT_CSV_PATH = os.environ.get("OFFLINESTREETVIEW_CSV_PATH", "")
34
+ DEFAULT_CSV_NAME = os.environ.get("OFFLINESTREETVIEW_CSV_NAME", "")
35
+
36
+ DEFAULT_LAT_COL = "lat"
37
+ DEFAULT_LON_COL = "lon"
38
+ DEFAULT_TIME_COL = "adj_time"
39
+
40
+ # columns used to build the front/back image file paths
41
+ DEFAULT_IMAGE_COLS = {
42
+ "front_path": "path_fr",
43
+ "front_file": "file_fr",
44
+ "back_path": "path_bk",
45
+ "back_file": "file_bk",
46
+ }
47
+
48
+ # legacy drive mappings used in the original project data
49
+ LEGACY_PATH_REPLACEMENTS = {
50
+ "/media/kuldeep/Elements1/Washington_proh_sep23/GoPro_video/":
51
+ "K:/washington_project_app/",
52
+ }
53
+
54
+ # numeric columns offered for the bar plot (only these are loaded)
55
+ DEFAULT_BAR_COLS = ["cpc_cor", "sp_cor", "bcc_kd_60sec"]
56
+
57
+ # --- image frame defaults (position & size, set before loading) ---
58
+ DEFAULT_IMG_WIDTH_PCT = 100 # image width inside its frame (%)
59
+ DEFAULT_IMG_HEIGHT_VH = 45 # image height (view-height units)
60
+ DEFAULT_X_OFFSET_PX = 0 # move images right (+) / left (-)
61
+ DEFAULT_Y_OFFSET_PX = 0 # move images down (+) / up (-)
62
+ DEFAULT_PANEL_PCT = 40 # width of the right images panel (% of screen)
63
+
64
+ # --- bar plot defaults (width slider removed; width is always 100%) ---
65
+ DEFAULT_BAR_HEIGHT_VH = 25 # bar plot height (vh)
66
+
67
+ # --- offline OpenStreetMap tiles ---
68
+ OSM_TILE_SERVER = "https://tile.openstreetmap.org"
69
+ DEFAULT_TILE_ZOOM = 18
70
+ OSM_TILE_BASE_URL = "/osm_tiles" # relative -> served by this same app
71
+
72
+ # --- map defaults ---
73
+ DEFAULT_MAP_ZOOM = 18
74
+ DEFAULT_MAP_OPACITY = 1.0 # 0.0 = transparent tiles, 1.0 = fully opaque
@@ -0,0 +1,183 @@
1
+ """plots.py - figure factories for the map and the bar chart."""
2
+ from __future__ import annotations
3
+
4
+ from uuid import uuid4
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+ import plotly.graph_objects as go
9
+
10
+
11
+ # English labels for known instruments (fallback = the column name itself)
12
+ BAR_LABELS = {
13
+ "cpc_cor": "Particle Number Concentration",
14
+ "sp_cor": "Concentration (µg/m³)",
15
+ "bcc_kd_60sec": "Concentration",
16
+ }
17
+
18
+
19
+ def _empty_figure():
20
+ return go.Figure()
21
+
22
+
23
+ def _new_uids(fig: go.Figure) -> go.Figure:
24
+ """Assign a fresh uid to every trace.
25
+
26
+ Workaround for the known plotly.js bug where Scattermapbox markers vanish
27
+ after a Plotly.react update if the trace uid stays the same (the hover area
28
+ remains but the marker is not painted).
29
+ """
30
+ for tr in fig.data:
31
+ tr.uid = str(uuid4())
32
+ return fig
33
+
34
+
35
+ # --------------------------------------------------------------------------- #
36
+ # MAP - dot + crosshair (+ optional ALL-DATA bubble/heatmap layer)
37
+ # --------------------------------------------------------------------------- #
38
+ def map_figure(df: pd.DataFrame, row: int, use_offline: bool = False,
39
+ zoom: int = 18, map_opacity: float = 1.0,
40
+ show_all_points: bool = False, bubble_column: str | None = None):
41
+ """Map centred on the current row.
42
+
43
+ - Red DOT at the current row; hovering pops the timestamp
44
+ - Floating red crosshair intersecting at the centroid of the map square
45
+ - Optional bubbble/heatmap layer: every (lat, lon, value) point of the
46
+ loaded CSV, coloured by the selected numeric column
47
+ - No legend
48
+ """
49
+ if df.empty or row < 0 or row >= len(df):
50
+ return _empty_figure()
51
+
52
+ lat, lon = float(df.iloc[row]["lat"]), float(df.iloc[row]["lon"])
53
+ timestamp = str(df.iloc[row]["adj_time"])
54
+
55
+ centroid_lat = float((df["lat"].min() + df["lat"].max()) / 2.0)
56
+ centroid_lon = float((df["lon"].min() + df["lon"].max()) / 2.0)
57
+
58
+ lat_span = float(df["lat"].max() - df["lat"].min()) or 1e-6
59
+ lon_span = float(df["lon"].max() - df["lon"].min()) or 1e-6
60
+ lat_pad = max(lat_span * 0.6, 0.0006)
61
+ lon_pad = max(lon_span * 0.6, 0.0006)
62
+
63
+ opacity = max(0.0, min(1.0, float(map_opacity)))
64
+
65
+ fig = go.Figure()
66
+
67
+ # # ---- crosshair: vertical line -----------------------------------------
68
+ # fig.add_trace(go.Scattermapbox(
69
+ # lat=[centroid_lat - lat_pad, centroid_lat + lat_pad],
70
+ # lon=[centroid_lon, centroid_lon],
71
+ # mode="lines", line=dict(color="red", width=3),
72
+ # opacity=0.85, hoverinfo="skip", showlegend=False, name="",
73
+ # ))
74
+
75
+ # # ---- crosshair: horizontal line ---------------------------------------
76
+ # fig.add_trace(go.Scattermapbox(
77
+ # lat=[centroid_lat, centroid_lat],
78
+ # lon=[centroid_lon - lon_pad, centroid_lon + lon_pad],
79
+ # mode="lines", line=dict(color="red", width=3),
80
+ # opacity=0.85, hoverinfo="skip", showlegend=False, name="",
81
+ # ))
82
+
83
+ # ---- OPTIONAL: all-data bubble / heatmap layer -------------------------
84
+ if show_all_points and bubble_column and bubble_column in df.columns:
85
+ vals = pd.to_numeric(df[bubble_column], errors="coerce")
86
+ valid = vals.notna()
87
+ if valid.sum() > 0:
88
+ sub_lat = df.loc[valid, "lat"].astype(float)
89
+ sub_lon = df.loc[valid, "lon"].astype(float)
90
+ v = vals[valid].astype(float)
91
+ vmin, vmax = float(v.min()), float(v.max())
92
+
93
+ # bubble size proportional to magnitude (sqrt scaling)
94
+ if vmax > vmin:
95
+ size = 5.0 + 22.0 * np.sqrt((v - vmin) / (vmax - vmin))
96
+ else:
97
+ size = np.full(len(v), 12.0)
98
+
99
+ hover_text = [
100
+ f"{t}<br>{bubble_column}: {val:,.2f}"
101
+ for t, val in zip(df.loc[valid, "adj_time"], v)
102
+ ]
103
+
104
+ fig.add_trace(go.Scattermapbox(
105
+ lat=sub_lat, lon=sub_lon,
106
+ mode="markers",
107
+ marker=dict(
108
+ size=size,
109
+ color=v,
110
+ colorscale="YlOrRd",
111
+ showscale=True,
112
+ opacity=0.65,
113
+ colorbar=dict(title=bubble_column, thickness=12, len=0.6),
114
+ ),
115
+ text=hover_text,
116
+ hoverinfo="text",
117
+ hovertemplate="%{text}<extra></extra>",
118
+ showlegend=False, name="",
119
+ ))
120
+
121
+ # ---- red DOT at current location (drawn LAST so it stays on top) -------
122
+ fig.add_trace(go.Scattermapbox(
123
+ lat=[lat], lon=[lon],
124
+ mode="markers",
125
+ marker=dict(size=14, color="red", opacity=0.95),
126
+ text=[timestamp],
127
+ hoverinfo="text",
128
+ hovertemplate="%{text}<extra></extra>",
129
+ showlegend=False, name="",
130
+ ))
131
+
132
+ # ---- map background ----------------------------------------------------
133
+ if use_offline:
134
+ fig.update_layout(mapbox=dict(
135
+ style="white-bg",
136
+ center={"lat": lat, "lon": lon},
137
+ zoom=zoom,
138
+ layers=[dict(sourcetype="raster",
139
+ source=["/osm_tiles/{z}/{x}/{y}.png"],
140
+ below="traces", opacity=opacity)],
141
+ ))
142
+ elif opacity >= 0.99:
143
+ fig.update_layout(mapbox=dict(
144
+ style="open-street-map",
145
+ center={"lat": lat, "lon": lon}, zoom=zoom,
146
+ ))
147
+ else:
148
+ fig.update_layout(mapbox=dict(
149
+ style="white-bg",
150
+ center={"lat": lat, "lon": lon}, zoom=zoom,
151
+ layers=[dict(sourcetype="raster",
152
+ source=["https://tile.openstreetmap.org/{z}/{x}/{y}.png"],
153
+ below="traces", opacity=opacity)],
154
+ ))
155
+
156
+ fig.update_layout(
157
+ showlegend=False,
158
+ margin=dict(l=0, r=0, t=0, b=0),
159
+ uirevision="washington-map", # keep the user's pan/zoom while sliding
160
+ )
161
+ return _new_uids(fig)
162
+
163
+
164
+ # --------------------------------------------------------------------------- #
165
+ # BAR CHART - one row, dynamic axis range for any numeric column
166
+ # --------------------------------------------------------------------------- #
167
+ def bar_figure(df: pd.DataFrame, row: int, column: str):
168
+ if df.empty or not column or column not in df.columns:
169
+ return _empty_figure()
170
+
171
+ values = pd.to_numeric(df[column], errors="coerce").dropna()
172
+ value = float(values.iloc[row]) if row < len(values) else 0.0
173
+ col_max = float(values.max()) if len(values) else 1.0
174
+ x_range = [0.0, col_max * 1.05 + 1e-6] if col_max > 0 else [0.0, 1.0]
175
+
176
+ fig = go.Figure(go.Bar(
177
+ x=[value], y=[column], orientation="h", marker=dict(color="blue"),
178
+ ))
179
+ fig.update_layout(
180
+ xaxis=dict(title=BAR_LABELS.get(column, column), range=x_range),
181
+ showlegend=False, margin=dict(l=0, r=0, t=0, b=0),
182
+ )
183
+ return fig
@@ -0,0 +1,102 @@
1
+ """tiles.py - offline OpenStreetMap tile downloader + local tile server."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import math
6
+ import pathlib
7
+ import urllib.request
8
+
9
+ from .config import DEFAULT_TILE_DIR, DEFAULT_TILE_ZOOM, OSM_TILE_SERVER, __version__
10
+
11
+ USER_AGENT = f"offlinestreetview/{__version__} (+https://pypi.org/project/offlinestreetview/)"
12
+
13
+
14
+ def deg2num(lat_deg: float, lon_deg: float, zoom: int) -> tuple[int, int]:
15
+ """Convert a lat/lon pair to the OSM (x, y) tile coordinate at a zoom level."""
16
+ lat_rad = math.radians(lat_deg)
17
+ n = 2.0 ** zoom
18
+ xtile = int((lon_deg + 180.0) / 360.0 * n)
19
+ ytile = int((1.0 - math.asinh(math.tan(lat_rad)) / math.pi) / 2.0 * n)
20
+ return xtile, ytile
21
+
22
+
23
+ def download_tile(zoom: int, x: int, y: int, tile_dir=None, server=None) -> pathlib.Path:
24
+ """Download a single OSM tile into the local offline folder (skips if cached)."""
25
+ tile_dir = pathlib.Path(tile_dir or DEFAULT_TILE_DIR)
26
+ server = server or OSM_TILE_SERVER
27
+ dest = tile_dir / str(zoom) / str(x) / f"{y}.png"
28
+ if dest.exists():
29
+ return dest
30
+
31
+ dest.parent.mkdir(parents=True, exist_ok=True)
32
+ url = f"{server}/{zoom}/{x}/{y}.png"
33
+ req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
34
+ with urllib.request.urlopen(req, timeout=15) as resp, open(dest, "wb") as fh:
35
+ fh.write(resp.read())
36
+ return dest
37
+
38
+
39
+ def download_tiles_for_bbox(lat_min: float, lat_max: float,
40
+ lon_min: float, lon_max: float,
41
+ zoom: int, tile_dir=None, server=None) -> tuple[int, int]:
42
+ """Download every tile covering a bounding box. Returns (downloaded, cached)."""
43
+ x0, y0 = deg2num(lat_max, lon_min, zoom) # top-left tile
44
+ x1, y1 = deg2num(lat_min, lon_max, zoom) # bottom-right tile
45
+ base = pathlib.Path(tile_dir or DEFAULT_TILE_DIR)
46
+ downloaded, cached = 0, 0
47
+ for x in range(x0, x1 + 1):
48
+ for y in range(y0, y1 + 1):
49
+ if (base / str(zoom) / str(x) / f"{y}.png").exists():
50
+ cached += 1
51
+ else:
52
+ download_tile(zoom, x, y, tile_dir, server)
53
+ downloaded += 1
54
+ return downloaded, cached
55
+
56
+
57
+ def tile_url_template(base_url: str = None, zoom: int = 18) -> str:
58
+ """Plotly raster source template pointing at the LOCAL tile server."""
59
+ base = (base_url or "").rstrip("/")
60
+ return f"{base}/{{z}}/{{x}}/{{y}}.png"
61
+
62
+
63
+ def register_tile_server(app, tile_dir=None):
64
+ """Mount a Flask route on the Dash app: /osm_tiles/<z>/<x>/<y>.png"""
65
+ from flask import abort, send_from_directory
66
+
67
+ tile_dir = pathlib.Path(tile_dir or DEFAULT_TILE_DIR)
68
+ tile_dir.mkdir(parents=True, exist_ok=True)
69
+
70
+ @app.server.route("/osm_tiles/<int:zoom>/<int:x>/<int:y>.png",
71
+ endpoint="offlinestreetview_osm_tiles")
72
+ def _serve_osm_tile(zoom: int, x: int, y: int):
73
+ dest = tile_dir / str(zoom) / str(x) / f"{y}.png"
74
+ if not dest.exists():
75
+ try:
76
+ download_tile(zoom, x, y, tile_dir)
77
+ except Exception:
78
+ abort(404)
79
+ return send_from_directory(tile_dir, f"{zoom}/{x}/{y}.png")
80
+
81
+
82
+ def cli():
83
+ parser = argparse.ArgumentParser(prog="offlinestreetview-tiles",
84
+ description="Download offline OpenStreetMap tiles")
85
+ parser.add_argument("--lat-min", type=float, required=True)
86
+ parser.add_argument("--lat-max", type=float, required=True)
87
+ parser.add_argument("--lon-min", type=float, required=True)
88
+ parser.add_argument("--lon-max", type=float, required=True)
89
+ parser.add_argument("--zoom", type=int, default=DEFAULT_TILE_ZOOM)
90
+ parser.add_argument("--tile-dir", default=None)
91
+ args = parser.parse_args()
92
+
93
+ dl, cached = download_tiles_for_bbox(
94
+ args.lat_min, args.lat_max, args.lon_min, args.lon_max,
95
+ args.zoom, tile_dir=args.tile_dir,
96
+ )
97
+ print(f"done: {dl} downloaded, {cached} already cached (zoom {args.zoom}) "
98
+ f"-> {args.tile_dir or DEFAULT_TILE_DIR}")
99
+
100
+
101
+ if __name__ == "__main__":
102
+ cli()
@@ -0,0 +1,148 @@
1
+ """utils.py - all reusable functionality of the Washington Viewer.
2
+
3
+ Every file/data operation lives here so main (app.py) and the callbacks stay
4
+ small and focused.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import base64
9
+ import os
10
+ from datetime import datetime
11
+
12
+ import pandas as pd
13
+
14
+ from .config import DEFAULT_EXPORT_DIR, DEFAULT_IMAGE_COLS, LEGACY_PATH_REPLACEMENTS as LEGACY_DRIVE_REPLACEMENTS
15
+
16
+ # legacy drive mappings used in the original project
17
+ LEGACY_DRIVE_REPLACEMENTS = {
18
+ "/media/kuldeep/Elements1/Washington_proh_sep23/GoPro_video/": "K:/washington_project_app/",
19
+ }
20
+
21
+
22
+ # --------------------------------------------------------------------------- #
23
+ # DATA LOADING (feature 3: load ONLY the requested numeric columns)
24
+ # --------------------------------------------------------------------------- #
25
+ def build_image_paths(df: pd.DataFrame, image_cols: dict | None = None) -> pd.DataFrame:
26
+ """Add image_path1/image_path2 columns combining path + file for both cameras."""
27
+ image_cols = image_cols or DEFAULT_IMAGE_COLS
28
+ out = df.copy()
29
+ out["image_path1"] = out[image_cols["front_path"]].astype(str) + out[image_cols["front_file"]].astype(str)
30
+ out["image_path2"] = out[image_cols["back_path"]].astype(str) + out[image_cols["back_file"]].astype(str)
31
+ for col in ("image_path1", "image_path2"):
32
+ for old, new in LEGACY_DRIVE_REPLACEMENTS.items():
33
+ out[col] = out[col].str.replace(old, new, regex=False)
34
+ return out
35
+
36
+
37
+ def load_dashboard_data(
38
+ csv_path: str,
39
+ csv_name: str,
40
+ bar_columns: list[str],
41
+ lat_col: str = "lat",
42
+ lon_col: str = "lon",
43
+ time_col: str = "adj_time",
44
+ image_cols: dict | None = None,
45
+ ):
46
+ """Read a lean dataframe containing ONLY the columns that are needed.
47
+
48
+ - geo/time columns,
49
+ - the four image path/file columns,
50
+ - the numeric columns the user asked for on the config screen.
51
+
52
+ Returns: (dataframe, loaded_bar_columns, missing_bar_columns)
53
+ """
54
+ image_cols = image_cols or DEFAULT_IMAGE_COLS
55
+ full_path = os.path.join(csv_path, csv_name)
56
+
57
+ # check which requested numeric columns actually exist
58
+ columns_in_file = list(pd.read_csv(full_path, nrows=1).columns)
59
+ loaded = [c for c in bar_columns if c in columns_in_file]
60
+ missing = [c for c in bar_columns if c not in columns_in_file]
61
+
62
+ # columns that are always required
63
+ required = [time_col, lat_col, lon_col] + list(image_cols.values())
64
+ keep = list(dict.fromkeys(required + loaded)) # preserve order, drop dups
65
+
66
+ # load ONLY those columns -> fast & memory-lean
67
+ df = pd.read_csv(full_path, usecols=lambda c: c in keep)
68
+
69
+ # normalise geo/time column names for the rest of the app
70
+ df = df.rename(columns={time_col: "adj_time", lat_col: "lat", lon_col: "lon"})
71
+ df = build_image_paths(df, image_cols)
72
+
73
+ order = ["adj_time", "lat", "lon",
74
+ image_cols["front_path"], image_cols["front_file"],
75
+ image_cols["back_path"], image_cols["back_file"],
76
+ "image_path1", "image_path2"] + loaded
77
+ df = df[[c for c in order if c in df.columns]]
78
+ return df, loaded, missing
79
+
80
+
81
+ # --------------------------------------------------------------------------- #
82
+ # IMAGE HELPERS
83
+ # --------------------------------------------------------------------------- #
84
+ def encode_image(path: str) -> str:
85
+ """Return a base64 data URI for an image file ("" if it cannot be read)."""
86
+ try:
87
+ with open(path, "rb") as fh:
88
+ data = base64.b64encode(fh.read()).decode("ascii")
89
+ return "data:image/png;base64," + data
90
+ except Exception:
91
+ return ""
92
+
93
+
94
+ def clamp_index(idx: int, total_rows: int) -> int:
95
+ """Clamp an index into the valid 0..total_rows-1 range."""
96
+ return max(0, min(total_rows - 1, idx))
97
+
98
+
99
+ def shifted_image_path(df: pd.DataFrame, row: int, shift: int, which: str) -> str:
100
+ """Image path for row+shift (clamped), used when image shifts are applied."""
101
+ idx = clamp_index(row + shift, len(df))
102
+ return df.iloc[idx][which]
103
+
104
+
105
+ # --------------------------------------------------------------------------- #
106
+ # EXPORT (shifted file assignments -> csv + summary)
107
+ # --------------------------------------------------------------------------- #
108
+ def export_shifted_csv(
109
+ df: pd.DataFrame,
110
+ shift1: int = 0,
111
+ shift2: int = 0,
112
+ file_fr_col: str = "file_fr",
113
+ file_bk_col: str = "file_bk",
114
+ out_root: str | None = None,
115
+ ):
116
+ """Write a new CSV that only shifts file_fr/file_bk, leaving paths intact."""
117
+ out_root = out_root or str(DEFAULT_EXPORT_DIR)
118
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
119
+ export_path = os.path.join(out_root, f"exported_shifted_data_{timestamp}")
120
+ os.makedirs(export_path, exist_ok=True)
121
+
122
+ df_export = df.copy()
123
+ original_fr = df_export[file_fr_col].astype(str).copy()
124
+ original_bk = df_export[file_bk_col].astype(str).copy()
125
+ total = len(df_export)
126
+
127
+ if shift1:
128
+ for idx in range(total):
129
+ df_export.at[idx, file_fr_col] = original_fr.iloc[clamp_index(idx + shift1, total)]
130
+ if shift2:
131
+ for idx in range(total):
132
+ df_export.at[idx, file_bk_col] = original_bk.iloc[clamp_index(idx + shift2, total)]
133
+
134
+ csv_path = os.path.join(export_path, f"shifted_data_{timestamp}.csv")
135
+ df_export.to_csv(csv_path, index=False)
136
+
137
+ summary_path = os.path.join(export_path, "shift_summary.txt")
138
+ with open(summary_path, "w") as f:
139
+ f.write("File Shift Summary\n")
140
+ f.write(f"Export Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
141
+ f.write(f"Total rows processed: {total}\n")
142
+ f.write(f"file_fr Shift: {shift1} positions\n")
143
+ f.write(f"file_bk Shift: {shift2} positions\n")
144
+ f.write("Only file_fr and file_bk were shifted; path_fr/path_bk are unchanged.\n")
145
+
146
+ fr_changes = int(sum(df_export[file_fr_col].astype(str) != original_fr)) if shift1 else 0
147
+ bk_changes = int(sum(df_export[file_bk_col].astype(str) != original_bk)) if shift2 else 0
148
+ return csv_path, fr_changes, bk_changes
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.4
2
+ Name: offlinestreetview
3
+ Version: 0.1.0
4
+ Summary: Offline street-level image dashboard: synced images, OpenStreetMap tiles, bar chart and image-shift export.
5
+ Author-email: Kuldeep Dixit <dixitkuldeep252@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Kuldeep252/offlinestreetview
8
+ Project-URL: Source, https://github.com/Kuldeep252/offlinestreetview
9
+ Project-URL: Issues, https://github.com/Kuldeep252/offlinestreetview/issues
10
+ Keywords: dash,plotly,openstreetmap,offline,dashboard,image,street-view
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Framework :: Dash
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Scientific/Engineering :: Visualization
21
+ Requires-Python: >=3.9
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: dash>=2.11
25
+ Requires-Dist: plotly<6
26
+ Requires-Dist: pandas>=1.3
27
+ Requires-Dist: numpy>=1.20
28
+ Requires-Dist: Flask>=2.0
29
+ Provides-Extra: dev
30
+ Requires-Dist: build>=1.0; extra == "dev"
31
+ Requires-Dist: twine>=4.0; extra == "dev"
32
+ Requires-Dist: pytest>=7.0; extra == "dev"
33
+ Dynamic: license-file
34
+
35
+ # Offline Street View
36
+
37
+ Modular Dash dashboard for street-level surveys: two synced images, an
38
+ OpenStreetMap map (online **or** fully offline tiles), a bar chart of any
39
+ numeric CSV column, image-shift controls and a shifted-CSV export.
40
+
41
+ ## Install
42
+ pip install offlinestreetview
43
+
44
+ ## Run
45
+ python -m offlinestreetview ## http://127.0.0.1:8050
46
+ python offlinestreetview --port 8070 --debug
47
+
48
+
49
+ Options: `--host`, `--port`, `--debug`, `--tile-dir`.
50
+
51
+ ## Offline map tiles
52
+ Enable "Use offline tiles" on the setup screen, or pre-download:
53
+
54
+ offlinestreetview-tiles --lat-min 38.89 --lat-max 38.95 \
55
+ --lon-min -77.06 --lon-max -77.00 --zoom 18
56
+
57
+ Tiles are stored in:
58
+ * `%LOCALAPPDATA%\offlinestreetview\osm_tiles` (Windows)
59
+ * `~/.local/share/offlinestreetview/osm_tiles` (Linux/macOS)
60
+
61
+ Override with the `OFFLINESTREETVIEW_HOME` environment variable, or `--tile-dir`.
62
+
63
+ ## Expected CSV columns
64
+ `adj_time`, `lat`, `lon`, `path_fr`, `file_fr`, `path_bk`, `file_bk`
65
+ + the numeric columns can be edited on the setup screen.
@@ -0,0 +1,14 @@
1
+ offlinestreetview/__init__.py,sha256=CciQXAgonvPmpK5S4m3n2fMJQVtuLi6rkj52w-gpX14,128
2
+ offlinestreetview/__main__.py,sha256=jLmyzKTmpTRI3lGiHMO2bGvU4kw0BVOq2J95lj22Qvs,60
3
+ offlinestreetview/app.py,sha256=R3O8KBDwDKF5KzkbVi5sks3Gqr4dONRTVJmuPqhKjKs,13830
4
+ offlinestreetview/callbacks.py,sha256=67hTbTdpgucKhI8ZW2tt6BcmQC81t_ntstdTc3mhIxs,15693
5
+ offlinestreetview/config.py,sha256=T_rc_h_VpJrJbCfyXSFPZV7TNJtYA8vRG67cbr0O6sQ,2650
6
+ offlinestreetview/plots.py,sha256=YKsdHOZnb6BgW5ZizLqCbHEgV8QMSGMYs-5TjRBkSc8,6851
7
+ offlinestreetview/tiles.py,sha256=FyEBmDt_NZn3WFczxubmHja_JgGujsPZCy9zIb_Yloo,4077
8
+ offlinestreetview/utils.py,sha256=FgcR_MLO9bnEGoXsTYrJlSQUDM4ln8C3-q3tTXLUAkw,6022
9
+ offlinestreetview-0.1.0.dist-info/licenses/LICENSE,sha256=xsXYy7_GEvMKIlGqpjrYhkIqBSRcHcPQnywBL0OqzuM,1069
10
+ offlinestreetview-0.1.0.dist-info/METADATA,sha256=rS3v-ovD1qmcRuoUI80-evI-hyViQrsbHnUQkLNu5Ag,2457
11
+ offlinestreetview-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
12
+ offlinestreetview-0.1.0.dist-info/entry_points.txt,sha256=fxcUO1BtYv4NYeW57ULrBG1RBVcHgrEDcmgYGaACw6s,119
13
+ offlinestreetview-0.1.0.dist-info/top_level.txt,sha256=khcS71yNtM_UJ3rlYetqeHIlgpmrZuSX25V9n-ka27I,18
14
+ offlinestreetview-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ offlinestreetview = offlinestreetview.app:main
3
+ offlinestreetview-tiles = offlinestreetview.tiles:cli
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kuldeep Dixit
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ offlinestreetview