diff --git a/doc/web-ui.md b/doc/web-ui.md index b5a3cf81..5cacf5ff 100644 --- a/doc/web-ui.md +++ b/doc/web-ui.md @@ -266,7 +266,7 @@ both modes. ## 5. What you can ask for -33 commands, grouped by what they tell you. Parameters are in `code`. +35 commands, grouped by what they tell you. Parameters are in `code`. ### Profile @@ -311,14 +311,19 @@ half the requests of `both`. | **Hashtags** | Hashtags used, most frequent first | | **Captions** | Post captions | | **Addresses** | Geotagged locations, reverse-geocoded, **plotted on a map** | +| **Travel route** | Chronological travel trajectory, distances between stops, and transit hops from geotags (geotags indicate tagged places, not verified physical presence) | | **Comments** | Every comment with author and post | | **Like totals** / **Comment totals** | Total, min, max, average — plus post previews | | **Media types** | How many posts are photos, videos, carousels, with views, collaborations and paid partnerships | | **Posting times** | Weekday × hour heatmap of when they post, and how often | +| **Sleep schedule** | Circadian quiet hours and timezone range (rough estimate, not evidence) | | **Photo descriptions** | Alt text of each photo, carousel slides included | All of these take `limit_posts`. +> [!NOTE] +> Travel routes and sleep schedules are based on public post metadata and geotags. They represent rough heuristic estimates, not evidence of physical presence or actual sleep routines. + > **On "Photo descriptions":** Instagram only returns alt text the author wrote > themselves — its automatic "May be an image of…" descriptions are no longer > exposed. On most accounts it comes back empty; the card then tells you how diff --git a/src/chronology_tracker.py b/src/chronology_tracker.py new file mode 100644 index 00000000..b59c0810 --- /dev/null +++ b/src/chronology_tracker.py @@ -0,0 +1,333 @@ +"""Chronology, Sleep Pattern & Travel Route Tracker for Instagram OSINT. + +Analyzes post timestamps and geotags to reconstruct: +1. Circadian sleep schedule & probable local timezone (rough estimate). +2. Chronological geolocation route, distances traveled, and travel hops. + +Note: Rough estimates, not evidence. Geotags and post timestamps do not prove +physical presence, and social media activity does not reliably reflect sleep. +""" +import math +from datetime import datetime, timezone +from typing import Any, Dict, List, Optional + + +def haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float: + """Calculate great-circle distance between two points in kilometers.""" + radius_earth_km = 6371.0 + dlat = math.radians(lat2 - lat1) + dlon = math.radians(lon2 - lon1) + a = ( + math.sin(dlat / 2.0) ** 2 + + math.cos(math.radians(lat1)) + * math.cos(math.radians(lat2)) + * math.sin(dlon / 2.0) ** 2 + ) + c = 2.0 * math.atan2(math.sqrt(a), math.sqrt(max(0.0, 1.0 - a))) + return round(radius_earth_km * c, 1) + + +def parse_timestamp(val: Any) -> Optional[datetime]: + """Parse various timestamp representations into UTC datetime.""" + if val is None: + return None + if isinstance(val, (int, float)): + try: + return datetime.fromtimestamp(val, tz=timezone.utc) + except Exception: + return None + if isinstance(val, str): + val = val.strip() + if val.isdigit(): + try: + return datetime.fromtimestamp(int(val), tz=timezone.utc) + except Exception: + return None + # ISO format try + try: + dt = datetime.fromisoformat(val.replace("Z", "+00:00")) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + return dt.astimezone(timezone.utc) + except Exception: + return None + return None + + +class SleepScheduleAnalyzer: + """Estimates sleep window and timezone range from publication timestamps. + + Disclaimer: Rough estimate, not evidence. Social media activity does not + reliably reflect sleep or physical presence (scheduled posts, nocturnal habits, + and irregular routines can significantly skew results). + """ + + def analyze(self, posts: List[Dict[str, Any]]) -> Dict[str, Any]: + """Infer sleep window and timezone from 24h activity histogram.""" + histogram = [0] * 24 + valid_posts = [] + + for p in posts: + raw_ts = ( + p.get("taken_at") + or p.get("taken_at_timestamp") + or p.get("timestamp") + ) + dt = parse_timestamp(raw_ts) + if dt: + histogram[dt.hour] += 1 + valid_posts.append((dt, p)) + + total_posts = len(valid_posts) + disclaimer_text = ( + "Rough estimate, not evidence. Social media activity does not " + "reliably reflect sleep or physical presence." + ) + + if total_posts < 3: + return { + "insufficient_data": True, + "disclaimer": disclaimer_text, + "total_analyzed": total_posts, + "histogram_utc": histogram, + "sleep_window_utc": None, + "estimated_timezone": "Unknown (Insufficient data)", + "confidence": "Low", + "is_ambiguous": True, + "circadian_anomalies": [], + } + + # 7-hour contiguous quiet window (wrapping 24h) + window_size = 7 + window_sums = [ + sum(histogram[(start + i) % 24] for i in range(window_size)) + for start in range(24) + ] + min_activity = min(window_sums) + tied_starts = [start for start, s in enumerate(window_sums) if s == min_activity] + + # Handle ties: pick the center of the longest contiguous run of tied start hours + def get_center_start(starts: List[int]) -> int: + if not starts: + return 0 + if len(starts) == 1: + return starts[0] + # Identify contiguous runs + runs = [] + curr = [starts[0]] + for i in range(1, len(starts)): + if starts[i] == starts[i - 1] + 1: + curr.append(starts[i]) + else: + runs.append(curr) + curr = [starts[i]] + runs.append(curr) + + # Check circular wrap (starts[0] == 0 and starts[-1] == 23) + if len(runs) > 1 and runs[0][0] == 0 and runs[-1][-1] == 23: + wrapped_run = runs[-1] + runs[0] + runs = runs[1:-1] + [wrapped_run] + + longest_run = max(runs, key=len) + mid_val = longest_run[len(longest_run) // 2] + return mid_val % 24 + + best_start = get_center_start(tied_starts) + best_end = (best_start + window_size) % 24 + + # Ambiguity: more than 1 tied window or completely flat + expected_window = total_posts * (window_size / 24.0) + depth = 1.0 - (min_activity / expected_window) if expected_window > 0 else 0.0 + is_ambiguous = len(tied_starts) > 1 or depth < 0.2 + + # Present timezone as a range / rough estimate: + # Assuming natural sleep window start falls between 22:00 and 01:00 local time: + def norm_offset(h: int) -> int: + while h > 14: + h -= 24 + while h < -12: + h += 24 + return h + + def fmt_tz(offset: int) -> str: + sign = "+" if offset >= 0 else "-" + return f"UTC{sign}{abs(offset):02d}:00" + + offset_min = norm_offset(22 - best_start) + offset_max = norm_offset(25 - best_start) + if offset_min > offset_max: + offset_min, offset_max = offset_max, offset_min + + tz_str = f"{fmt_tz(offset_min)} to {fmt_tz(offset_max)} (rough estimate)" + + # Confidence based on quiet window depth relative to average and ambiguity + if is_ambiguous or depth < 0.4 or total_posts < 8: + confidence = "Low" + elif total_posts >= 25 and depth >= 0.75: + confidence = "High" + else: + confidence = "Medium" + + # Detect nocturnal anomalies + anomalies = [] + for dt, p in valid_posts: + h = dt.hour + if best_start <= best_end: + in_window = best_start <= h < best_end + else: + in_window = (h >= best_start) or (h < best_end) + + if in_window: + anomalies.append({ + "post_id": str(p.get("id") or p.get("pk") or ""), + "timestamp_utc": dt.isoformat(), + "hour_utc": h, + "caption": ( + (p.get("caption") or {}).get("text") + if isinstance(p.get("caption"), dict) + else str(p.get("caption") or "") + )[:60], + }) + + return { + "insufficient_data": False, + "disclaimer": disclaimer_text, + "total_analyzed": total_posts, + "histogram_utc": histogram, + "sleep_window_utc": { + "start_hour": best_start, + "end_hour": best_end, + "duration_hours": window_size, + "posts_in_window": min_activity, + "candidate_start_hours": tied_starts, + }, + "estimated_timezone": tz_str, + "tz_offset_hours": round((offset_min + offset_max) / 2), + "tz_offset_range": [offset_min, offset_max], + "quiet_depth_ratio": round(depth, 2), + "is_ambiguous": is_ambiguous, + "confidence": confidence, + "circadian_anomalies": anomalies[:10], + } + + +class TravelRouteTracker: + """Reconstructs chronological travel trajectory from geotagged posts. + + Disclaimer: Geotags and post timestamps do not prove physical presence: + users frequently tag locations remotely, after traveling, or on old photos. + """ + + def analyze(self, posts: List[Dict[str, Any]]) -> Dict[str, Any]: + """Extract locations, sort chronologically, and compute travel legs.""" + geotagged = [] + + def _first_coord(*values): + for v in values: + if v is not None: + return v + return None + + for p in posts: + loc = p.get("location") or {} + lat = _first_coord(loc.get("lat"), loc.get("latitude"), p.get("lat")) + lng = _first_coord( + loc.get("lng"), loc.get("longitude"), loc.get("long"), p.get("lng") + ) + raw_ts = ( + p.get("taken_at") + or p.get("taken_at_timestamp") + or p.get("timestamp") + ) + dt = parse_timestamp(raw_ts) + + if lat is not None and lng is not None and dt: + try: + lat_f = float(lat) + lng_f = float(lng) + loc_name = ( + loc.get("name") + or loc.get("title") + or "Unknown location" + ) + geotagged.append({ + "post_id": str(p.get("id") or p.get("pk") or ""), + "timestamp": dt, + "timestamp_iso": dt.isoformat(), + "location_name": loc_name, + "city": loc.get("city") or "", + "lat": lat_f, + "lng": lng_f, + }) + except (ValueError, TypeError): + continue + + # Sort chronologically ascending + geotagged.sort(key=lambda x: x["timestamp"]) + + total_distance = 0.0 + hops = [] + unique_places = [] + seen_names = set() + + for i, stop in enumerate(geotagged): + name = stop["location_name"] + if name and name not in seen_names: + seen_names.add(name) + unique_places.append(name) + + leg_km = 0.0 + days_gap = 0.0 + speed_kmh = None + + if i > 0: + prev = geotagged[i - 1] + leg_km = haversine_km( + prev["lat"], prev["lng"], stop["lat"], stop["lng"] + ) + total_distance += leg_km + seconds_diff = max( + 1, (stop["timestamp"] - prev["timestamp"]).total_seconds() + ) + days_gap = round(seconds_diff / 86400.0, 1) + hours_diff = seconds_diff / 3600.0 + # Meaningful speed only computed for short intervals (<= 48 hours) + if 0 < hours_diff <= 48.0: + speed_kmh = round(leg_km / hours_diff, 1) + + # Classify transit using both distance and time gap + if leg_km == 0.0: + transit_type = "Same Location / Co-located" + elif days_gap > 3.0: + transit_type = f"Distant post ({leg_km:.0f} km, {days_gap:.0f}d gap)" + elif leg_km > 500: + transit_type = "Likely Flight / Fast Transit" + elif leg_km > 80: + transit_type = "Intercity Road / Rail Travel" + else: + transit_type = "Local / Stationary" + + hops.append({ + "sequence": i + 1, + "post_id": stop["post_id"], + "date": stop["timestamp_iso"][:10], + "datetime_utc": stop["timestamp_iso"], + "location": stop["location_name"], + "coordinates": [stop["lat"], stop["lng"]], + "distance_from_prev_km": leg_km, + "days_since_prev": days_gap, + "speed_kmh": speed_kmh, + "transit_type": transit_type, + }) + + return { + "disclaimer": ( + "Geotags indicate tagged locations, not verified physical presence " + "(posts may be retroactive or tagged remotely)." + ), + "total_geotagged_stops": len(geotagged), + "total_distance_km": round(total_distance, 1), + "unique_locations_count": len(unique_places), + "unique_locations": unique_places, + "route_hops": hops, + } diff --git a/src/osint_service.py b/src/osint_service.py index 7c28193c..7b9c1c60 100644 --- a/src/osint_service.py +++ b/src/osint_service.py @@ -1515,6 +1515,24 @@ def diff_snapshots(self, old_id: Optional[int] = None, new_id: Optional[int] = N raise OsintServiceError(f"Not enough snapshots to compare for @{self.target}. At least 2 snapshots are required.") return diff + def get_sleep_schedule(self, limit_posts: Optional[int] = 50) -> dict: + """Infer target's circadian sleep pattern, quiet hours, and timezone range (rough estimate).""" + self._require_public() + from src.chronology_tracker import SleepScheduleAnalyzer + limit_posts = max(1, min(int(limit_posts or 50), 100)) + posts = self._get_feed(limit=limit_posts) + analyzer = SleepScheduleAnalyzer() + return analyzer.analyze(posts) + + def get_travel_route(self, limit_posts: Optional[int] = 50) -> dict: + """Reconstruct target's chronological travel trajectory, distances, and transit legs from geotags.""" + self._require_public() + from src.chronology_tracker import TravelRouteTracker + limit_posts = max(1, min(int(limit_posts or 50), 100)) + posts = self._get_feed(limit=limit_posts) + tracker = TravelRouteTracker() + return tracker.analyze(posts) + def check_hiker_token(token: str) -> dict: """Verify a token by asking HikerAPI for its own balance. diff --git a/src/web/static/index.html b/src/web/static/index.html index 25542091..f6ba9cd8 100644 --- a/src/web/static/index.html +++ b/src/web/static/index.html @@ -1806,6 +1806,8 @@ get_total_likes: ["❤️", "Like totals", "Total, min, max and average likes per post."], get_media_type: ["🖼️", "Media types", "How many posts are photos, videos or carousels, with views, collaborations and paid partnerships."], get_posting_times: ["🕒", "Posting times", "Which days and hours they post on (heatmap) and how often."], + get_sleep_schedule: ["🌙", "Sleep schedule", "Circadian quiet hours and timezone range (rough estimate, not evidence)."], + get_travel_route: ["🗺️", "Travel route", "Chronological travel trajectory and distances between geotagged posts (geotags indicate tagged places, not physical presence)."], get_photo_descriptions: ["🔍", "Photo descriptions", "Alt text of the photos (what they show), when the post's author wrote it."], get_comment_data: ["💬", "Comments", "Every comment on the posts, with its author and post."], get_people_who_commented: ["💬", "Who commented", "Accounts that commented on the posts, by number of comments."], @@ -1832,7 +1834,7 @@ const TOOL_GROUPS = [ ["Profile", ["get_user_info", "get_account_about", "snapshot_profile", "diff_profile", "get_user_propic", "get_user_stories", "get_highlights", "get_user_photos"]], ["Network", ["get_followers", "get_followings", "audit_followers", "get_suggested_profiles", "compare_with", "get_people_who_tagged", "get_tagged_posts", "get_people_tagged_by_user", "get_people_who_commented"]], - ["Content", ["get_hashtags", "get_captions", "get_addrs", "get_comment_data", "get_total_likes", "get_total_comments", "get_media_type", "get_posting_times", "get_photo_descriptions"]], + ["Content", ["get_hashtags", "get_captions", "get_addrs", "get_travel_route", "get_comment_data", "get_total_likes", "get_total_comments", "get_media_type", "get_posting_times", "get_sleep_schedule", "get_photo_descriptions"]], ["Contacts", ["get_followers_email", "get_followings_email", "get_followers_phone", "get_followings_phone"]], ["Search (no target)", ["search_hashtag", "search_location", "get_post_comments", "search_public_context", "search_cross_platform"]], ]; @@ -2953,6 +2955,100 @@ `; } + // ---- Sleep Schedule & Circadian Analyzer ---- + function renderSleepSchedule(result) { + if (result.insufficient_data) { + return `

