Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -11,8 +11,8 @@ APIFY_TOKEN = "apify_api_VEELKPpmSsIfcblSisaKkKk2YiocQb2bwaS1"
|
|
| 11 |
GEMINI_KEY = "AIzaSyBoD_j_LG5rBA0wthWn9xCFl555p0hC5Pc"
|
| 12 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 13 |
|
| 14 |
-
#
|
| 15 |
-
gemini_client = genai.Client(api_key=GEMINI_KEY
|
| 16 |
|
| 17 |
apify_client = ApifyClient(APIFY_TOKEN)
|
| 18 |
app = FastAPI()
|
|
@@ -25,8 +25,8 @@ app.add_middleware(
|
|
| 25 |
allow_headers=["*"],
|
| 26 |
)
|
| 27 |
|
| 28 |
-
#
|
| 29 |
-
HF_API_URL = "https://
|
| 30 |
HF_HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"}
|
| 31 |
|
| 32 |
# --- 2. FUNGSI ANALISIS SENTIMEN (MDEBERTA) ---
|
|
@@ -34,13 +34,15 @@ def analyze_with_mdeberta(ulasan_list):
|
|
| 34 |
aspek_list = ["Kualitas Makanan", "Pelayanan", "Kebersihan", "Harga", "Variasi Menu", "Waktu Tunggu"]
|
| 35 |
raw_scores = {k: {"pos": 0, "neu": 0, "neg": 0} for k in aspek_list}
|
| 36 |
|
| 37 |
-
|
|
|
|
| 38 |
try:
|
| 39 |
payload = {
|
| 40 |
"inputs": teks,
|
| 41 |
"parameters": {"candidate_labels": ["positif", "netral", "negatif"]}
|
| 42 |
}
|
| 43 |
-
|
|
|
|
| 44 |
|
| 45 |
if response.status_code == 200:
|
| 46 |
res = response.json()
|
|
@@ -51,19 +53,19 @@ def analyze_with_mdeberta(ulasan_list):
|
|
| 51 |
elif sentiment == "negatif": raw_scores[asp]["neg"] += 1
|
| 52 |
else: raw_scores[asp]["neu"] += 1
|
| 53 |
else:
|
| 54 |
-
print(f"HF
|
| 55 |
except Exception as e:
|
| 56 |
print(f"mDeBERTa Error: {e}")
|
| 57 |
|
| 58 |
return raw_scores
|
| 59 |
|
| 60 |
-
# --- 3. FUNGSI REKOMENDASI (GEMINI
|
| 61 |
def get_advanced_insights(ulasan_list):
|
| 62 |
try:
|
| 63 |
-
gabungan_ulasan = " | ".join(ulasan_list[:
|
| 64 |
prompt = f"""
|
| 65 |
Analisis ulasan restoran ini: {gabungan_ulasan}.
|
| 66 |
-
Berikan respon JSON murni:
|
| 67 |
{{
|
| 68 |
"kata_kunci_positif": ["kata1", "kata2"],
|
| 69 |
"kata_kunci_negatif": ["kata1", "kata2"],
|
|
@@ -73,13 +75,12 @@ def get_advanced_insights(ulasan_list):
|
|
| 73 |
}}
|
| 74 |
"""
|
| 75 |
|
| 76 |
-
# Eksekusi
|
| 77 |
response = gemini_client.models.generate_content(
|
| 78 |
model='gemini-1.5-flash',
|
| 79 |
contents=prompt,
|
| 80 |
)
|
| 81 |
|
| 82 |
-
# Membersihkan tag markdown JSON
|
| 83 |
t = response.text.replace('```json', '').replace('```', '').strip()
|
| 84 |
return json.loads(t)
|
| 85 |
except Exception as e:
|
|
@@ -87,10 +88,10 @@ def get_advanced_insights(ulasan_list):
|
|
| 87 |
return {
|
| 88 |
"kata_kunci_positif": ["Rasa Enak"],
|
| 89 |
"kata_kunci_negatif": ["Antrean"],
|
| 90 |
-
"rekomendasi": [{"judul": "Layanan", "deskripsi": "
|
| 91 |
}
|
| 92 |
|
| 93 |
-
# --- 4. ENDPOINT ---
|
| 94 |
@app.post("/analyze")
|
| 95 |
async def analyze_realtime(request: Request):
|
| 96 |
try:
|
|
@@ -98,7 +99,7 @@ async def analyze_realtime(request: Request):
|
|
| 98 |
target_url = body.get("url")
|
| 99 |
|
| 100 |
run = apify_client.actor("compass/google-maps-reviews-scraper").call(
|
| 101 |
-
run_input={"startUrls": [{"url": target_url}], "maxReviews":
|
| 102 |
)
|
| 103 |
|
| 104 |
ulasan_lengkap = []
|
|
@@ -115,11 +116,10 @@ async def analyze_realtime(request: Request):
|
|
| 115 |
if not ulasan_teks_saja:
|
| 116 |
return {"status": "error", "message": "Ulasan tidak ditemukan."}
|
| 117 |
|
| 118 |
-
#
|
| 119 |
raw_scores = analyze_with_mdeberta(ulasan_teks_saja)
|
| 120 |
gemini_data = get_advanced_insights(ulasan_teks_saja)
|
| 121 |
|
| 122 |
-
# Kalkulasi
|
| 123 |
sentiment_results = []
|
| 124 |
tp = tn = tneu = 0
|
| 125 |
for name, counts in raw_scores.items():
|
|
|
|
| 11 |
GEMINI_KEY = "AIzaSyBoD_j_LG5rBA0wthWn9xCFl555p0hC5Pc"
|
| 12 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 13 |
|
| 14 |
+
# PERBAIKAN GEMINI: Hapus batasan 'v1' agar SDK otomatis mencari versi API yang tepat!
|
| 15 |
+
gemini_client = genai.Client(api_key=GEMINI_KEY)
|
| 16 |
|
| 17 |
apify_client = ApifyClient(APIFY_TOKEN)
|
| 18 |
app = FastAPI()
|
|
|
|
| 25 |
allow_headers=["*"],
|
| 26 |
)
|
| 27 |
|
| 28 |
+
# Kembali menggunakan URL utama HF (lebih stabil dari router jika token benar)
|
| 29 |
+
HF_API_URL = "https://api-inference.huggingface.co/models/MoritzLaurer/mDeBERTa-v3-base-mnli-xnli"
|
| 30 |
HF_HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"}
|
| 31 |
|
| 32 |
# --- 2. FUNGSI ANALISIS SENTIMEN (MDEBERTA) ---
|
|
|
|
| 34 |
aspek_list = ["Kualitas Makanan", "Pelayanan", "Kebersihan", "Harga", "Variasi Menu", "Waktu Tunggu"]
|
| 35 |
raw_scores = {k: {"pos": 0, "neu": 0, "neg": 0} for k in aspek_list}
|
| 36 |
|
| 37 |
+
# PERBAIKAN KECEPATAN: Hanya ambil 5 ulasan teratas agar tidak lama loading!
|
| 38 |
+
for teks in ulasan_list[:5]:
|
| 39 |
try:
|
| 40 |
payload = {
|
| 41 |
"inputs": teks,
|
| 42 |
"parameters": {"candidate_labels": ["positif", "netral", "negatif"]}
|
| 43 |
}
|
| 44 |
+
# PERBAIKAN TIMEOUT: Kurangi jadi 6 detik. Jika HF lemot, langsung skip agar Vercel tidak muter terus!
|
| 45 |
+
response = requests.post(HF_API_URL, headers=HF_HEADERS, json=payload, timeout=6)
|
| 46 |
|
| 47 |
if response.status_code == 200:
|
| 48 |
res = response.json()
|
|
|
|
| 53 |
elif sentiment == "negatif": raw_scores[asp]["neg"] += 1
|
| 54 |
else: raw_scores[asp]["neu"] += 1
|
| 55 |
else:
|
| 56 |
+
print(f"HF Error {response.status_code}: {response.text[:50]}")
|
| 57 |
except Exception as e:
|
| 58 |
print(f"mDeBERTa Error: {e}")
|
| 59 |
|
| 60 |
return raw_scores
|
| 61 |
|
| 62 |
+
# --- 3. FUNGSI REKOMENDASI (GEMINI) ---
|
| 63 |
def get_advanced_insights(ulasan_list):
|
| 64 |
try:
|
| 65 |
+
gabungan_ulasan = " | ".join(ulasan_list[:6])
|
| 66 |
prompt = f"""
|
| 67 |
Analisis ulasan restoran ini: {gabungan_ulasan}.
|
| 68 |
+
Berikan respon JSON murni TANPA markdown/codeblock:
|
| 69 |
{{
|
| 70 |
"kata_kunci_positif": ["kata1", "kata2"],
|
| 71 |
"kata_kunci_negatif": ["kata1", "kata2"],
|
|
|
|
| 75 |
}}
|
| 76 |
"""
|
| 77 |
|
| 78 |
+
# Eksekusi dengan Gemini 1.5 Flash
|
| 79 |
response = gemini_client.models.generate_content(
|
| 80 |
model='gemini-1.5-flash',
|
| 81 |
contents=prompt,
|
| 82 |
)
|
| 83 |
|
|
|
|
| 84 |
t = response.text.replace('```json', '').replace('```', '').strip()
|
| 85 |
return json.loads(t)
|
| 86 |
except Exception as e:
|
|
|
|
| 88 |
return {
|
| 89 |
"kata_kunci_positif": ["Rasa Enak"],
|
| 90 |
"kata_kunci_negatif": ["Antrean"],
|
| 91 |
+
"rekomendasi": [{"judul": "Sistem Layanan", "deskripsi": "Percepat respons staf.", "prioritas": "Medium"}]
|
| 92 |
}
|
| 93 |
|
| 94 |
+
# --- 4. ENDPOINT UTAMA ---
|
| 95 |
@app.post("/analyze")
|
| 96 |
async def analyze_realtime(request: Request):
|
| 97 |
try:
|
|
|
|
| 99 |
target_url = body.get("url")
|
| 100 |
|
| 101 |
run = apify_client.actor("compass/google-maps-reviews-scraper").call(
|
| 102 |
+
run_input={"startUrls": [{"url": target_url}], "maxReviews": 10, "language": "id"}
|
| 103 |
)
|
| 104 |
|
| 105 |
ulasan_lengkap = []
|
|
|
|
| 116 |
if not ulasan_teks_saja:
|
| 117 |
return {"status": "error", "message": "Ulasan tidak ditemukan."}
|
| 118 |
|
| 119 |
+
# AI Processing
|
| 120 |
raw_scores = analyze_with_mdeberta(ulasan_teks_saja)
|
| 121 |
gemini_data = get_advanced_insights(ulasan_teks_saja)
|
| 122 |
|
|
|
|
| 123 |
sentiment_results = []
|
| 124 |
tp = tn = tneu = 0
|
| 125 |
for name, counts in raw_scores.items():
|