Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,100 +1,50 @@
|
|
1 |
-
import
|
2 |
-
from
|
3 |
-
import
|
4 |
-
import
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
|
|
|
|
|
|
21 |
|
22 |
-
#
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
messages=messages,
|
49 |
-
max_tokens=max_tokens,
|
50 |
-
temperature=temperature,
|
51 |
-
top_p=top_p,
|
52 |
-
stream=True
|
53 |
-
)
|
54 |
-
print("✅ Requête envoyée au modèle avec succès.")
|
55 |
-
except Exception as e:
|
56 |
-
print(f"⚠️ Erreur lors de l'appel à l'API : {e}")
|
57 |
-
return "Erreur lors de l'appel à l'API."
|
58 |
-
|
59 |
-
# Stream des tokens au fur et à mesure
|
60 |
-
partial_message = ""
|
61 |
-
try:
|
62 |
-
for chunk in stream:
|
63 |
-
token = chunk.choices[0].delta.content
|
64 |
-
if token:
|
65 |
-
partial_message += token
|
66 |
-
print(f"📝 Token reçu : {token}") # Vérifie si les tokens arrivent progressivement
|
67 |
-
yield partial_message # Envoi chaque token au fur et à mesure
|
68 |
-
except Exception as e:
|
69 |
-
print(f"⚠️ Erreur lors du streaming des tokens : {e}")
|
70 |
-
return "Erreur lors du streaming des tokens."
|
71 |
-
|
72 |
-
# 3. Configuration de l'interface Gradio
|
73 |
-
print("🔄 Configuration de l'interface Gradio...")
|
74 |
-
try:
|
75 |
-
demo = gr.ChatInterface(
|
76 |
-
fn=stream_response,
|
77 |
-
additional_inputs=[
|
78 |
-
gr.Textbox(value="You are a helpful AI assistant.", label="System message"),
|
79 |
-
gr.Slider(1, 2048, value=512, label="Max tokens"),
|
80 |
-
gr.Slider(0.1, 1.0, value=0.7, label="Temperature"),
|
81 |
-
gr.Slider(0.1, 1.0, value=0.9, label="Top-p")
|
82 |
-
],
|
83 |
-
title="Phi-3 Chatbot (Streaming)",
|
84 |
-
examples=[
|
85 |
-
["Explain quantum computing"],
|
86 |
-
["Write a poem about AI"]
|
87 |
-
],
|
88 |
-
chatbot=gr.Chatbot(height=500, label="Phi-3 Chat", show_copy_button=True)
|
89 |
-
)
|
90 |
-
print("✅ Interface Gradio configurée.")
|
91 |
-
except Exception as e:
|
92 |
-
print(f"⚠️ Erreur lors de la configuration de l'interface Gradio : {e}")
|
93 |
-
|
94 |
-
# 4. Lancement de l'application
|
95 |
-
print("🔄 Lancement de l'application Gradio...")
|
96 |
-
try:
|
97 |
-
demo.launch(share=True)
|
98 |
-
print("✅ Application lancée avec succès.")
|
99 |
-
except Exception as e:
|
100 |
-
print(f"⚠️ Erreur lors du lancement de l'application : {e}")
|
|
|
1 |
+
from fastapi import FastAPI, Request
|
2 |
+
from fastapi.responses import StreamingResponse, HTMLResponse
|
3 |
+
from fastapi.staticfiles import StaticFiles
|
4 |
+
from fastapi.templating import Jinja2Templates
|
5 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
6 |
+
import torch
|
7 |
+
import asyncio
|
8 |
+
|
9 |
+
app = FastAPI()
|
10 |
+
app.mount("/static", StaticFiles(directory="static"), name="static")
|
11 |
+
templates = Jinja2Templates(directory="templates")
|
12 |
+
|
13 |
+
# Charger le modèle public (sans token)
|
14 |
+
model_name = "microsoft/Phi-3.5-mini-instruct"
|
15 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
16 |
+
model = AutoModelForCausalLM.from_pretrained(
|
17 |
+
model_name,
|
18 |
+
torch_dtype=torch.float16,
|
19 |
+
device_map="auto"
|
20 |
+
)
|
21 |
+
|
22 |
+
async def generate_response(prompt: str):
|
23 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
24 |
|
25 |
+
# Génération token par token
|
26 |
+
with torch.no_grad():
|
27 |
+
for _ in range(512): # Limite de tokens
|
28 |
+
outputs = model.generate(
|
29 |
+
**inputs,
|
30 |
+
max_new_tokens=1,
|
31 |
+
do_sample=True,
|
32 |
+
temperature=0.7,
|
33 |
+
top_p=0.9
|
34 |
+
)
|
35 |
+
new_token = tokenizer.decode(outputs[0][-1], skip_special_tokens=True)
|
36 |
+
yield f"data: {new_token}\n\n"
|
37 |
+
await asyncio.sleep(0.05)
|
38 |
+
|
39 |
+
inputs = {"input_ids": outputs}
|
40 |
+
|
41 |
+
@app.get("/", response_class=HTMLResponse)
|
42 |
+
async def home(request: Request):
|
43 |
+
return templates.TemplateResponse("index.html", {"request": request})
|
44 |
+
|
45 |
+
@app.get("/stream")
|
46 |
+
async def stream(prompt: str):
|
47 |
+
return StreamingResponse(
|
48 |
+
generate_response(prompt),
|
49 |
+
media_type="text/event-stream"
|
50 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|