File size: 2,403 Bytes
c0ce4a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import gradio as gr
import requests
from mapbox import Geocoder

# Mapbox token
MAPBOX_TOKEN = 'pk.eyJ1IjoiYWRpbDk4IiwiYSI6ImNtYjdzODZ1NzBkcXcybHM2OHcwZTZ5NzAifQ.SlPs3gdrGqD7iU3Fk35AFw'

# Initialize Mapbox geocoder
geocoder = Geocoder(access_token=MAPBOX_TOKEN)

# Get coordinates from location name
def get_coordinates(location_name):
    response = geocoder.forward(location_name, limit=1)
    if response.status_code == 200:
        data = response.json()
        if data['features']:
            coords = data['features'][0]['center']  # [lon, lat]
            return coords[1], coords[0]
    return None

# Get distance and duration
def get_route_info(coord1, coord2):
    url = f"http://router.project-osrm.org/route/v1/driving/{coord1[1]},{coord1[0]};{coord2[1]},{coord2[0]}?overview=false"
    response = requests.get(url)
    data = response.json()
    if 'routes' in data and data['routes']:
        distance_km = data['routes'][0]['distance'] / 1000
        duration_min = data['routes'][0]['duration'] / 60
        return distance_km, duration_min
    return None, None

# Fuel estimation
def estimate_fuel(distance_km, avg_kmpl):
    return round(distance_km / avg_kmpl, 2)

# Main function to integrate
def estimate_all(loc1, loc2, user_kmpl):
    coord1 = get_coordinates(loc1)
    coord2 = get_coordinates(loc2)

    if not coord1 or not coord2:
        return "Failed to get location coordinates. Please check input names.", None, None, None

    distance, duration = get_route_info(coord1, coord2)
    if distance is None:
        return "Failed to retrieve route data.", None, None, None

    fuel = estimate_fuel(distance, user_kmpl)
    return (
        "Here are the results:",
        f"πŸ“ Distance: {distance:.2f} km",
        f"⏱️ Estimated Time: {duration:.2f} minutes",
        f"β›½ Fuel Used: {fuel:.2f} litres (at {user_kmpl} km/l)"
    )

# Gradio Interface
demo = gr.Interface(
    fn=estimate_all,
    inputs=[
        gr.Textbox(label="Enter Location 1"),
        gr.Textbox(label="Enter Location 2"),
        gr.Slider(1.0, 100.0, value=15.0, label="Vehicle Mileage (km/l)")
    ],
    outputs=[
        gr.Textbox(label="Status"),
        gr.Textbox(label="Distance"),
        gr.Textbox(label="Time"),
        gr.Textbox(label="Fuel Used")
    ],
    title="Distance, Time & Fuel Estimator πŸš—",
    description="App Developed by Koshur AI"
)

demo.launch()