Add files via upload

This commit is contained in:
FatihMakes authored and GitHub committed 2026-04-19 15:22:49 +03:00
1 parent 320d933f08
commit cd70cb7796
27 files changed
+5807 -3538

No files matched your search

+110 -170
View File
@@ -1,37 +1,19 @@
# actions/flight_finder.py
# MARK XXV — Flight Finder
#
# Searches for flights using Google Flights via browser_control.
# Results are spoken by JARVIS. Optionally saved to Notepad or opened in browser.
#
# Flow:
# 1. Parse origin, destination, date, passengers from parameters
# 2. Open Google Flights via browser_control
# 3. Fill in search fields
# 4. Scrape results via get_text
# 5. Parse with Gemini → structured flight data
# 6. Speak top results
# 7. Optionally save to Notepad or keep browser open
#
# Cross-platform: Windows, macOS, Linux
# No API key required — Google Flights is free to access
import json
import re
import sys
import subprocess
import platform
import sys
from datetime import datetime, timedelta
from pathlib import Path
from config import is_windows, is_mac, is_linux
def get_base_dir() -> Path:
def _get_base_dir() -> Path:
if getattr(sys, "frozen", False):
return Path(sys.executable).parent
return Path(__file__).resolve().parent.parent
BASE_DIR = get_base_dir()
BASE_DIR = _get_base_dir()
API_CONFIG_PATH = BASE_DIR / "config" / "api_keys.json"
@@ -39,34 +21,42 @@ def _get_api_key() -> str:
with open(API_CONFIG_PATH, "r", encoding="utf-8") as f:
return json.load(f)["gemini_api_key"]
_MONTH_MAP: dict[str, int] = {
"january": 1, "february": 2, "march": 3, "april": 4,
"may": 5, "june": 6, "july": 7, "august": 8,
"september": 9, "october": 10, "november": 11, "december": 12,
"ocak": 1, "şubat": 2, "mart": 3, "nisan": 4,
"mayıs": 5, "haziran": 6, "temmuz": 7, "ağustos": 8,
"eylül": 9, "ekim": 10, "kasım": 11, "aralık": 12,
}
_RELATIVE_MAP_KEYS = {
"today", "bugün",
"tomorrow", "yarın",
}
def _parse_date(raw: str) -> str:
"""
Converts natural language date to YYYY-MM-DD.
Handles: '15 Mart', 'March 15', '2025-03-15', 'next friday', etc.
Falls back to Gemini for ambiguous inputs.
"""
raw = raw.strip()
raw = raw.strip()
lower = raw.lower()
today = datetime.now()
if re.match(r"\d{4}-\d{2}-\d{2}", raw):
return raw
for fmt in ("%d/%m/%Y", "%m/%d/%Y", "%d.%m.%Y", "%d-%m-%Y"):
try:
return datetime.strptime(raw, fmt).strftime("%Y-%m-%d")
except ValueError:
pass
today = datetime.now()
lower = raw.lower()
relative_map = {
"today": today,
"tomorrow": today + timedelta(days=1),
"bugün": today,
"yarın": today + timedelta(days=1),
relative = {
"today": today, "bugün": today,
"tomorrow": today + timedelta(days=1),
"yarın": today + timedelta(days=1),
}
for key, val in relative_map.items():
for key, val in relative.items():
if key in lower:
return val.strftime("%Y-%m-%d")
@@ -74,27 +64,18 @@ def _parse_date(raw: str) -> str:
import google.generativeai as genai
genai.configure(api_key=_get_api_key())
model = genai.GenerativeModel("gemini-2.5-flash-lite")
today_str = today.strftime("%Y-%m-%d")
response = model.generate_content(
f"Today is {today_str}. Convert this date to YYYY-MM-DD format: '{raw}'. "
f"Today is {today.strftime('%Y-%m-%d')}. "
f"Convert this date expression to YYYY-MM-DD: '{raw}'. "
f"Return ONLY the date string, nothing else."
)
result = response.text.strip()
if re.match(r"\d{4}-\d{2}-\d{2}", result):
return result
except Exception:
pass
except Exception as e:
print(f"[FlightFinder] ⚠️ Gemini date parse failed: {e}")
month_map = {
"january": 1, "february": 2, "march": 3, "april": 4,
"may": 5, "june": 6, "july": 7, "august": 8,
"september": 9,"october": 10, "november": 11, "december": 12,
"january": 1, "ocak": 1, "şubat": 2, "mart": 3,
"nisan": 4, "mayıs": 5, "haziran": 6, "temmuz": 7,
"ağustos": 8, "eylül": 9, "ekim": 10, "kasım": 11,
"aralık": 12,
}
for month_name, month_num in month_map.items():
for month_name, month_num in _MONTH_MAP.items():
if month_name in lower:
day_match = re.search(r"\d{1,2}", raw)
if day_match:
@@ -102,8 +83,16 @@ def _parse_date(raw: str) -> str:
year = today.year if month_num >= today.month else today.year + 1
return f"{year}-{month_num:02d}-{day:02d}"
# Last resort: today
print(f"[FlightFinder] ⚠️ Could not parse date '{raw}' — using today.")
return today.strftime("%Y-%m-%d")
_CABIN_CODE: dict[str, str] = {
"economy": "1",
"premium": "2",
"business": "3",
"first": "4",
}
def _build_google_flights_url(
@@ -114,33 +103,23 @@ def _build_google_flights_url(
passengers: int = 1,
cabin: str = "economy",
) -> str:
"""
Builds a Google Flights URL with pre-filled search parameters.
Uses the direct search URL format.
"""
cabin_map = {
"economy": "1",
"premium": "2",
"business": "3",
"first": "4",
}
cabin_code = cabin_map.get(cabin.lower(), "1")
base = "https://www.google.com/travel/flights"
cabin_code = _CABIN_CODE.get(cabin.lower(), "1")
base = "https://www.google.com/travel/flights"
# Google Flights accepts these query params for pre-filling
if return_date:
url = (
f"{base}?q=Flights+from+{origin}+to+{destination}"
f"+on+{date}+returning+{return_date}"
f"&curr=TRY"
)
trip = f"Flights+from+{origin}+to+{destination}+on+{date}+returning+{return_date}"
else:
url = (
f"{base}?q=Flights+from+{origin}+to+{destination}+on+{date}"
f"&curr=TRY"
)
trip = f"Flights+from+{origin}+to+{destination}+on+{date}"
return url
return (
f"{base}"
f"?q={trip}"
f"&tfs=CBwQAhoeEgoyMDI1LTAzLTE1agcIARIDSVNUcgcIARIDTEhS"
f"&curr=USD"
f"&cabin={cabin_code}"
f"&adults={passengers}"
)
@@ -152,12 +131,8 @@ def _search_flights_browser(
passengers: int,
cabin: str,
) -> tuple[str, str]:
"""
Opens Google Flights in browser, waits for results, scrapes text.
Returns (raw_text, page_url).
"""
from actions.browser_control import browser_control
import time
from actions.browser_control import browser_control
url = _build_google_flights_url(
origin, destination, date, return_date, passengers, cabin
@@ -165,11 +140,10 @@ def _search_flights_browser(
print(f"[FlightFinder] 🌐 Opening: {url}")
browser_control({"action": "go_to", "url": url})
time.sleep(5)
result = browser_control({"action": "get_text"})
return result or "", url
time.sleep(5)
raw = browser_control({"action": "get_text"})
return (raw or ""), url
def _parse_flights_with_gemini(
raw_text: str,
@@ -177,10 +151,6 @@ def _parse_flights_with_gemini(
destination: str,
date: str,
) -> list[dict]:
"""
Sends raw page text to Gemini and extracts structured flight data.
Returns list of flight dicts.
"""
import google.generativeai as genai
genai.configure(api_key=_get_api_key())
@@ -189,47 +159,41 @@ def _parse_flights_with_gemini(
system_instruction=(
"You are a flight data extraction expert. "
"Extract flight information from raw webpage text. "
"Return ONLY valid JSON array. No explanation, no markdown."
)
"Return ONLY valid JSON — no markdown, no explanation."
),
)
truncated = raw_text[:12000]
prompt = (
f"Extract flight options from {origin} to {destination} on {date} "
f"from this Google Flights page text:\n\n{truncated}\n\n"
f"from this Google Flights page text:\n\n{raw_text[:12000]}\n\n"
f"Return a JSON array of up to 5 flights:\n"
f'[{{"airline": "...", "departure": "HH:MM", "arrival": "HH:MM", '
f'"duration": "Xh Ym", "stops": 0, "price": "...", "currency": "..."}}]\n'
f'[{{"airline":"...","departure":"HH:MM","arrival":"HH:MM",'
f'"duration":"Xh Ym","stops":0,"price":"...","currency":"USD"}}]\n'
f"If no flights found, return: []"
)
try:
response = model.generate_content(prompt)
text = response.text.strip()
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
text = re.sub(r"```(?:json)?", "", response.text).strip().rstrip("`").strip()
flights = json.loads(text)
return flights if isinstance(flights, list) else []
except Exception as e:
print(f"[FlightFinder] ⚠️ Parse failed: {e}")
print(f"[FlightFinder] ⚠️ Gemini parse failed: {e}")
return []
def _format_spoken(
flights: list[dict],
origin: str,
destination: str,
date: str,
) -> str:
"""Formats flights for spoken output — concise and natural."""
if not flights:
return (
f"I couldn't find any flights from {origin} to {destination} "
f"on {date}, sir. The page may not have loaded correctly."
)
lines = [f"Here are the flights from {origin} to {destination} on {date}, sir."]
lines = [f"Here are the top flights from {origin} to {destination} on {date}, sir."]
for i, f in enumerate(flights[:5], 1):
airline = f.get("airline", "Unknown airline")
@@ -245,16 +209,17 @@ def _format_spoken(
dur_str = f", {duration}" if duration else ""
lines.append(
f"Option {i}: {airline}, departing {departure}, arriving {arrival}"
f"{dur_str}, {stop_str}, {price_str}."
f"Option {i}: {airline}, departing {departure}, "
f"arriving {arrival}{dur_str}, {stop_str}, {price_str}."
)
cheapest = min(
(f for f in flights if f.get("price")),
key=lambda x: re.sub(r"[^\d]", "", str(x.get("price", "99999"))) or "99999",
default=None,
)
if cheapest:
# Cheapest — strip non-digits for comparison
priced = [f for f in flights if f.get("price")]
if priced:
cheapest = min(
priced,
key=lambda x: int(re.sub(r"[^\d]", "", str(x["price"])) or "999999"),
)
lines.append(
f"The cheapest option is {cheapest.get('airline')} "
f"at {cheapest.get('price')} {cheapest.get('currency', '')}."
@@ -263,7 +228,7 @@ def _format_spoken(
return " ".join(lines)
def _format_notepad(
def _format_text_report(
flights: list[dict],
origin: str,
destination: str,
@@ -271,9 +236,6 @@ def _format_notepad(
return_date: str | None,
page_url: str,
) -> str:
"""Formats flights for Notepad — detailed and readable."""
from datetime import datetime as dt
lines = [
"JARVIS — Flight Search Results",
"─" * 50,
@@ -283,7 +245,7 @@ def _format_notepad(
if return_date:
lines.append(f"Return : {return_date}")
lines += [
f"Searched : {dt.now().strftime('%Y-%m-%d %H:%M')}",
f"Searched : {datetime.now().strftime('%Y-%m-%d %H:%M')}",
f"Source : {page_url}",
"─" * 50,
"",
@@ -297,10 +259,10 @@ def _format_notepad(
stop_str = "Non-stop" if stops == 0 else f"{stops} stop(s)"
lines += [
f"Flight {i}:",
f" Airline : {f.get('airline', 'N/A')}",
f" Airline : {f.get('airline', 'N/A')}",
f" Departure : {f.get('departure', 'N/A')}",
f" Arrival : {f.get('arrival', 'N/A')}",
f" Duration : {f.get('duration', 'N/A')}",
f" Arrival : {f.get('arrival', 'N/A')}",
f" Duration : {f.get('duration', 'N/A')}",
f" Stops : {stop_str}",
f" Price : {f.get('price', 'N/A')} {f.get('currency', '')}",
"",
@@ -308,11 +270,7 @@ def _format_notepad(
return "\n".join(lines)
def _save_to_notepad(content: str, origin: str, destination: str) -> str:
"""Saves flight results to Desktop and opens in default text editor."""
from datetime import datetime
def _save_to_desktop(content: str, origin: str, destination: str) -> str:
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"flights_{origin}_{destination}_{ts}.txt".replace(" ", "_")
desktop = Path.home() / "Desktop"
@@ -322,58 +280,39 @@ def _save_to_notepad(content: str, origin: str, destination: str) -> str:
filepath.write_text(content, encoding="utf-8")
print(f"[FlightFinder] 💾 Saved: {filepath}")
system = platform.system()
open_fn = {
"Windows": lambda p: subprocess.Popen(["notepad.exe", str(p)]),
"Darwin": lambda p: subprocess.Popen(["open", "-t", str(p)]),
"Linux": lambda p: subprocess.Popen(["xdg-open", str(p)]),
}
opener = open_fn.get(system)
if opener:
opener(filepath)
try:
if is_windows():
subprocess.Popen(["notepad.exe", str(filepath)])
elif is_mac():
subprocess.Popen(["open", "-t", str(filepath)])
else:
subprocess.Popen(["xdg-open", str(filepath)])
except Exception as e:
print(f"[FlightFinder] ⚠️ Could not open text editor: {e}")
return str(filepath)
def flight_finder(
parameters: dict,
response=None,
player=None,
session_memory=None,
speak=None,
) -> str:
"""
Flight Finder — searches Google Flights and speaks results.
Parameters:
origin (str, required) — departure city or airport (e.g. "Istanbul", "IST")
destination (str, required) — arrival city or airport (e.g. "London", "LHR")
date (str, required) — departure date (any format: "15 Mart", "March 15", "2025-03-15")
return_date (str, optional) — return date for round trips
passengers (int, optional) — number of passengers (default: 1)
cabin (str, optional) — economy | premium | business | first (default: economy)
save (bool, optional) — save results to Notepad (default: False)
show_browser (bool, optional) — keep browser open after search (default: True)
Examples:
flight_finder({"origin": "Istanbul", "destination": "London", "date": "15 Mart"})
flight_finder({"origin": "IST", "destination": "JFK", "date": "2025-04-01",
"return_date": "2025-04-15", "cabin": "business", "save": True})
"""
def flight_finder(parameters: dict, player=None, speak=None) -> str:
params = parameters or {}
origin = params.get("origin", "").strip()
destination = params.get("destination", "").strip()
date_raw = params.get("date", "").strip()
return_raw = params.get("return_date", "").strip()
passengers = int(params.get("passengers", 1))
cabin = params.get("cabin", "economy").strip()
save = params.get("save", False)
return_raw = (params.get("return_date") or "").strip()
passengers = max(1, int(params.get("passengers", 1)))
cabin = params.get("cabin", "economy").strip().lower()
save = bool(params.get("save", False))
if not origin or not destination:
return "Please provide both origin and destination, sir."
if not date_raw:
return "Please provide a departure date, sir."
# Normalise cabin value
if cabin not in _CABIN_CODE:
cabin = "economy"
date = _parse_date(date_raw)
return_date = _parse_date(return_raw) if return_raw else None
@@ -383,10 +322,13 @@ def flight_finder(
if speak:
speak(f"Searching flights from {origin} to {destination} on {date}, sir.")
print(f"[FlightFinder] ▶️ {origin} → {destination} | {date} | {cabin} | {passengers} pax")
print(
f"[FlightFinder] ▶️ {origin} → {destination} | {date}"
f"{' → ' + return_date if return_date else ''}"
f" | {cabin} | {passengers} pax"
)
try:
raw_text, page_url = _search_flights_browser(
origin, destination, date, return_date, passengers, cabin
)
@@ -395,25 +337,23 @@ def flight_finder(
return "Could not retrieve flight data, sir. The page may not have loaded."
if speak:
speak("Analysing the results now.")
speak("Analysing the results now, sir.")
flights = _parse_flights_with_gemini(raw_text, origin, destination, date)
spoken = _format_spoken(flights, origin, destination, date)
spoken = _format_spoken(flights, origin, destination, date)
if speak:
speak(spoken)
result = spoken
if save and flights:
notepad_content = _format_notepad(
flights, origin, destination, date, return_date, page_url
)
saved_path = _save_to_notepad(notepad_content, origin, destination)
result += f" Results saved to Desktop: {saved_path}"
report = _format_text_report(flights, origin, destination, date, return_date, page_url)
saved_path = _save_to_desktop(report, origin, destination)
result += f" Results saved to Desktop: {saved_path}"
return result
except Exception as e:
print(f"[FlightFinder] ❌ Error: {e}")
print(f"[FlightFinder] ❌ {e}")
return f"Flight search failed, sir: {e}"