Dev4zz commited on
Commit
19e9e7f
·
verified ·
1 Parent(s): b85033e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -20
app.py CHANGED
@@ -7,8 +7,8 @@ from apify_client import ApifyClient
7
 
8
  # --- 1. KONFIGURASI API ---
9
  APIFY_TOKEN = os.getenv("APIFY_TOKEN")
10
- GEMINI_KEY = os.getenv("GEMINI_KEY")
11
  HF_TOKEN = os.getenv("HF_TOKEN")
 
12
 
13
  # Validasi token saat startup
14
  if not HF_TOKEN:
@@ -18,8 +18,7 @@ if not GEMINI_KEY:
18
  if not APIFY_TOKEN:
19
  print("⚠️ WARNING: APIFY_TOKEN is not set! Scraping will fail.")
20
 
21
- # Gemini REST API — bypass SDK entirely (using Gemini 2.5 Flash, stable free tier)
22
- GEMINI_URL = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={GEMINI_KEY}"
23
 
24
  apify_client = ApifyClient(APIFY_TOKEN)
25
  app = FastAPI()
@@ -107,14 +106,14 @@ def analyze_sentiment(ulasan_list):
107
 
108
  return raw_scores
109
 
110
- # --- 3. FUNGSI REKOMENDASI (GEMINI REST API) ---
111
  def get_advanced_insights(ulasan_list):
112
  try:
113
- # Kirim ulasan lebih banyak ke Gemini (8 ulasan) untuk analisis lebih tajam
114
  gabungan_ulasan = " | ".join(ulasan_list[:8])
 
115
  prompt = f"""
116
- Analisis ulasan restoran ini: {gabungan_ulasan}.
117
- Berikan respon JSON murni:
118
  {{
119
  "kata_kunci_positif": ["kata1", "kata2"],
120
  "kata_kunci_negatif": ["kata1", "kata2"],
@@ -123,28 +122,37 @@ def get_advanced_insights(ulasan_list):
123
  ]
124
  }}
125
  """
 
 
 
 
 
 
126
  payload = {
127
- "contents": [{"parts": [{"text": prompt}]}],
128
- "generationConfig": {"temperature": 0.7}
 
 
129
  }
130
- response = requests.post(GEMINI_URL, json=payload, timeout=30)
 
 
131
  if response.status_code == 200:
132
  data = response.json()
133
- t = data["candidates"][0]["content"]["parts"][0]["text"]
134
- # Menghapus tag markdown jika ada
135
- t = t.replace('```json', '').replace('```', '').strip()
136
  return json.loads(t)
137
  else:
138
- print(f"Gemini REST Error: {response.status_code} - {response.text[:200]}")
139
- raise Exception(f"Gemini API returned {response.status_code}")
140
  except Exception as e:
141
- print(f"Gemini Logic Error: {e}")
142
  return {
143
- "kata_kunci_positif": ["Rasa Enak", "Porsi Kenyang"],
144
- "kata_kunci_negatif": ["Antrean"],
145
- "rekomendasi": [{"judul": "Layanan", "deskripsi": "Tingkatkan kecepatan staf.", "prioritas": "Medium"}]
146
  }
147
-
148
  # --- 4. ENDPOINT ---
149
  @app.post("/analyze")
150
  async def analyze_realtime(request: Request):
 
7
 
8
  # --- 1. KONFIGURASI API ---
9
  APIFY_TOKEN = os.getenv("APIFY_TOKEN")
 
10
  HF_TOKEN = os.getenv("HF_TOKEN")
11
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
12
 
13
  # Validasi token saat startup
14
  if not HF_TOKEN:
 
18
  if not APIFY_TOKEN:
19
  print("⚠️ WARNING: APIFY_TOKEN is not set! Scraping will fail.")
20
 
21
+ GROQ_URL = "https://api.groq.com/openai/v1/chat/completions"
 
22
 
23
  apify_client = ApifyClient(APIFY_TOKEN)
24
  app = FastAPI()
 
106
 
107
  return raw_scores
108
 
109
+ # --- 3. FUNGSI REKOMENDASI (GROQ LLAMA 3) ---
110
  def get_advanced_insights(ulasan_list):
111
  try:
 
112
  gabungan_ulasan = " | ".join(ulasan_list[:8])
113
+ # Prompt disesuaikan sedikit agar Llama 3 lebih menurut
114
  prompt = f"""
115
+ Kamu adalah analis bisnis restoran. Analisis ulasan berikut: {gabungan_ulasan}.
116
+ Kamu WAJIB mengembalikan respon HANYA dalam format JSON murni ini:
117
  {{
118
  "kata_kunci_positif": ["kata1", "kata2"],
119
  "kata_kunci_negatif": ["kata1", "kata2"],
 
122
  ]
123
  }}
124
  """
125
+
126
+ headers = {
127
+ "Authorization": f"Bearer {GROQ_API_KEY}",
128
+ "Content-Type": "application/json"
129
+ }
130
+
131
  payload = {
132
+ "model": "llama3-8b-8192", # Model Llama 3 yang sangat cepat
133
+ "messages": [{"role": "user", "content": prompt}],
134
+ "response_format": {"type": "json_object"}, # Memaksa output berupa JSON
135
+ "temperature": 0.5
136
  }
137
+
138
+ response = requests.post(GROQ_URL, headers=headers, json=payload, timeout=20)
139
+
140
  if response.status_code == 200:
141
  data = response.json()
142
+ # Parsing output khas arsitektur OpenAI/Groq
143
+ t = data["choices"][0]["message"]["content"]
 
144
  return json.loads(t)
145
  else:
146
+ raise Exception(f"Groq API Error {response.status_code}")
147
+
148
  except Exception as e:
149
+ print(f"LLM Error: {e}")
150
  return {
151
+ "kata_kunci_positif": ["Coba Lagi"],
152
+ "kata_kunci_negatif": ["Server Sibuk"],
153
+ "rekomendasi": [{"judul": "Gunakan Fallback", "deskripsi": "Server LLM sedang sibuk.", "prioritas": "Low"}]
154
  }
155
+
156
  # --- 4. ENDPOINT ---
157
  @app.post("/analyze")
158
  async def analyze_realtime(request: Request):