MisterAI commited on
Commit
bb6cb3c
·
verified ·
1 Parent(s): 3be8d14

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +219 -0
app.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from huggingface_hub import hf_hub_download
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer
5
+ from pptx import Presentation
6
+ from pptx.util import Inches, Pt
7
+ from pptx.enum.text import PP_ALIGN
8
+ from huggingface_hub import login
9
+ import torch
10
+
11
+ # Préprompt amélioré pour une meilleure structuration
12
+ PREPROMPT = """Vous êtes un assistant IA chargé de générer une présentation PowerPoint. Générez une présentation structurée en suivant ce format EXACT:
13
+
14
+ TITRE: [Titre principal de la présentation]
15
+ DIAPO 1:
16
+ Titre: [Titre de la diapo]
17
+ Points:
18
+ - Point 1
19
+ - Point 2
20
+ - Point 3
21
+ DIAPO 2:
22
+ Titre: [Titre de la diapo]
23
+ Points:
24
+ - Point 1
25
+ - Point 2
26
+ - Point 3
27
+ [Continuez avec ce format pour chaque diapositive]
28
+
29
+ Analysez le texte suivant et créez une présentation claire et professionnelle :"""
30
+
31
+ # Authentification HuggingFace
32
+ token = os.getenv('Authentification_HF')
33
+ login(token)
34
+ model_id = "mistralai/Mistral-Nemo-Instruct-2407"
35
+
36
+ # Initialisation du modèle avec des paramètres de contexte plus grands
37
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
38
+ model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16, device_map="auto")
39
+
40
+ def parse_presentation_content(content):
41
+ """Parse le contenu généré en sections pour les diapositives"""
42
+ slides = []
43
+ current_slide = None
44
+
45
+ for line in content.split('\n'):
46
+ line = line.strip()
47
+ if line.startswith('TITRE:'):
48
+ slides.append({'type': 'title', 'title': line[6:].strip()})
49
+ elif line.startswith('DIAPO'):
50
+ if current_slide:
51
+ slides.append(current_slide)
52
+ current_slide = {'type': 'content', 'title': '', 'points': []}
53
+ elif line.startswith('Titre:') and current_slide:
54
+ current_slide['title'] = line[6:].strip()
55
+ elif line.startswith('- ') and current_slide:
56
+ current_slide['points'].append(line[2:].strip())
57
+
58
+ if current_slide:
59
+ slides.append(current_slide)
60
+
61
+ return slides
62
+
63
+ def create_presentation(slides):
64
+ """Crée la présentation PowerPoint à partir des sections parsées"""
65
+ prs = Presentation()
66
+
67
+ # Première diapo (titre)
68
+ title_slide = prs.slides.add_slide(prs.slide_layouts[0])
69
+ title_slide.shapes.title.text = slides[0]['title']
70
+
71
+ # Autres diapos
72
+ for slide in slides[1:]:
73
+ content_slide = prs.slides.add_slide(prs.slide_layouts[1])
74
+ content_slide.shapes.title.text = slide['title']
75
+
76
+ if slide['points']:
77
+ body = content_slide.shapes.placeholders[1].text_frame
78
+ body.clear()
79
+ for point in slide['points']:
80
+ p = body.add_paragraph()
81
+ p.text = point
82
+ p.level = 0
83
+
84
+ return prs
85
+
86
+ def generate_content_and_pptx(text):
87
+ """Fonction en deux étapes : génération du contenu puis création du PPTX"""
88
+ # Ajout du préprompt au texte de l'utilisateur
89
+ full_prompt = PREPROMPT + "\n\n" + text
90
+
91
+ # Génération du contenu avec le modèle
92
+ inputs = tokenizer.apply_chat_template(
93
+ [{"role": "user", "content": full_prompt}],
94
+ return_tensors="pt",
95
+ return_dict=True
96
+ )
97
+
98
+ outputs = model.generate(
99
+ **inputs,
100
+ max_new_tokens=4096,
101
+ temperature=0.3
102
+ )
103
+
104
+ # Extraction du texte généré
105
+ generated_content = tokenizer.decode(outputs[0], skip_special_tokens=True)
106
+
107
+ # Parse le contenu et crée la présentation
108
+ slides = parse_presentation_content(generated_content)
109
+ prs = create_presentation(slides)
110
+
111
+ # Sauvegarde de la présentation
112
+ output_path = "presentation.pptx"
113
+ prs.save(output_path)
114
+
115
+ return generated_content, f"Présentation générée avec succès ! Vous pouvez la télécharger ici : {os.path.abspath(output_path)}"
116
+
117
+ # CSS personnalisé pour un thème sombre amélioré
118
+ css = """
119
+ /* Styles globaux */
120
+ .gradio-container {
121
+ background-color: #000000 !important;
122
+ }
123
+
124
+ /* Titre et description */
125
+ h1, h2, h3, p, label, .label-text {
126
+ color: #ffffff !important;
127
+ }
128
+
129
+ /* Zones de texte */
130
+ .gr-box, .gr-input, .gr-textarea, .gr-textbox, .gr-text-input {
131
+ background-color: #000000 !important;
132
+ border: 1px solid #666666 !important;
133
+ color: #ffffff !important;
134
+ }
135
+
136
+ /* Boutons */
137
+ .gr-button {
138
+ background-color: #333333 !important;
139
+ color: #ffffff !important;
140
+ border: 1px solid #666666 !important;
141
+ }
142
+
143
+ .gr-button:hover {
144
+ background-color: #444444 !important;
145
+ }
146
+
147
+ /* Progress bar et éléments de statut */
148
+ .gr-progress, .gr-status {
149
+ color: #ffffff !important;
150
+ background-color: #000000 !important;
151
+ }
152
+
153
+ /* Conteneurs et boîtes */
154
+ .gr-panel, .gr-box {
155
+ background-color: #000000 !important;
156
+ border: 1px solid #666666 !important;
157
+ }
158
+
159
+ /* Texte de placeholder */
160
+ ::placeholder {
161
+ color: #999999 !important;
162
+ }
163
+
164
+ /* Scrollbar personnalisée */
165
+ ::-webkit-scrollbar {
166
+ width: 10px;
167
+ background-color: #000000;
168
+ }
169
+
170
+ ::-webkit-scrollbar-thumb {
171
+ background-color: #666666;
172
+ border-radius: 5px;
173
+ }
174
+
175
+ ::-webkit-scrollbar-track {
176
+ background-color: #333333;
177
+ }
178
+ """
179
+
180
+ # Interface Gradio avec une zone de texte plus grande et thème sombre amélioré
181
+ with gr.Blocks(theme=gr.themes.Default(), css=css) as demo:
182
+ gr.Markdown(
183
+ """
184
+ # Générateur de Présentations PowerPoint
185
+
186
+ Entrez votre texte et obtenez une présentation PowerPoint générée automatiquement.
187
+ """
188
+ )
189
+
190
+ with gr.Row():
191
+ with gr.Column():
192
+ input_text = gr.Textbox(
193
+ lines=10,
194
+ label="Entrez votre texte",
195
+ placeholder="Décrivez le contenu que vous souhaitez pour votre présentation...",
196
+ )
197
+
198
+ with gr.Row():
199
+ generate_btn = gr.Button("Générer la présentation")
200
+
201
+ with gr.Row():
202
+ with gr.Column():
203
+ output_content = gr.Textbox(
204
+ label="Contenu généré par l'IA",
205
+ lines=10,
206
+ show_copy_button=True
207
+ )
208
+ output_status = gr.Textbox(
209
+ label="Statut de la génération"
210
+ )
211
+
212
+ generate_btn.click(
213
+ fn=generate_content_and_pptx,
214
+ inputs=input_text,
215
+ outputs=[output_content, output_status]
216
+ )
217
+
218
+ if __name__ == "__main__":
219
+ demo.launch()