Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -12,24 +12,23 @@ from dotenv import load_dotenv
|
|
| 12 |
from supabase import create_client
|
| 13 |
import os
|
| 14 |
|
|
|
|
|
|
|
| 15 |
SUPABASE_URL = os.getenv("SUPABASE_URL")
|
| 16 |
SUPABASE_KEY = os.getenv("SBASEKEY")
|
| 17 |
-
supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
|
| 18 |
-
|
| 19 |
-
# --- Load API Key dari .env ---
|
| 20 |
-
load_dotenv()
|
| 21 |
API_KEY = os.getenv("GEMINI_API_KEY")
|
|
|
|
|
|
|
| 22 |
genai.configure(api_key=API_KEY)
|
| 23 |
|
| 24 |
-
# --- Load
|
| 25 |
def fetch_data_from_supabase():
|
| 26 |
response = supabase.table("Maps").select("*").execute()
|
| 27 |
return pd.DataFrame(response.data)
|
| 28 |
|
| 29 |
-
# Load data dari Supabase
|
| 30 |
df = fetch_data_from_supabase()
|
| 31 |
|
| 32 |
-
# ---
|
| 33 |
def extract_keywords(user_input):
|
| 34 |
prompt = f"""
|
| 35 |
Ekstrak 3–7 kata kunci penting dari deskripsi wisata berikut:
|
|
@@ -46,7 +45,7 @@ def extract_keywords(user_input):
|
|
| 46 |
except Exception as e:
|
| 47 |
return [f"Error: {e}"]
|
| 48 |
|
| 49 |
-
# ---
|
| 50 |
def get_coordinates_from_location(location_name):
|
| 51 |
try:
|
| 52 |
geolocator = Nominatim(user_agent="geoapi")
|
|
@@ -63,15 +62,28 @@ def get_location_name_from_coordinates(lat, lon):
|
|
| 63 |
except GeocoderTimedOut:
|
| 64 |
return "Tidak ditemukan"
|
| 65 |
|
| 66 |
-
# ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
def prepare_and_recommend(df, user_description):
|
| 68 |
tfidf = TfidfVectorizer()
|
| 69 |
-
# Langsung gunakan deskripsi tanpa cleaning
|
| 70 |
tfidf_matrix = tfidf.fit_transform(df['deskripsi'].astype(str).tolist() + [user_description])
|
| 71 |
similarity = cosine_similarity(tfidf_matrix[-1], tfidf_matrix[:-1]).flatten()
|
| 72 |
df['similarity'] = similarity
|
| 73 |
return df.sort_values(by='similarity', ascending=False).head(10)
|
| 74 |
|
|
|
|
| 75 |
def sort_by_nearest_location(df, user_lat, user_lon):
|
| 76 |
df['distance_km'] = df.apply(
|
| 77 |
lambda row: geodesic((user_lat, user_lon), (row['latitude'], row['longitude'])).km,
|
|
@@ -80,40 +92,57 @@ def sort_by_nearest_location(df, user_lat, user_lon):
|
|
| 80 |
df['distance_km'] = df['distance_km'].round(2)
|
| 81 |
return df.sort_values(by='distance_km')
|
| 82 |
|
| 83 |
-
# --- Fungsi Utama
|
| 84 |
def wisata_rekomendasi(deskripsi, lokasi):
|
| 85 |
if df.empty:
|
| 86 |
-
return "Data tidak tersedia.", pd.DataFrame([["Data tidak tersedia"
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
user_description_joined = " ".join(keywords)
|
| 93 |
lat, lon = get_coordinates_from_location(lokasi)
|
| 94 |
if lat is None or lon is None:
|
| 95 |
-
return "Lokasi tidak ditemukan.", pd.DataFrame([["Lokasi tidak ditemukan"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
top_place = prepare_and_recommend(df.copy(), user_description_joined)
|
|
|
|
| 98 |
sorted_place = sort_by_nearest_location(top_place, lat, lon)
|
| 99 |
-
|
| 100 |
sorted_place = sorted_place[sorted_place["gambar"].apply(lambda x: isinstance(x, str) and x.startswith("https"))]
|
| 101 |
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
-
# --- UI
|
| 105 |
demo = gr.Interface(
|
| 106 |
fn=wisata_rekomendasi,
|
| 107 |
inputs=[
|
| 108 |
gr.Textbox(label="Deskripsi Wisata yang Anda Inginkan"),
|
| 109 |
-
gr.Textbox(label="Lokasi Anda (Contoh: Cilacap,
|
| 110 |
],
|
| 111 |
outputs=[
|
| 112 |
gr.Textbox(label="Kata Kunci yang Diekstrak"),
|
| 113 |
-
gr.Dataframe(
|
|
|
|
|
|
|
|
|
|
| 114 |
],
|
| 115 |
title="Sistem Rekomendasi Wisata",
|
| 116 |
-
description="Masukkan deskripsi dan lokasi, lalu dapatkan rekomendasi tempat wisata terdekat"
|
| 117 |
)
|
| 118 |
|
| 119 |
demo.launch()
|
|
|
|
| 12 |
from supabase import create_client
|
| 13 |
import os
|
| 14 |
|
| 15 |
+
# --- Supabase & Gemini ---
|
| 16 |
+
load_dotenv()
|
| 17 |
SUPABASE_URL = os.getenv("SUPABASE_URL")
|
| 18 |
SUPABASE_KEY = os.getenv("SBASEKEY")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
API_KEY = os.getenv("GEMINI_API_KEY")
|
| 20 |
+
|
| 21 |
+
supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
|
| 22 |
genai.configure(api_key=API_KEY)
|
| 23 |
|
| 24 |
+
# --- Load data dari Supabase ---
|
| 25 |
def fetch_data_from_supabase():
|
| 26 |
response = supabase.table("Maps").select("*").execute()
|
| 27 |
return pd.DataFrame(response.data)
|
| 28 |
|
|
|
|
| 29 |
df = fetch_data_from_supabase()
|
| 30 |
|
| 31 |
+
# --- Ekstraksi Kata Kunci ---
|
| 32 |
def extract_keywords(user_input):
|
| 33 |
prompt = f"""
|
| 34 |
Ekstrak 3–7 kata kunci penting dari deskripsi wisata berikut:
|
|
|
|
| 45 |
except Exception as e:
|
| 46 |
return [f"Error: {e}"]
|
| 47 |
|
| 48 |
+
# --- Lokasi ---
|
| 49 |
def get_coordinates_from_location(location_name):
|
| 50 |
try:
|
| 51 |
geolocator = Nominatim(user_agent="geoapi")
|
|
|
|
| 62 |
except GeocoderTimedOut:
|
| 63 |
return "Tidak ditemukan"
|
| 64 |
|
| 65 |
+
# --- Enhancement untuk deskripsi singkat ---
|
| 66 |
+
def enhance_description_with_gemini(short_desc):
|
| 67 |
+
prompt = f"""
|
| 68 |
+
Deskripsi berikut terlalu singkat: "{short_desc}"
|
| 69 |
+
Tolong kembangkan menjadi paragraf singkat (2–3 kalimat) yang menggambarkan keinginan wisata pengguna secara lebih lengkap.
|
| 70 |
+
Contohnya: sebutkan suasana, aktivitas, atau lokasi ideal.
|
| 71 |
+
"""
|
| 72 |
+
try:
|
| 73 |
+
response = genai.GenerativeModel("gemini-1.5-flash").generate_content(prompt)
|
| 74 |
+
return response.text.strip()
|
| 75 |
+
except Exception as e:
|
| 76 |
+
return short_desc
|
| 77 |
+
|
| 78 |
+
# --- TF-IDF dan Cosine Similarity ---
|
| 79 |
def prepare_and_recommend(df, user_description):
|
| 80 |
tfidf = TfidfVectorizer()
|
|
|
|
| 81 |
tfidf_matrix = tfidf.fit_transform(df['deskripsi'].astype(str).tolist() + [user_description])
|
| 82 |
similarity = cosine_similarity(tfidf_matrix[-1], tfidf_matrix[:-1]).flatten()
|
| 83 |
df['similarity'] = similarity
|
| 84 |
return df.sort_values(by='similarity', ascending=False).head(10)
|
| 85 |
|
| 86 |
+
# --- Jarak Lokasi ---
|
| 87 |
def sort_by_nearest_location(df, user_lat, user_lon):
|
| 88 |
df['distance_km'] = df.apply(
|
| 89 |
lambda row: geodesic((user_lat, user_lon), (row['latitude'], row['longitude'])).km,
|
|
|
|
| 92 |
df['distance_km'] = df['distance_km'].round(2)
|
| 93 |
return df.sort_values(by='distance_km')
|
| 94 |
|
| 95 |
+
# --- Fungsi Utama ---
|
| 96 |
def wisata_rekomendasi(deskripsi, lokasi):
|
| 97 |
if df.empty:
|
| 98 |
+
return "Data tidak tersedia.", pd.DataFrame([["Data tidak tersedia"]], columns=["nama"])
|
| 99 |
|
| 100 |
+
if len(deskripsi.strip().split()) < 3 or len(deskripsi.strip()) < 20:
|
| 101 |
+
deskripsi = enhance_description_with_gemini(deskripsi)
|
| 102 |
+
|
| 103 |
+
# Lokasi → Koordinat
|
|
|
|
| 104 |
lat, lon = get_coordinates_from_location(lokasi)
|
| 105 |
if lat is None or lon is None:
|
| 106 |
+
return "Lokasi tidak ditemukan.", pd.DataFrame([["Lokasi tidak ditemukan"]], columns=["nama"])
|
| 107 |
+
|
| 108 |
+
# Tambahkan lokasi ke deskripsi
|
| 109 |
+
deskripsi_lengkap = f"{deskripsi} di sekitar {lokasi}"
|
| 110 |
+
|
| 111 |
+
keywords = extract_keywords(deskripsi_lengkap)
|
| 112 |
+
if "Error:" in str(keywords):
|
| 113 |
+
return f"Kata kunci gagal diambil: {keywords[0]}", pd.DataFrame([[keywords[0]]], columns=["nama"])
|
| 114 |
+
|
| 115 |
+
user_description_joined = " ".join(keywords)
|
| 116 |
|
| 117 |
top_place = prepare_and_recommend(df.copy(), user_description_joined)
|
| 118 |
+
top_place = top_place[top_place['total_ulasan'] > 10]
|
| 119 |
sorted_place = sort_by_nearest_location(top_place, lat, lon)
|
| 120 |
+
|
| 121 |
sorted_place = sorted_place[sorted_place["gambar"].apply(lambda x: isinstance(x, str) and x.startswith("https"))]
|
| 122 |
|
| 123 |
+
# Urutkan berdasarkan similarity tertinggi dan tampilkan kolom similarity
|
| 124 |
+
sorted_place = sorted_place.sort_values(by='similarity', ascending=False)
|
| 125 |
+
|
| 126 |
+
return f"Kata kunci: {', '.join(keywords)}", sorted_place[[
|
| 127 |
+
"id", "nama", "alamat", "distance_km", "deskripsi", "harga", "rating", "total_ulasan", "gambar", "similarity"
|
| 128 |
+
]]
|
| 129 |
|
| 130 |
+
# --- Gradio UI ---
|
| 131 |
demo = gr.Interface(
|
| 132 |
fn=wisata_rekomendasi,
|
| 133 |
inputs=[
|
| 134 |
gr.Textbox(label="Deskripsi Wisata yang Anda Inginkan"),
|
| 135 |
+
gr.Textbox(label="Lokasi Anda (Contoh: Cilacap, Jawa Tengah, Indonesia)"),
|
| 136 |
],
|
| 137 |
outputs=[
|
| 138 |
gr.Textbox(label="Kata Kunci yang Diekstrak"),
|
| 139 |
+
gr.Dataframe(
|
| 140 |
+
headers=["id", "nama", "alamat", "distance_km", "deskripsi", "harga", "rating", "total_ulasan", "gambar", "similarity"],
|
| 141 |
+
label="Rekomendasi Tempat Wisata"
|
| 142 |
+
)
|
| 143 |
],
|
| 144 |
title="Sistem Rekomendasi Wisata",
|
| 145 |
+
description="Masukkan deskripsi dan lokasi, lalu dapatkan rekomendasi tempat wisata terdekat beserta skor kecocokannya."
|
| 146 |
)
|
| 147 |
|
| 148 |
demo.launch()
|