Insufficient timestamp data (less than 3 posts with valid timestamps) to determine sleep patterns.

`; + } + const win = result.sleep_window_utc || {}; + const tz = result.estimated_timezone || "UTC"; + const conf = result.confidence || "Low"; + const confClass = conf === "High" ? "ok" : (conf === "Medium" ? "accent" : "muted"); + + const maxPosts = Math.max(1, ...(result.histogram_utc || [])); + const bars = (result.histogram_utc || []).map((cnt, h) => { + const inSleep = win.start_hour !== undefined && ( + win.start_hour <= win.end_hour + ? (h >= win.start_hour && h < win.end_hour) + : (h >= win.start_hour || h < win.end_hour) + ); + const pct = Math.round((cnt / maxPosts) * 100); + const bg = inSleep ? "rgba(99, 102, 241, 0.4)" : "var(--accent)"; + return `
+ ${cnt || ""} +
+
+
+ ${h} +
`; + }).join(""); + + const anomalies = (result.circadian_anomalies || []).map(a => ` +
+ ${escapeHtml(a.timestamp_utc)} (${a.hour_utc}:00 UTC): ${escapeHtml(a.caption || "No caption")} +
+ `).join(""); + + return ` +
+
Estimated Timezone${escapeHtml(tz)}
+
Inferred Sleep Window${win.start_hour}:00 - ${win.end_hour}:00 UTC (${win.duration_hours}h)
+
Confidence${escapeHtml(conf)}
+
Analyzed Posts${result.total_analyzed || 0}
+
+
+
24h Activity Distribution (UTC hours, purple bars denote quiet / sleep period):
+
${bars}
+
+ ${anomalies ? `
🚨 Nocturnal / Jet-Lag Activity Incidents:${anomalies}
` : ""} + `; + } + + // ---- Travel Route & Timeline Tracker ---- + function renderTravelRoute(result) { + const hops = result.route_hops || []; + if (hops.length === 0) { + return `

