Update app.py
Browse files
app.py
CHANGED
|
@@ -2,6 +2,8 @@
|
|
| 2 |
#app.py_143
|
| 3 |
|
| 4 |
|
|
|
|
|
|
|
| 5 |
import os
|
| 6 |
import gradio as gr
|
| 7 |
from huggingface_hub import hf_hub_download, login
|
|
@@ -12,7 +14,7 @@ import torch
|
|
| 12 |
from llama_cpp import Llama
|
| 13 |
import time
|
| 14 |
|
| 15 |
-
# Configuration des modèles et PREPROMPT
|
| 16 |
TEXT_MODELS = {
|
| 17 |
"Utter-Project_EuroLLM-1.7B": "utter-project/EuroLLM-1.7B",
|
| 18 |
"Mistral Nemo 2407 (GGUF)": "MisterAI/Bartowski_MistralAI_Mistral-Nemo-Instruct-2407-IQ4_XS.gguf",
|
|
@@ -43,142 +45,22 @@ Points:
|
|
| 43 |
|
| 44 |
Analysez le texte suivant et créez une présentation professionnelle :"""
|
| 45 |
|
|
|
|
| 46 |
class PresentationGenerator:
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
if not self.token:
|
| 50 |
-
raise ValueError("Token d'authentification HuggingFace non trouvé")
|
| 51 |
-
login(self.token)
|
| 52 |
-
self.text_model = None
|
| 53 |
-
self.text_tokenizer = None
|
| 54 |
-
self.loaded_model = None
|
| 55 |
-
|
| 56 |
-
def load_text_model(self, model_name):
|
| 57 |
-
"""Charge le modèle de génération de texte"""
|
| 58 |
-
if self.loaded_model == model_name:
|
| 59 |
-
print(f"Modèle {model_name} déjà chargé.")
|
| 60 |
-
return
|
| 61 |
-
|
| 62 |
-
model_id = TEXT_MODELS[model_name]
|
| 63 |
-
model_path = None
|
| 64 |
-
|
| 65 |
-
# Vérifiez si le modèle est déjà téléchargé localement
|
| 66 |
-
if model_id.endswith('.gguf'):
|
| 67 |
-
model_filename = model_id.split('/')[-1]
|
| 68 |
-
local_path = f"./models/{model_filename}"
|
| 69 |
-
if os.path.exists(local_path):
|
| 70 |
-
model_path = local_path
|
| 71 |
-
else:
|
| 72 |
-
model_path = hf_hub_download(
|
| 73 |
-
repo_id=model_id.split('/')[0] + '/' + model_id.split('/')[1],
|
| 74 |
-
filename=model_filename,
|
| 75 |
-
token=self.token,
|
| 76 |
-
cache_dir="./models"
|
| 77 |
-
)
|
| 78 |
-
self.text_model = Llama(
|
| 79 |
-
model_path=model_path,
|
| 80 |
-
n_ctx=4096,
|
| 81 |
-
n_batch=512,
|
| 82 |
-
verbose=False
|
| 83 |
-
)
|
| 84 |
-
print(f"Modèle GGUF {model_id} chargé avec succès!")
|
| 85 |
-
else:
|
| 86 |
-
self.text_tokenizer = AutoTokenizer.from_pretrained(model_id, token=self.token)
|
| 87 |
-
self.text_model = AutoModelForCausalLM.from_pretrained(
|
| 88 |
-
model_id,
|
| 89 |
-
torch_dtype=torch.bfloat16,
|
| 90 |
-
device_map="auto",
|
| 91 |
-
token=self.token
|
| 92 |
-
)
|
| 93 |
-
print(f"Modèle Transformers {model_id} chargé avec succès!")
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
def generate_text(self, prompt, temperature=0.7, max_tokens=4096):
|
| 98 |
-
"""Génère le texte de la présentation"""
|
| 99 |
-
start_time = time.time()
|
| 100 |
-
if isinstance(self.text_model, Llama):
|
| 101 |
-
response = self.text_model(
|
| 102 |
-
prompt,
|
| 103 |
-
max_tokens=max_tokens,
|
| 104 |
-
temperature=temperature,
|
| 105 |
-
echo=False
|
| 106 |
-
)
|
| 107 |
-
generated_text = response['choices'][0]['text']
|
| 108 |
-
else:
|
| 109 |
-
inputs = self.text_tokenizer(prompt, return_tensors="pt")
|
| 110 |
-
outputs = self.text_model.generate(
|
| 111 |
-
**inputs,
|
| 112 |
-
max_new_tokens=max_tokens,
|
| 113 |
-
temperature=temperature,
|
| 114 |
-
do_sample=True
|
| 115 |
-
)
|
| 116 |
-
generated_text = self.text_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 117 |
-
|
| 118 |
-
print(f"Texte généré en {time.time() - start_time:.2f} secondes")
|
| 119 |
-
return generated_text
|
| 120 |
-
|
| 121 |
-
def parse_presentation_content(self, content):
|
| 122 |
-
"""Parse le contenu généré en sections pour les diapositives"""
|
| 123 |
-
slides = []
|
| 124 |
-
current_slide = None
|
| 125 |
-
|
| 126 |
-
for line in content.split('\n'):
|
| 127 |
-
line = line.strip()
|
| 128 |
-
print(f"#LOG supplémentaire: Parsing line: {line}") # LOG supplémentaire
|
| 129 |
-
if line.startswith('TITRE:'):
|
| 130 |
-
slides.append({'type': 'title', 'title': line[6:].strip()})
|
| 131 |
-
elif line.startswith('DIAPO'):
|
| 132 |
-
if current_slide:
|
| 133 |
-
slides.append(current_slide)
|
| 134 |
-
current_slide = {'type': 'content', 'title': '', 'points': []}
|
| 135 |
-
elif line.startswith('Titre:') and current_slide:
|
| 136 |
-
current_slide['title'] = line[6:].strip()
|
| 137 |
-
elif line.startswith('- ') and current_slide:
|
| 138 |
-
current_slide['points'].append(line[2:].strip())
|
| 139 |
-
|
| 140 |
-
if current_slide:
|
| 141 |
-
slides.append(current_slide)
|
| 142 |
-
|
| 143 |
-
print(f"#LOG supplémentaire: Parsed slides: {slides}") # LOG supplémentaire
|
| 144 |
-
return slides
|
| 145 |
-
|
| 146 |
-
def create_presentation(self, slides):
|
| 147 |
-
"""Crée la présentation PowerPoint avec texte uniquement"""
|
| 148 |
-
prs = Presentation()
|
| 149 |
-
|
| 150 |
-
# Première diapo (titre)
|
| 151 |
-
title_slide = prs.slides.add_slide(prs.slide_layouts[0])
|
| 152 |
-
title_slide.shapes.title.text = slides[0]['title']
|
| 153 |
-
|
| 154 |
-
# Autres diapos
|
| 155 |
-
for slide in slides[1:]:
|
| 156 |
-
content_slide = prs.slides.add_slide(prs.slide_layouts[1])
|
| 157 |
-
content_slide.shapes.title.text = slide['title']
|
| 158 |
-
|
| 159 |
-
# Ajout du texte
|
| 160 |
-
if slide['points']:
|
| 161 |
-
body = content_slide.shapes.placeholders[1].text_frame
|
| 162 |
-
body.clear()
|
| 163 |
-
for point in slide['points']:
|
| 164 |
-
p = body.add_paragraph()
|
| 165 |
-
p.text = point
|
| 166 |
-
p.level = 0
|
| 167 |
-
|
| 168 |
-
return prs
|
| 169 |
-
|
| 170 |
-
def generate_skeleton(text, text_model_name, temperature, max_tokens, progress=gr.Progress()):
|
| 171 |
"""Génère le squelette de la présentation"""
|
| 172 |
try:
|
| 173 |
start_time = time.time()
|
| 174 |
generator = PresentationGenerator()
|
| 175 |
|
| 176 |
# Chargement du modèle de texte uniquement
|
| 177 |
-
progress(0, desc="Chargement du modèle...")
|
| 178 |
generator.load_text_model(text_model_name)
|
| 179 |
|
| 180 |
# Génération du contenu
|
| 181 |
-
progress(0.5, desc="Génération du contenu de la présentation...")
|
| 182 |
full_prompt = PREPROMPT + "\n\n" + text
|
| 183 |
generated_content = generator.generate_text(full_prompt, temperature, max_tokens)
|
| 184 |
|
|
@@ -190,15 +72,14 @@ def generate_skeleton(text, text_model_name, temperature, max_tokens, progress=g
|
|
| 190 |
|
| 191 |
except Exception as e:
|
| 192 |
print(f"Erreur lors de la génération: {str(e)}")
|
| 193 |
-
return f"Erreur: {str(e)}", None,
|
| 194 |
|
| 195 |
-
def create_presentation_file(generated_content
|
| 196 |
"""Crée le fichier PowerPoint à partir du contenu généré"""
|
| 197 |
try:
|
| 198 |
generator = PresentationGenerator()
|
| 199 |
|
| 200 |
# Création de la présentation
|
| 201 |
-
progress(0, desc="Création de la présentation PowerPoint...")
|
| 202 |
slides = generator.parse_presentation_content(generated_content)
|
| 203 |
prs = generator.create_presentation(slides)
|
| 204 |
|
|
@@ -210,13 +91,13 @@ def create_presentation_file(generated_content, progress=gr.Progress()):
|
|
| 210 |
if not os.path.exists(output_path):
|
| 211 |
raise FileNotFoundError(f"Le fichier {output_path} n'a pas été créé correctement")
|
| 212 |
|
| 213 |
-
progress(1, desc="Présentation créée avec succès!")
|
| 214 |
return output_path
|
| 215 |
|
| 216 |
except Exception as e:
|
| 217 |
print(f"Erreur lors de la création du fichier: {str(e)}")
|
| 218 |
return None
|
| 219 |
|
|
|
|
| 220 |
with gr.Blocks(theme=gr.themes.Glass()) as demo:
|
| 221 |
gr.Markdown(
|
| 222 |
"""
|
|
@@ -274,16 +155,15 @@ with gr.Blocks(theme=gr.themes.Glass()) as demo:
|
|
| 274 |
output_file = gr.File(
|
| 275 |
label="Présentation PowerPoint"
|
| 276 |
)
|
| 277 |
-
progress_bar = gr.Progress(track_tqdm=True)
|
| 278 |
|
|
|
|
| 279 |
generate_skeleton_btn.click(
|
| 280 |
fn=generate_skeleton,
|
| 281 |
inputs=[
|
| 282 |
input_text,
|
| 283 |
text_model_choice,
|
| 284 |
temperature,
|
| 285 |
-
max_tokens
|
| 286 |
-
progress_bar
|
| 287 |
],
|
| 288 |
outputs=[
|
| 289 |
status_output,
|
|
@@ -294,8 +174,8 @@ with gr.Blocks(theme=gr.themes.Glass()) as demo:
|
|
| 294 |
|
| 295 |
create_presentation_btn.click(
|
| 296 |
fn=create_presentation_file,
|
| 297 |
-
inputs=generated_content,
|
| 298 |
-
outputs=output_file
|
| 299 |
)
|
| 300 |
|
| 301 |
if __name__ == "__main__":
|
|
@@ -309,6 +189,3 @@ if __name__ == "__main__":
|
|
| 309 |
|
| 310 |
|
| 311 |
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
|
|
|
| 2 |
#app.py_143
|
| 3 |
|
| 4 |
|
| 5 |
+
|
| 6 |
+
# [Imports et configuration des modèles restent identiques]
|
| 7 |
import os
|
| 8 |
import gradio as gr
|
| 9 |
from huggingface_hub import hf_hub_download, login
|
|
|
|
| 14 |
from llama_cpp import Llama
|
| 15 |
import time
|
| 16 |
|
| 17 |
+
# Configuration des modèles et PREPROMPT [inchangés]
|
| 18 |
TEXT_MODELS = {
|
| 19 |
"Utter-Project_EuroLLM-1.7B": "utter-project/EuroLLM-1.7B",
|
| 20 |
"Mistral Nemo 2407 (GGUF)": "MisterAI/Bartowski_MistralAI_Mistral-Nemo-Instruct-2407-IQ4_XS.gguf",
|
|
|
|
| 45 |
|
| 46 |
Analysez le texte suivant et créez une présentation professionnelle :"""
|
| 47 |
|
| 48 |
+
# [La classe PresentationGenerator reste inchangée]
|
| 49 |
class PresentationGenerator:
|
| 50 |
+
# [Le code de la classe reste identique]
|
| 51 |
+
[...]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
+
# Correction des fonctions de génération pour gérer correctement le progress
|
| 54 |
+
def generate_skeleton(text, text_model_name, temperature, max_tokens):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
"""Génère le squelette de la présentation"""
|
| 56 |
try:
|
| 57 |
start_time = time.time()
|
| 58 |
generator = PresentationGenerator()
|
| 59 |
|
| 60 |
# Chargement du modèle de texte uniquement
|
|
|
|
| 61 |
generator.load_text_model(text_model_name)
|
| 62 |
|
| 63 |
# Génération du contenu
|
|
|
|
| 64 |
full_prompt = PREPROMPT + "\n\n" + text
|
| 65 |
generated_content = generator.generate_text(full_prompt, temperature, max_tokens)
|
| 66 |
|
|
|
|
| 72 |
|
| 73 |
except Exception as e:
|
| 74 |
print(f"Erreur lors de la génération: {str(e)}")
|
| 75 |
+
return f"Erreur: {str(e)}", None, gr.update(visible=False)
|
| 76 |
|
| 77 |
+
def create_presentation_file(generated_content):
|
| 78 |
"""Crée le fichier PowerPoint à partir du contenu généré"""
|
| 79 |
try:
|
| 80 |
generator = PresentationGenerator()
|
| 81 |
|
| 82 |
# Création de la présentation
|
|
|
|
| 83 |
slides = generator.parse_presentation_content(generated_content)
|
| 84 |
prs = generator.create_presentation(slides)
|
| 85 |
|
|
|
|
| 91 |
if not os.path.exists(output_path):
|
| 92 |
raise FileNotFoundError(f"Le fichier {output_path} n'a pas été créé correctement")
|
| 93 |
|
|
|
|
| 94 |
return output_path
|
| 95 |
|
| 96 |
except Exception as e:
|
| 97 |
print(f"Erreur lors de la création du fichier: {str(e)}")
|
| 98 |
return None
|
| 99 |
|
| 100 |
+
# Interface Gradio corrigée
|
| 101 |
with gr.Blocks(theme=gr.themes.Glass()) as demo:
|
| 102 |
gr.Markdown(
|
| 103 |
"""
|
|
|
|
| 155 |
output_file = gr.File(
|
| 156 |
label="Présentation PowerPoint"
|
| 157 |
)
|
|
|
|
| 158 |
|
| 159 |
+
# Correction des événements click
|
| 160 |
generate_skeleton_btn.click(
|
| 161 |
fn=generate_skeleton,
|
| 162 |
inputs=[
|
| 163 |
input_text,
|
| 164 |
text_model_choice,
|
| 165 |
temperature,
|
| 166 |
+
max_tokens
|
|
|
|
| 167 |
],
|
| 168 |
outputs=[
|
| 169 |
status_output,
|
|
|
|
| 174 |
|
| 175 |
create_presentation_btn.click(
|
| 176 |
fn=create_presentation_file,
|
| 177 |
+
inputs=[generated_content],
|
| 178 |
+
outputs=[output_file]
|
| 179 |
)
|
| 180 |
|
| 181 |
if __name__ == "__main__":
|
|
|
|
| 189 |
|
| 190 |
|
| 191 |
|
|
|
|
|
|
|
|
|