File size: 3,889 Bytes
b02d52a 1c6034b b02d52a 1c6034b 5887122 4005dc6 b02d52a 5887122 1c6034b 5887122 b02d52a 5887122 4005dc6 b02d52a 4005dc6 5887122 4005dc6 5887122 4005dc6 5887122 4005dc6 5887122 1c6034b 5887122 b02d52a 4005dc6 83b105d b02d52a 4005dc6 b02d52a 5887122 b02d52a 4005dc6 b02d52a 1c6034b 4005dc6 b02d52a 5887122 b02d52a 1c6034b 4005dc6 966e298 b02d52a 4005dc6 b02d52a 1c6034b b02d52a 1c6034b a86c03a 5887122 a86c03a 5887122 79383bb 5887122 0ffc6c7 a86c03a 5887122 591f1c9 5887122 1c6034b 591f1c9 5887122 1c6034b 5887122 4005dc6 |
1 2 3 4 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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
import os
from threading import Thread
from typing import Iterator
import gradio as gr
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
# Limites des tokens
MAX_MAX_NEW_TOKENS = 2048
DEFAULT_MAX_NEW_TOKENS = 1024
MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
# Description de l'application
DESCRIPTION = """\
# Dany-1.0
Dany est une IA avancée. Elle est spécialisée dans les langages de programmation.
"""
# Vérification de la disponibilité de CUDA
if not torch.cuda.is_available():
print("CUDA n'est pas disponible. Exécution sur CPU 🥶. Le modèle sera plus lent.")
model_id = "deepseek-ai/deepseek-coder-1.3b-instruct"
model = AutoModelForCausalLM.from_pretrained(model_id)
tokenizer = AutoTokenizer.from_pretrained(model_id)
tokenizer.use_default_system_prompt = False
else:
print("CUDA est disponible. Exécution sur GPU 🚀.")
model_id = "deepseek-ai/deepseek-coder-1.3b-instruct"
model = AutoModelForCausalLM.from_pretrained(
model_id, torch_dtype=torch.bfloat16, device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(model_id)
tokenizer.use_default_system_prompt = False
# Prompt système personnalisé pour Dany
DANY_SYSTEM_PROMPT = """
Tu es Dany, une intelligence artificielle avancée créée par Giovanni Lucas Correia, un programmeur ambitieux de 21 ans.
Tu es spécialisée dans la programmation, en particulier en Python et Delphi.
Tu peux parler trois langues : français, portugais et anglais.
"""
# Fonction pour générer des réponses
def generate(
message: str,
chat_history: list,
system_prompt: str = DANY_SYSTEM_PROMPT,
max_new_tokens: int = DEFAULT_MAX_NEW_TOKENS,
temperature: float = 1.0,
top_k: int = 50,
repetition_penalty: float = 1.0,
) -> Iterator[str]:
conversation = []
if system_prompt:
conversation.append({"role": "system", "content": system_prompt})
for user, assistant in chat_history:
conversation.extend(
[{"role": "user", "content": user}, {"role": "assistant", "content": assistant}]
)
conversation.append({"role": "user", "content": message})
input_ids = tokenizer.apply_chat_template(
conversation, return_tensors="pt", add_generation_prompt=True
)
if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
gr.Warning(
f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens."
)
input_ids = input_ids.to(model.device)
streamer = TextIteratorStreamer(
tokenizer, timeout=30.0, skip_prompt=True, skip_special_tokens=True
)
generate_kwargs = {
"input_ids": input_ids,
"streamer": streamer,
"max_new_tokens": max_new_tokens,
"do_sample": False,
"num_beams": 1,
"repetition_penalty": repetition_penalty,
"eos_token_id": tokenizer.eos_token_id,
}
t = Thread(target=model.generate, kwargs=generate_kwargs)
t.start()
outputs = []
for text in streamer:
outputs.append(text)
yield "".join(outputs).replace("<|EOT|>", "")
# Interface de chat
chat_interface = gr.ChatInterface(
fn=generate,
additional_inputs=[], # Supprime les inputs supplémentaires
stop_btn=None,
examples=[
["Qui t'a créé et quelles sont tes compétences ?"],
["Peux-tu écrire un algorithme de tri rapide en Python ?"],
["Code du python."],
],
)
# Bloc Gradio
# Bloc Gradio avec style CSS pour cacher "Built with Gradio"
with gr.Blocks(css="""
footer {visibility: hidden;}
""") as demo:
gr.Markdown(DESCRIPTION)
chat_interface.render()
# Lancement de l'application
if __name__ == "__main__":
demo.launch(share=True, show_api=False)
|