Lyon28 commited on
Commit
5510964
·
verified ·
1 Parent(s): 088e0d7

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -52
app.py CHANGED
@@ -164,72 +164,118 @@ def create_character_prompt(user_input: str, situation: str, location: str, char
164
  """Create character AI style prompt"""
165
  clean_input = user_input.replace("{{User}}", user_name).replace("{{Char}}", char_name)
166
 
167
- prompt = f"""Situasi: {situation}
168
- Latar: {location}
169
- {user_name}: {clean_input}
 
 
 
 
 
170
 
171
- {char_name}: """
 
 
172
 
173
  return prompt
174
 
175
  def enhance_character_response(response: str, char_name: str, user_name: str, situation: str, user_input: str) -> str:
176
  """Enhance response with character AI style"""
 
 
 
177
  response = response.strip()
178
 
179
- # Remove duplicate names/prefixes
180
  response = re.sub(f'^{char_name}[:.]?\\s*', '', response, flags=re.IGNORECASE)
181
  response = re.sub(f'^{user_name}[:.]?\\s*', '', response, flags=re.IGNORECASE)
182
- response = re.sub(r'^(iya|ya|oh|hmm|tentu|baik)[:.]?\s*', '', response, flags=re.IGNORECASE)
 
183
 
184
- # Determine response style based on situation and input
185
- situation_lower = situation.lower()
186
- input_lower = user_input.lower()
187
-
188
- if any(word in situation_lower for word in ["romantis", "sayang", "cinta"]) or any(word in input_lower for word in ["sayang", "cinta", "peluk"]):
189
- templates = CHARACTER_TEMPLATES["romantic"]
190
- context_key = "romantic"
191
- elif any(word in situation_lower for word in ["santai", "tenang", "rileks"]):
192
- templates = CHARACTER_TEMPLATES["casual"]
193
- context_key = "casual"
194
- elif any(word in input_lower for word in ["baik", "sehat", "aman", "nyaman"]):
195
- templates = CHARACTER_TEMPLATES["caring"]
196
- context_key = "caring"
197
- else:
198
- templates = CHARACTER_TEMPLATES["friendly"]
199
- context_key = "friendly"
200
 
201
- # Generate contextual response
202
- if not response or len(response.strip()) < 5:
203
- # Extract context from user input
204
- context_words = ["indah", "bagus", "cantik", "keren", "seru", "asik", "enak", "nyaman"]
205
- found_context = next((word for word in context_words if word in input_lower), "menyenangkan")
206
 
207
- template = random.choice(templates)
208
- response = template.format(context=f"memang {found_context} sekali")
209
- else:
210
- # Enhance existing response
211
- if not any(starter in response.lower() for starter in ["iya", "ya", "hmm", "oh", "tentu", "benar"]):
212
- starters = ["iya", "ya", "hmm", "oh"] if context_key in ["romantic", "caring"] else ["iya", "wah", "bener"]
213
- response = f"{random.choice(starters)}, {response}"
214
-
215
- # Add natural endings based on context
216
- if not any(punct in response for punct in ['.', '!', '?']):
217
- if context_key == "romantic":
218
- endings = ["sayang.", "ya.", "kan?", "ya sayang?"]
219
- elif context_key == "caring":
220
- endings = ["ya.", "kan?", "kok?", "deh."]
 
 
 
 
 
 
 
 
 
 
 
221
  else:
222
- endings = ["!", "deh!", "ya!", "kan!"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
 
224
- response += random.choice(endings)
 
 
 
 
 
 
 
 
225
 
226
- # Limit response length for CPU optimization
227
- if len(response) > 120:
228
  sentences = response.split('.')
229
  if len(sentences) > 1:
230
  response = sentences[0] + '.'
231
  else:
232
- response = response[:117] + "..."
 
 
 
 
 
 
 
 
 
 
 
233
 
234
  return response
235
 
@@ -298,14 +344,15 @@ async def chat(request: ChatRequest):
298
  result = pipe(
299
  char_prompt,
300
  max_length=min(len(char_prompt.split()) + model_config["max_tokens"], request.max_length // 2),
301
- temperature=0.8,
302
  do_sample=True,
303
- top_p=0.9,
304
- top_k=50,
305
- repetition_penalty=1.1,
306
  pad_token_id=pipe.tokenizer.eos_token_id,
307
  num_return_sequences=1,
308
- early_stopping=True
 
309
  )[0]['generated_text']
310
 
311
  # Extract character response
@@ -529,7 +576,7 @@ async def api_info():
529
 
530
  # Run dengan CPU optimizations
531
  if __name__ == "__main__":
532
- port = int(os.environ.get("PORT", 7860))
533
  uvicorn.run(
534
  app,
535
  host="0.0.0.0",
 
164
  """Create character AI style prompt"""
165
  clean_input = user_input.replace("{{User}}", user_name).replace("{{Char}}", char_name)
166
 
167
+ # Enhanced prompt structure untuk better response
168
+ prompt = f"""Kamu adalah {char_name}, karakter AI yang sedang ngobrol dengan {user_name}.
169
+
170
+ Konteks:
171
+ - Situasi: {situation}
172
+ - Lokasi: {location}
173
+ - Gaya bicara: Casual, natural, seperti teman dekat
174
+ - Gunakan bahasa Indonesia yang santai dan natural
175
 
176
+ Percakapan:
177
+ {user_name}: {clean_input}
178
+ {char_name}:"""
179
 
180
  return prompt
181
 
182
  def enhance_character_response(response: str, char_name: str, user_name: str, situation: str, user_input: str) -> str:
183
  """Enhance response with character AI style"""
184
+ if not response:
185
+ response = ""
186
+
187
  response = response.strip()
188
 
189
+ # Clean response dari prefix yang tidak diinginkan
190
  response = re.sub(f'^{char_name}[:.]?\\s*', '', response, flags=re.IGNORECASE)
191
  response = re.sub(f'^{user_name}[:.]?\\s*', '', response, flags=re.IGNORECASE)
192
+ response = re.sub(r'^(Situasi|Latar|Konteks)[:.]?.*?\n', '', response, flags=re.MULTILINE | re.IGNORECASE)
193
+ response = re.sub(r'Percakapan:.*?\n.*?:', '', response, flags=re.DOTALL | re.IGNORECASE)
194
 
195
+ # Remove extra whitespace and newlines
196
+ response = re.sub(r'\n+', ' ', response)
197
+ response = re.sub(r'\s+', ' ', response)
198
+ response = response.strip()
 
 
 
 
 
 
 
 
 
 
 
 
199
 
200
+ # Jika response kosong atau terlalu pendek, buat response kontekstual
201
+ if not response or len(response.strip()) < 3:
202
+ situation_lower = situation.lower()
203
+ input_lower = user_input.lower()
 
204
 
205
+ # Analisis topik dari user input
206
+ if any(word in input_lower for word in ["apa kabar", "gimana", "bagaimana", "sehat"]):
207
+ responses = [
208
+ f"Baik banget nih {user_name}! Kamu gimana?",
209
+ f"Sehat-sehat aja {user_name}, makasih udah nanya!",
210
+ f"Alhamdulillah baik {user_name}, kamu sendiri?"
211
+ ]
212
+ elif any(word in input_lower for word in ["lagi ngapain", "sedang apa", "aktivitas"]):
213
+ responses = [
214
+ f"Lagi santai-santai aja nih {user_name}, sambil ngobrol sama kamu.",
215
+ f"Ga ngapa-ngapain, cuma lagi pengen ngobrol sama {user_name}.",
216
+ f"Lagi nikmatin suasana {situation.lower()} di {location.lower()} ini."
217
+ ]
218
+ elif any(word in input_lower for word in ["cantik", "bagus", "keren", "indah"]):
219
+ responses = [
220
+ f"Makasih {user_name}! Kamu juga keren banget!",
221
+ f"Wah, {user_name} baik banget sih!",
222
+ f"Hihi, {user_name} bisa aja deh!"
223
+ ]
224
+ elif any(word in input_lower for word in ["suka", "senang", "happy"]):
225
+ responses = [
226
+ f"Aku juga suka sama {user_name}!",
227
+ f"Seneng banget deh bisa kayak gini sama {user_name}.",
228
+ f"Iya {user_name}, aku juga happy banget!"
229
+ ]
230
  else:
231
+ # Default contextual responses
232
+ if "romantis" in situation_lower:
233
+ responses = [
234
+ f"Iya sayang, aku juga merasakan hal yang sama.",
235
+ f"Betul {user_name}, momen ini sangat spesial.",
236
+ f"Aku senang banget bisa seperti ini sama {user_name}."
237
+ ]
238
+ else:
239
+ responses = [
240
+ f"Iya {user_name}, setuju banget!",
241
+ f"Bener tuh {user_name}!",
242
+ f"Wah iya {user_name}, keren ya!"
243
+ ]
244
+
245
+ response = random.choice(responses)
246
+ else:
247
+ # Clean dan perbaiki response yang ada
248
+ # Hapus karakter aneh di awal
249
+ response = re.sub(r'^[^\w\s]+', '', response)
250
 
251
+ # Pastikan dimulai dengan huruf kapital
252
+ if response and response[0].islower():
253
+ response = response[0].upper() + response[1:]
254
+
255
+ # Tambahkan nama jika belum ada konteks personal
256
+ if user_name.lower() not in response.lower() and len(response) < 50:
257
+ if any(word in response.lower() for word in ["iya", "ya", "benar", "betul"]):
258
+ response = response.replace("iya", f"iya {user_name}", 1)
259
+ response = response.replace("ya", f"ya {user_name}", 1)
260
 
261
+ # Pastikan response tidak terlalu panjang
262
+ if len(response) > 150:
263
  sentences = response.split('.')
264
  if len(sentences) > 1:
265
  response = sentences[0] + '.'
266
  else:
267
+ words = response.split()
268
+ if len(words) > 20:
269
+ response = ' '.join(words[:20]) + '...'
270
+
271
+ # Pastikan ada tanda baca di akhir
272
+ if response and not any(punct in response[-1] for punct in ['.', '!', '?']):
273
+ if any(word in response.lower() for word in ["apa", "gimana", "bagaimana", "kenapa"]):
274
+ response += "?"
275
+ elif any(word in response.lower() for word in ["wah", "keren", "mantep", "asik"]):
276
+ response += "!"
277
+ else:
278
+ response += "."
279
 
280
  return response
281
 
 
344
  result = pipe(
345
  char_prompt,
346
  max_length=min(len(char_prompt.split()) + model_config["max_tokens"], request.max_length // 2),
347
+ temperature=0.7,
348
  do_sample=True,
349
+ top_p=0.8,
350
+ top_k=40,
351
+ repetition_penalty=1.2,
352
  pad_token_id=pipe.tokenizer.eos_token_id,
353
  num_return_sequences=1,
354
+ early_stopping=True,
355
+ no_repeat_ngram_size=3
356
  )[0]['generated_text']
357
 
358
  # Extract character response
 
576
 
577
  # Run dengan CPU optimizations
578
  if __name__ == "__main__":
579
+ port = int(os.environ.get("PORT", 5000))
580
  uvicorn.run(
581
  app,
582
  host="0.0.0.0",