Spaces:
Runtime error
Runtime error
version 2
Browse files
app.py
CHANGED
@@ -1,101 +1,63 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
import
|
4 |
-
from collections.abc import Iterator
|
5 |
-
from threading import Thread
|
6 |
-
|
7 |
-
import gradio as gr
|
8 |
-
import spaces
|
9 |
import torch
|
10 |
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
|
|
11 |
|
12 |
-
|
13 |
-
<h1 style="color:black;">Mistral-7B v0.3</h1>
|
14 |
-
"""
|
15 |
-
|
16 |
-
if not torch.cuda.is_available():
|
17 |
-
DESCRIPTION += "\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>"
|
18 |
-
|
19 |
-
MAX_MAX_NEW_TOKENS = 2048
|
20 |
-
DEFAULT_MAX_NEW_TOKENS = 1024
|
21 |
-
MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
|
22 |
|
|
|
23 |
if torch.cuda.is_available():
|
24 |
model_id = "mistralai/Mistral-7B-Instruct-v0.3"
|
25 |
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto")
|
26 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
|
|
|
|
|
|
27 |
|
|
|
28 |
|
29 |
-
|
30 |
-
|
31 |
-
message: str,
|
32 |
-
chat_history: list[dict],
|
33 |
-
max_new_tokens: int = 1024,
|
34 |
-
temperature: float = 0.6,
|
35 |
-
top_p: float = 0.9,
|
36 |
-
top_k: int = 50,
|
37 |
-
repetition_penalty: float = 1.2,
|
38 |
-
) -> Iterator[str]:
|
39 |
-
conversation = [*chat_history, {"role": "user", "content": message}]
|
40 |
input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
|
41 |
if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
|
42 |
input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
|
43 |
-
gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
|
44 |
input_ids = input_ids.to(model.device)
|
45 |
-
|
46 |
streamer = TextIteratorStreamer(tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True)
|
47 |
-
generate_kwargs =
|
48 |
-
|
49 |
-
streamer
|
50 |
-
max_new_tokens
|
51 |
-
do_sample
|
52 |
-
top_p
|
53 |
-
top_k
|
54 |
-
temperature
|
55 |
-
num_beams
|
56 |
-
repetition_penalty
|
57 |
-
|
58 |
t = Thread(target=model.generate, kwargs=generate_kwargs)
|
59 |
t.start()
|
60 |
-
|
61 |
-
|
62 |
for text in streamer:
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
["1 - C’est quoi le consentement ? Comment savoir si ma copine a envie de moi ?"], # noqa: RUF001
|
80 |
-
["2 - C’est quoi une agression sexuelle ?"],
|
81 |
-
["3 - C’est quoi un viol ?"],
|
82 |
-
["4 - C’est quoi un attouchement ?"],
|
83 |
-
["5 - C’est quoi un harcèlement sexuel ?"],
|
84 |
-
["6 - Est ce illégal de visionner du porno ?"],
|
85 |
-
["7 - Mon copain me demande un nude, dois-je le faire ?"],
|
86 |
-
["8 - Mon ancien copain me menace de poster des photos de moi nue sur internet, que faire ?"],
|
87 |
-
[
|
88 |
-
"9 - Que puis-je faire si un membre de ma famille me touche d’une manière bizarre, mais que j’ai peur de parler ou de ne pas être cru ?"
|
89 |
-
],
|
90 |
-
]
|
91 |
-
|
92 |
-
demo = gr.ChatInterface(
|
93 |
-
fn=generate,
|
94 |
-
type="messages",
|
95 |
-
description=DESCRIPTION,
|
96 |
-
css=custom_css, # On applique le CSS pastel global
|
97 |
-
examples=predefined_examples,
|
98 |
-
)
|
99 |
|
100 |
if __name__ == "__main__":
|
101 |
-
|
|
|
1 |
+
from fastapi import FastAPI, Request
|
2 |
+
from fastapi.responses import HTMLResponse, JSONResponse
|
3 |
+
import uvicorn
|
|
|
|
|
|
|
|
|
|
|
4 |
import torch
|
5 |
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
6 |
+
from threading import Thread
|
7 |
|
8 |
+
app = FastAPI()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
+
# Chargement du modèle uniquement si CUDA est disponible
|
11 |
if torch.cuda.is_available():
|
12 |
model_id = "mistralai/Mistral-7B-Instruct-v0.3"
|
13 |
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto")
|
14 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
15 |
+
else:
|
16 |
+
model = None
|
17 |
+
tokenizer = None
|
18 |
|
19 |
+
MAX_INPUT_TOKEN_LENGTH = 4096
|
20 |
|
21 |
+
def generate_response(message: str, history: list) -> str:
|
22 |
+
conversation = history + [{"role": "user", "content": message}]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
|
24 |
if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
|
25 |
input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
|
|
|
26 |
input_ids = input_ids.to(model.device)
|
27 |
+
|
28 |
streamer = TextIteratorStreamer(tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True)
|
29 |
+
generate_kwargs = {
|
30 |
+
"input_ids": input_ids,
|
31 |
+
"streamer": streamer,
|
32 |
+
"max_new_tokens": 1024,
|
33 |
+
"do_sample": True,
|
34 |
+
"top_p": 0.9,
|
35 |
+
"top_k": 50,
|
36 |
+
"temperature": 0.6,
|
37 |
+
"num_beams": 1,
|
38 |
+
"repetition_penalty": 1.2,
|
39 |
+
}
|
40 |
t = Thread(target=model.generate, kwargs=generate_kwargs)
|
41 |
t.start()
|
42 |
+
|
43 |
+
response_text = ""
|
44 |
for text in streamer:
|
45 |
+
response_text += text
|
46 |
+
return response_text
|
47 |
+
|
48 |
+
@app.post("/chat")
|
49 |
+
async def chat_endpoint(request: Request):
|
50 |
+
data = await request.json()
|
51 |
+
message = data.get("message", "")
|
52 |
+
# Utilisation d'un historique vide pour simplifier
|
53 |
+
response_text = generate_response(message, history=[])
|
54 |
+
return JSONResponse({"response": response_text})
|
55 |
+
|
56 |
+
@app.get("/", response_class=HTMLResponse)
|
57 |
+
async def root():
|
58 |
+
with open("index.html", "r", encoding="utf-8") as f:
|
59 |
+
html_content = f.read()
|
60 |
+
return HTMLResponse(content=html_content, status_code=200)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
if __name__ == "__main__":
|
63 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|