No geotagged locations found across the scanned posts to reconstruct a travel route.

`; + } + + const items = hops.map(h => { + const isTransit = h.distance_from_prev_km > 0; + const badgeKind = h.distance_from_prev_km > 500 ? "err" : (h.distance_from_prev_km > 80 ? "accent" : "muted"); + const transitBadge = isTransit + ? `
+ ↓ + 🚗 ${h.distance_from_prev_km} km (${h.transit_type}) + ⏱️ +${h.days_since_prev} days + ${h.speed_kmh ? `avg ~${h.speed_kmh} km/h` : ""} +
` + : ""; + + return ` + ${transitBadge} +
+ #${h.sequence} +
+
${escapeHtml(h.location)}
+
📅 ${escapeHtml(h.date)} (${h.coordinates[0].toFixed(3)}, ${h.coordinates[1].toFixed(3)})
+
+ 📍 Map +
+ `; + }).join(""); + + const travelDisclaimer = `

Geotags indicate tagged locations, not verified physical presence (posts may be retroactive or tagged remotely).

`; + return travelDisclaimer + ` +
+
Total Distance Traveled${result.total_distance_km} km
+
Geotagged Stops${result.total_geotagged_stops}
+
Unique Locations${result.unique_locations_count}
+
+
+ ${items} +
+ `; + } + // ---- Story Highlights (archived stories pinned on the profile) ---- function renderHighlights(items) { const cells = items.map((h) => { @@ -3700,6 +3796,8 @@ if ("common_followers" in result || "common_followings" in result) return renderCompare(result); if ("hashtag" in result || "place" in result) return renderSearch(result); if (Array.isArray(result.timestamps)) return renderPostingTimes(result); + if ("sleep_window_utc" in result && "histogram_utc" in result) return renderSleepSchedule(result); + if ("route_hops" in result && "total_distance_km" in result) return renderTravelRoute(result); if (Array.isArray(result.descriptions)) return renderDescriptions(result); if (result.has_changes !== undefined && Array.isArray(result.summary)) return renderDiffResult(result); if (result.avatar_hash !== undefined && result.timestamp) return renderSnapshotResult(result); diff --git a/src/web/tools.py b/src/web/tools.py index bd668952..61132d32 100644 --- a/src/web/tools.py +++ b/src/web/tools.py @@ -348,6 +348,22 @@ def get_people_tagged_by_user(limit_posts: Optional[int] = None) -> str: """ return _call(service.get_people_tagged_by_user, limit_posts=limit_posts) + def get_sleep_schedule(limit_posts: Optional[int] = 50) -> str: + """Infer target's circadian quiet hours and timezone range (rough estimate, not evidence). + + Args: + limit_posts: Number of recent posts to analyze for temporal activity (default: 50). + """ + return _call(service.get_sleep_schedule, limit_posts=limit_posts) + + def get_travel_route(limit_posts: Optional[int] = 50) -> str: + """Reconstruct target's chronological travel trajectory and distances between geotags. + + Args: + limit_posts: Number of recent posts to scan for geotags (default: 50). + """ + return _call(service.get_travel_route, limit_posts=limit_posts) + def get_user_photos(limit: Optional[int] = None) -> str: """Get direct CDN URLs for the target's posted photos (no download, just the URLs and media ids). @@ -521,6 +537,8 @@ def get_followings_phone(match_limit: Optional[int] = 20, max_checks: Optional[i get_people_who_tagged, get_tagged_posts, get_people_tagged_by_user, + get_sleep_schedule, + get_travel_route, get_user_photos, get_user_propic, get_user_stories, diff --git a/tests/test_chronology_travel.py b/tests/test_chronology_travel.py new file mode 100644 index 00000000..a99ae190 --- /dev/null +++ b/tests/test_chronology_travel.py @@ -0,0 +1,269 @@ +"""Unit tests for Chronology, Sleep Pattern & Travel Route Tracker.""" +from datetime import datetime, timezone +from unittest.mock import MagicMock + +import pytest + +from src.chronology_tracker import ( + SleepScheduleAnalyzer, + TravelRouteTracker, + haversine_km, + parse_timestamp, +) +from src.osint_service import OsintgramService, PrivateProfileError +from src.web.tools import build_tools, tool_specs + + +def test_haversine_km(): + # London (51.5074, -0.1278) to Paris (48.8566, 2.3522) ~ 343 km + dist = haversine_km(51.5074, -0.1278, 48.8566, 2.3522) + assert 340 <= dist <= 350 + + # Same coordinate is 0 km + assert haversine_km(52.2297, 21.0122, 52.2297, 21.0122) == 0.0 + + +def test_parse_timestamp(): + dt_epoch = parse_timestamp(1700000000) + assert dt_epoch == datetime(2023, 11, 14, 22, 13, 20, tzinfo=timezone.utc) + + dt_str = parse_timestamp("1700000000") + assert dt_str == datetime(2023, 11, 14, 22, 13, 20, tzinfo=timezone.utc) + + dt_iso = parse_timestamp("2024-05-10T15:30:00Z") + assert dt_iso == datetime(2024, 5, 10, 15, 30, tzinfo=timezone.utc) + + assert parse_timestamp(None) is None + assert parse_timestamp("invalid-date") is None + + +def test_sleep_schedule_insufficient_data(): + analyzer = SleepScheduleAnalyzer() + res = analyzer.analyze([{"taken_at": 1700000000}]) + assert res["insufficient_data"] is True + assert res["total_analyzed"] == 1 + + +def test_sleep_schedule_pattern_and_anomalies(): + analyzer = SleepScheduleAnalyzer() + + # Create posts between 08:00 and 22:00 UTC (quiet window 23:00 - 06:00 UTC) + posts = [] + base_ts = 1700000000 # Nov 14, 2023 + for hour in range(8, 22): + dt = datetime(2024, 1, 15, hour, 15, tzinfo=timezone.utc) + posts.append({"id": f"p_{hour}", "taken_at": dt.timestamp()}) + + # Add a nocturnal anomaly at 02:30 UTC + dt_night = datetime(2024, 1, 16, 2, 30, tzinfo=timezone.utc) + posts.append({ + "id": "p_night", + "taken_at": dt_night.timestamp(), + "caption": {"text": "Can't sleep, jet lag!"}, + }) + + res = analyzer.analyze(posts) + assert res["insufficient_data"] is False + assert res["total_analyzed"] == len(posts) + + win = res["sleep_window_utc"] + assert win is not None + # Quietest window starts around 23:00 - 00:00 UTC + assert 22 <= win["start_hour"] or win["start_hour"] <= 1 + assert "UTC" in res["estimated_timezone"] + + # Nocturnal anomaly detected + assert len(res["circadian_anomalies"]) >= 1 + assert any(a["post_id"] == "p_night" for a in res["circadian_anomalies"]) + + +def test_travel_route_tracker(): + tracker = TravelRouteTracker() + + posts = [ + # Stop 1: Warsaw (2024-01-01) + { + "id": "stop1", + "taken_at": datetime(2024, 1, 1, 12, 0, tzinfo=timezone.utc).timestamp(), + "location": {"name": "Warsaw Old Town", "lat": 52.2297, "lng": 21.0122}, + }, + # Stop 2: Berlin (2024-01-05) ~517 km from Warsaw + { + "id": "stop2", + "taken_at": datetime(2024, 1, 5, 12, 0, tzinfo=timezone.utc).timestamp(), + "location": {"name": "Berlin Alexanderplatz", "lat": 52.5200, "lng": 13.4050}, + }, + # Stop 3: Paris (2024-01-10) ~878 km from Berlin + { + "id": "stop3", + "taken_at": datetime(2024, 1, 10, 12, 0, tzinfo=timezone.utc).timestamp(), + "location": {"name": "Eiffel Tower", "lat": 48.8584, "lng": 2.2945}, + }, + ] + + res = tracker.analyze(posts) + assert res["total_geotagged_stops"] == 3 + assert res["unique_locations_count"] == 3 + assert res["total_distance_km"] > 1300 + + hops = res["route_hops"] + assert len(hops) == 3 + assert hops[0]["location"] == "Warsaw Old Town" + assert hops[0]["distance_from_prev_km"] == 0.0 + + assert hops[1]["location"] == "Berlin Alexanderplatz" + assert 500 <= hops[1]["distance_from_prev_km"] <= 530 + assert hops[1]["days_since_prev"] == 4.0 + assert "Distant post" in hops[1]["transit_type"] + assert hops[1]["speed_kmh"] is None # Long gap > 48h, speed is not computed + + assert hops[2]["location"] == "Eiffel Tower" + assert 850 <= hops[2]["distance_from_prev_km"] <= 900 + assert hops[2]["days_since_prev"] == 5.0 + + +def test_osint_service_sleep_and_travel_integration(): + mock_api = MagicMock() + mock_api.user_by_username_v2.return_value = { + "user": {"pk": "100", "username": "alice", "is_private": False} + } + mock_api.user_medias_g2.return_value = { + "response": { + "items": [ + { + "id": "post_1", + "taken_at": 1700000000, + "location": {"name": "Rome Colosseum", "lat": 41.8902, "lng": 12.4922}, + }, + { + "id": "post_2", + "taken_at": 1700100000, + "location": {"name": "Milan Duomo", "lat": 45.4642, "lng": 9.1919}, + }, + ] + }, + "next_page_id": None, + } + + service = OsintgramService("alice", mock_api) + sleep_data = service.get_sleep_schedule(limit_posts=10) + assert "sleep_window_utc" in sleep_data + + travel_data = service.get_travel_route(limit_posts=10) + assert travel_data["total_geotagged_stops"] == 2 + assert travel_data["total_distance_km"] > 400 + + +def test_private_profile_guard(): + mock_api = MagicMock() + mock_api.user_by_username_v2.return_value = { + "user": {"pk": "100", "username": "alice", "is_private": True} + } + service = OsintgramService("alice", mock_api) + + with pytest.raises(PrivateProfileError): + service.get_sleep_schedule() + + with pytest.raises(PrivateProfileError): + service.get_travel_route() + + +def test_tools_specs_and_execution(): + specs = tool_specs() + sleep_spec = next((s for s in specs if s["name"] == "get_sleep_schedule"), None) + assert sleep_spec is not None + assert any(p["name"] == "limit_posts" for p in sleep_spec["params"]) + + travel_spec = next((s for s in specs if s["name"] == "get_travel_route"), None) + assert travel_spec is not None + assert any(p["name"] == "limit_posts" for p in travel_spec["params"]) + + mock_service = MagicMock() + mock_service.get_sleep_schedule.return_value = {"confidence": "High"} + mock_service.get_travel_route.return_value = {"total_distance_km": 120.0} + + tools = build_tools(mock_service) + sleep_fn = next((t for t in tools if t.__name__ == "get_sleep_schedule"), None) + travel_fn = next((t for t in tools if t.__name__ == "get_travel_route"), None) + + assert sleep_fn is not None and "High" in sleep_fn(limit_posts=10) + assert travel_fn is not None and "120" in travel_fn(limit_posts=10) + + +def test_sleep_schedule_ties_in_histogram(): + analyzer = SleepScheduleAnalyzer() + + # Create posts only at hours 12:00, 13:00, 14:00 (multiple 7-hour windows have 0 posts) + posts = [ + {"id": "p1", "taken_at": datetime(2024, 1, 1, 12, 0, tzinfo=timezone.utc).timestamp()}, + {"id": "p2", "taken_at": datetime(2024, 1, 1, 13, 0, tzinfo=timezone.utc).timestamp()}, + {"id": "p3", "taken_at": datetime(2024, 1, 1, 14, 0, tzinfo=timezone.utc).timestamp()}, + ] + + res = analyzer.analyze(posts) + assert res["is_ambiguous"] is True + assert len(res["sleep_window_utc"]["candidate_start_hours"]) > 1 + # Check that center of run was picked, not just first start hour (0) + assert res["sleep_window_utc"]["start_hour"] > 0 + assert "rough estimate" in res["estimated_timezone"] + + +def test_travel_route_600km_over_long_gap(): + tracker = TravelRouteTracker() + posts = [ + { + "id": "p1", + "taken_at": datetime(2024, 1, 1, 10, 0, tzinfo=timezone.utc).timestamp(), + "location": {"name": "Munich", "lat": 48.1351, "lng": 11.5820}, + }, + # 600km away, 90 days later + { + "id": "p2", + "taken_at": datetime(2024, 4, 1, 10, 0, tzinfo=timezone.utc).timestamp(), + "location": {"name": "Hamburg", "lat": 53.5511, "lng": 9.9937}, + }, + ] + res = tracker.analyze(posts) + hops = res["route_hops"] + assert len(hops) == 2 + assert 590 <= hops[1]["distance_from_prev_km"] <= 630 + assert hops[1]["days_since_prev"] >= 90.0 + # Over distant dates, transit label should be neutral and NOT claimed as a Flight + assert "Flight" not in hops[1]["transit_type"] + assert "Distant post" in hops[1]["transit_type"] + assert hops[1]["speed_kmh"] is None + + +def test_travel_route_coordinate_equal_to_zero(): + tracker = TravelRouteTracker() + posts = [ + { + "id": "null_island", + "taken_at": datetime(2024, 1, 1, 12, 0, tzinfo=timezone.utc).timestamp(), + # Coordinates are exactly 0.0 (Null Island in Gulf of Guinea) + "location": {"name": "Null Island Buoy", "lat": 0.0, "lng": 0.0}, + }, + { + "id": "accra", + "taken_at": datetime(2024, 1, 2, 12, 0, tzinfo=timezone.utc).timestamp(), + "location": {"name": "Accra", "lat": 5.6037, "lng": -0.1870}, + }, + ] + res = tracker.analyze(posts) + # 0.0 coordinates should NOT be dropped + assert res["total_geotagged_stops"] == 2 + assert res["route_hops"][0]["coordinates"] == [0.0, 0.0] + assert res["route_hops"][0]["location"] == "Null Island Buoy" + + +def test_service_limit_posts_cap(): + mock_api = MagicMock() + mock_api.user_by_username_v2.return_value = { + "user": {"pk": "100", "username": "alice", "is_private": False} + } + mock_api.user_medias_g2.return_value = {"response": {"items": []}, "next_page_id": None} + service = OsintgramService("alice", mock_api) + + service.get_sleep_schedule(limit_posts=999) + args, kwargs = mock_api.user_medias_g2.call_args + assert kwargs.get("amount", 0) <= 33 or kwargs.get("limit", 0) <= 100