Trigger82 commited on
Commit
d28821f
Β·
verified Β·
1 Parent(s): 55f4325

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -15
app.py CHANGED
@@ -1,11 +1,16 @@
1
  import gradio as gr
 
 
 
2
  from transformers import AutoTokenizer, AutoModelForCausalLM
3
  import torch
4
 
 
5
  model_id = "microsoft/DialoGPT-medium"
6
  tokenizer = AutoTokenizer.from_pretrained(model_id)
7
  model = AutoModelForCausalLM.from_pretrained(model_id)
8
 
 
9
  PERSONA = """
10
  [System: You are 𝕴 𝖆𝖒 π–π–Žπ–’ - a fun, smooth, emotionally intelligent AI.
11
  You speak like a real person, not a robot. Keep it under 15 words. 😊😏]
@@ -13,29 +18,26 @@ You speak like a real person, not a robot. Keep it under 15 words. 😊😏]
13
 
14
  def format_context(history):
15
  context = PERSONA + "\n"
 
 
 
16
  for user, bot in history[-3:]:
17
  context += f"You: {user}\n𝕴 𝖆𝖒 π–π–Žπ–’: {bot}\n"
18
  return context
19
 
20
  def enhance_response(resp, message):
21
- if any(x in message for x in ["?", "think", "why"]):
22
  resp += " πŸ€”"
23
  elif any(x in resp.lower() for x in ["cool", "great", "love", "fun"]):
24
  resp += " 😏"
25
  return " ".join(resp.split()[:15])
26
 
27
- def chat(user_input, history):
28
- if history is None:
29
- history = []
30
-
31
  context = format_context(history) + f"You: {user_input}\n𝕴 𝖆𝖒 π–π–Žπ–’:"
32
- encoded = tokenizer(context, return_tensors="pt", truncation=True, max_length=1024)
33
- inputs = encoded.input_ids
34
- attention_mask = encoded.attention_mask
35
 
36
  outputs = model.generate(
37
  inputs,
38
- attention_mask=attention_mask,
39
  max_new_tokens=50,
40
  temperature=0.9,
41
  top_k=40,
@@ -46,12 +48,32 @@ def chat(user_input, history):
46
  full_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
47
  response = full_text.split("𝕴 𝖆𝖒 π–π–Žπ–’:")[-1].split("\nYou:")[0].strip()
48
  response = enhance_response(response, user_input)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
- history.append((user_input, response))
51
- return history
 
 
 
52
 
53
- # Create the Gradio Interface
54
- demo = gr.Interface(fn=chat, inputs=["text", "state"], outputs="state")
55
 
56
- # Launch the app
57
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
  import gradio as gr
2
+ from fastapi import FastAPI, Query
3
+ from fastapi.middleware.wsgi import WSGIMiddleware
4
+ import uvicorn
5
  from transformers import AutoTokenizer, AutoModelForCausalLM
6
  import torch
7
 
8
+ # Load model and tokenizer once
9
  model_id = "microsoft/DialoGPT-medium"
10
  tokenizer = AutoTokenizer.from_pretrained(model_id)
11
  model = AutoModelForCausalLM.from_pretrained(model_id)
12
 
13
+ # Your AI persona prompt
14
  PERSONA = """
15
  [System: You are 𝕴 𝖆𝖒 π–π–Žπ–’ - a fun, smooth, emotionally intelligent AI.
16
  You speak like a real person, not a robot. Keep it under 15 words. 😊😏]
 
18
 
19
  def format_context(history):
20
  context = PERSONA + "\n"
21
+ if not history:
22
+ return context
23
+ # Use only last 3 exchanges to keep it short
24
  for user, bot in history[-3:]:
25
  context += f"You: {user}\n𝕴 𝖆𝖒 π–π–Žπ–’: {bot}\n"
26
  return context
27
 
28
  def enhance_response(resp, message):
29
+ if any(x in message.lower() for x in ["?", "think", "why"]):
30
  resp += " πŸ€”"
31
  elif any(x in resp.lower() for x in ["cool", "great", "love", "fun"]):
32
  resp += " 😏"
33
  return " ".join(resp.split()[:15])
34
 
35
+ def generate_ai_reply(user_input, history):
 
 
 
36
  context = format_context(history) + f"You: {user_input}\n𝕴 𝖆𝖒 π–π–Žπ–’:"
37
+ inputs = tokenizer.encode(context, return_tensors="pt", truncation=True, max_length=1024)
 
 
38
 
39
  outputs = model.generate(
40
  inputs,
 
41
  max_new_tokens=50,
42
  temperature=0.9,
43
  top_k=40,
 
48
  full_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
49
  response = full_text.split("𝕴 𝖆𝖒 π–π–Žπ–’:")[-1].split("\nYou:")[0].strip()
50
  response = enhance_response(response, user_input)
51
+ return response
52
+
53
+ app = FastAPI()
54
+
55
+ # GET /ai?query=some+text => returns {"reply": "AI reply here"}
56
+ @app.get("/ai")
57
+ async def ai_endpoint(query: str = Query(..., min_length=1)):
58
+ # For stateless API calls, history is empty (or you can extend to save history)
59
+ reply = generate_ai_reply(query, history=[])
60
+ return {"reply": reply}
61
+
62
+ # Gradio chat interface for interactive web UI
63
+ def chat(user_input, history):
64
+ history = history or []
65
+ reply = generate_ai_reply(user_input, history)
66
+ history.append((user_input, reply))
67
+ return history, history
68
 
69
+ with gr.Blocks() as demo:
70
+ chatbot = gr.Chatbot()
71
+ msg = gr.Textbox(placeholder="Say something...")
72
+ state = gr.State()
73
+ msg.submit(chat, inputs=[msg, state], outputs=[chatbot, state])
74
 
75
+ # Mount Gradio UI at root
76
+ app.mount("/", WSGIMiddleware(demo.launch(prevent_thread_lock=True, share=False)))
77
 
78
+ if __name__ == "__main__":
79
+ uvicorn.run(app, host="0.0.0.0", port=7860)