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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -60
app.py CHANGED
@@ -1,79 +1,51 @@
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. 😊😏]
17
- """
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,
44
- do_sample=True,
45
- pad_token_id=tokenizer.eos_token_id
46
- )
47
 
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)
 
1
  import gradio as gr
 
 
 
 
2
  import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM
4
+ import urllib.parse
5
 
6
+ # Load model and tokenizer
7
+ model_id = "microsoft/phi-2"
8
  tokenizer = AutoTokenizer.from_pretrained(model_id)
9
  model = AutoModelForCausalLM.from_pretrained(model_id)
10
 
11
+ # Global memory for all users
12
+ chat_history = {}
 
 
 
13
 
14
+ # Format past messages
15
  def format_context(history):
16
+ context = ""
17
+ for user, bot in history[-3:]: # Last 3 exchanges
 
 
 
18
  context += f"You: {user}\n𝕴 𝖆𝖒 π–π–Žπ–’: {bot}\n"
19
  return context
20
 
21
+ # Main chat function with memory per user
22
+ def chat_with_memory(query_string):
23
+ parsed = urllib.parse.parse_qs(query_string)
24
+ user_input = parsed.get("query", [""])[0]
25
+ user_id = parsed.get("user_id", ["default"])[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
+ # Get or init user history
28
+ history = chat_history.get(user_id, [])
 
 
29
 
30
+ # Format prompt
31
+ context = format_context(history) + f"You: {user_input}\n𝕴 𝖆𝖒 π–π–Žπ–’:"
32
 
33
+ # Tokenize & generate
34
+ inputs = tokenizer(context, return_tensors="pt", return_attention_mask=True)
35
+ outputs = model.generate(**inputs, max_new_tokens=100, pad_token_id=tokenizer.eos_token_id)
36
+ reply = tokenizer.decode(outputs[0], skip_special_tokens=True).split("𝕴 𝖆𝖒 π–π–Žπ–’:")[-1].strip()
 
 
37
 
38
+ # Save memory
 
 
 
39
  history.append((user_input, reply))
40
+ chat_history[user_id] = history[-10:]
41
 
42
+ return {"reply": reply}
 
 
 
 
43
 
44
+ # Create public /ai?query=&user_id=
45
+ iface = gr.Interface(
46
+ fn=chat_with_memory,
47
+ inputs="text", # URL query string
48
+ outputs="json"
49
+ )
50
 
51
+ iface.launch()