lea97338 commited on
Commit
fc5a194
·
verified ·
1 Parent(s): 085f056

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -0
app.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
3
+ import torch
4
+
5
+ # =========================
6
+ # MODEL (Microsoft CPU léger)
7
+ # =========================
8
+ MODEL_NAME = "microsoft/phi-2"
9
+
10
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
11
+
12
+ model = AutoModelForCausalLM.from_pretrained(
13
+ MODEL_NAME,
14
+ torch_dtype=torch.float32,
15
+ device_map="cpu"
16
+ )
17
+
18
+ generator = pipeline(
19
+ "text-generation",
20
+ model=model,
21
+ tokenizer=tokenizer,
22
+ device=-1
23
+ )
24
+
25
+ # =========================
26
+ # CHAT LOGIC
27
+ # =========================
28
+ def chat(user_message, history):
29
+
30
+ # ✅ prompt système
31
+ system_prompt = """
32
+ You are an AI assistant.
33
+
34
+ If the user wants to generate an image,
35
+ you MUST answer ONLY with:
36
+
37
+ <CSD>image prompt here</CSD>
38
+
39
+ Otherwise respond normally.
40
+ """
41
+
42
+ # ✅ contexte court (rapide)
43
+ conversation = system_prompt + "\n"
44
+
45
+ for user, bot in history[-3:]:
46
+ conversation += f"User: {user}\nAssistant: {bot}\n"
47
+
48
+ conversation += f"User: {user_message}\nAssistant:"
49
+
50
+ # ✅ génération
51
+ output = generator(
52
+ conversation,
53
+ max_new_tokens=100,
54
+ temperature=0.7,
55
+ do_sample=True
56
+ )[0]["generated_text"]
57
+
58
+ response = output.split("Assistant:")[-1].strip()
59
+
60
+ history.append((user_message, response))
61
+
62
+ return history, ""
63
+
64
+ # =========================
65
+ # UI
66
+ # =========================
67
+ with gr.Blocks() as demo:
68
+
69
+ gr.Markdown("# 🤖 Microsoft Phi-2 Chatbot")
70
+
71
+ chatbot = gr.Chatbot(height=500)
72
+
73
+ msg = gr.Textbox(
74
+ placeholder="Pose une question ou demande une image...",
75
+ label="Message"
76
+ )
77
+
78
+ clear = gr.Button("🗑️ Clear")
79
+
80
+ msg.submit(chat, [msg, chatbot], [chatbot, msg])
81
+ clear.click(lambda: [], None, chatbot)
82
+
83
+ # =========================
84
+ # RUN
85
+ # =========================
86
+ if __name__ == "__main__":
87
+ demo.launch()