JairoCesar commited on
Commit
2b54235
·
verified ·
1 Parent(s): 3a1cc37

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -18
app.py CHANGED
@@ -1,6 +1,8 @@
1
  import streamlit as st
2
  from pptx import Presentation
3
  from pptx.util import Inches, Pt
 
 
4
  import io
5
  from huggingface_hub import InferenceClient
6
  import json
@@ -11,21 +13,24 @@ def get_inference_client():
11
  return InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
12
 
13
  def extract_and_clean_json(text):
14
- # Intenta encontrar un JSON válido en el texto
15
  json_match = re.search(r'\{.*\}', text, re.DOTALL)
16
  if json_match:
17
  json_str = json_match.group()
18
- # Limpia el JSON de caracteres no válidos
19
  json_str = re.sub(r'[\n\t\r]', '', json_str)
20
- # Intenta corregir problemas comunes de formato
21
- json_str = re.sub(r',\s*}', '}', json_str) # Elimina comas finales extras
22
- json_str = re.sub(r',\s*]', ']', json_str) # Elimina comas finales extras en arrays
23
  return json_str
24
  return None
25
 
26
  def generate_presentation_content(topic, client):
27
  prompt = f"""Crea una presentación de PowerPoint sobre el tema: {topic}.
28
- Genera exactamente 5 diapositivas. Cada diapositiva debe tener un título y contenido.
 
 
 
 
 
 
29
  Formatea la salida como un JSON con la siguiente estructura:
30
  {{
31
  "slides": [
@@ -38,16 +43,16 @@ def generate_presentation_content(topic, client):
38
  No incluyas saltos de línea o caracteres especiales dentro del JSON.
39
  """
40
 
41
- response = client.text_generation(prompt, max_new_tokens=1500, temperature=0.7)
42
 
43
  try:
44
  json_str = extract_and_clean_json(response)
45
  if json_str:
46
  slides_data = json.loads(json_str)
47
- if 'slides' in slides_data and len(slides_data['slides']) == 5:
48
  return slides_data['slides']
49
  else:
50
- raise ValueError("El JSON no contiene exactamente 5 diapositivas")
51
  else:
52
  raise ValueError("No se encontró un JSON válido en la respuesta")
53
  except json.JSONDecodeError as e:
@@ -63,17 +68,74 @@ def generate_presentation_content(topic, client):
63
  st.code(response)
64
  return None
65
 
66
- def create_powerpoint(slides):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  prs = Presentation()
68
 
69
- for slide_data in slides:
 
 
 
 
 
 
 
 
70
  slide = prs.slides.add_slide(prs.slide_layouts[1])
71
-
72
- title_shape = slide.shapes.title
73
- content_shape = slide.placeholders[1]
74
-
75
- title_shape.text = slide_data['title']
76
- content_shape.text = slide_data['content']
 
 
 
 
 
77
 
78
  pptx_buffer = io.BytesIO()
79
  prs.save(pptx_buffer)
@@ -88,6 +150,11 @@ def main():
88
 
89
  topic = st.text_input("Por favor, ingrese el tema de la presentación:")
90
 
 
 
 
 
 
91
  if st.button("Generar Presentación"):
92
  if topic:
93
  try:
@@ -96,7 +163,7 @@ def main():
96
 
97
  if slides:
98
  with st.spinner("Creando archivo PowerPoint..."):
99
- pptx_buffer = create_powerpoint(slides)
100
 
101
  st.success("Presentación generada con éxito!")
102
 
 
1
  import streamlit as st
2
  from pptx import Presentation
3
  from pptx.util import Inches, Pt
4
+ from pptx.enum.shapes import MSO_SHAPE
5
+ from pptx.dml.color import RGBColor
6
  import io
7
  from huggingface_hub import InferenceClient
8
  import json
 
13
  return InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
14
 
15
  def extract_and_clean_json(text):
 
16
  json_match = re.search(r'\{.*\}', text, re.DOTALL)
17
  if json_match:
18
  json_str = json_match.group()
 
19
  json_str = re.sub(r'[\n\t\r]', '', json_str)
20
+ json_str = re.sub(r',\s*}', '}', json_str)
21
+ json_str = re.sub(r',\s*]', ']', json_str)
 
22
  return json_str
23
  return None
24
 
25
  def generate_presentation_content(topic, client):
26
  prompt = f"""Crea una presentación de PowerPoint sobre el tema: {topic}.
27
+ Genera exactamente 8 diapositivas con la siguiente estructura:
28
+ 1. Título de la presentación
29
+ 2. Introducción
30
+ 3. Índice
31
+ 4-7. Contenido principal (4 diapositivas)
32
+ 8. Conclusiones
33
+
34
  Formatea la salida como un JSON con la siguiente estructura:
35
  {{
36
  "slides": [
 
43
  No incluyas saltos de línea o caracteres especiales dentro del JSON.
44
  """
45
 
46
+ response = client.text_generation(prompt, max_new_tokens=2000, temperature=0.7)
47
 
48
  try:
49
  json_str = extract_and_clean_json(response)
50
  if json_str:
51
  slides_data = json.loads(json_str)
52
+ if 'slides' in slides_data and len(slides_data['slides']) == 8:
53
  return slides_data['slides']
54
  else:
55
+ raise ValueError("El JSON no contiene exactamente 8 diapositivas")
56
  else:
57
  raise ValueError("No se encontró un JSON válido en la respuesta")
58
  except json.JSONDecodeError as e:
 
68
  st.code(response)
69
  return None
70
 
71
+ def apply_design(prs, design):
72
+ if design == "Moderno":
73
+ background = prs.slides[0].background
74
+ fill = background.fill
75
+ fill.solid()
76
+ fill.fore_color.rgb = RGBColor(240, 240, 240)
77
+
78
+ for slide in prs.slides:
79
+ for shape in slide.shapes:
80
+ if shape.has_text_frame:
81
+ tf = shape.text_frame
82
+ tf.text = tf.text
83
+ for paragraph in tf.paragraphs:
84
+ paragraph.font.color.rgb = RGBColor(0, 0, 0)
85
+ if shape.name == 'Title':
86
+ paragraph.font.size = Pt(44)
87
+ else:
88
+ paragraph.font.size = Pt(24)
89
+ elif design == "Corporativo":
90
+ background = prs.slides[0].background
91
+ fill = background.fill
92
+ fill.solid()
93
+ fill.fore_color.rgb = RGBColor(255, 255, 255)
94
+
95
+ for slide in prs.slides:
96
+ left = top = Inches(0.5)
97
+ width = Inches(1)
98
+ height = Inches(0.5)
99
+ shape = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, left, top, width, height)
100
+ shape.fill.solid()
101
+ shape.fill.fore_color.rgb = RGBColor(0, 112, 192)
102
+
103
+ for shape in slide.shapes:
104
+ if shape.has_text_frame:
105
+ tf = shape.text_frame
106
+ tf.text = tf.text
107
+ for paragraph in tf.paragraphs:
108
+ paragraph.font.color.rgb = RGBColor(0, 0, 0)
109
+ if shape.name == 'Title':
110
+ paragraph.font.size = Pt(40)
111
+ paragraph.font.color.rgb = RGBColor(0, 112, 192)
112
+ else:
113
+ paragraph.font.size = Pt(20)
114
+
115
+ def create_powerpoint(slides, design):
116
  prs = Presentation()
117
 
118
+ # Diapositiva de título
119
+ slide = prs.slides.add_slide(prs.slide_layouts[0])
120
+ title = slide.shapes.title
121
+ subtitle = slide.placeholders[1]
122
+ title.text = slides[0]['title']
123
+ subtitle.text = slides[0]['content']
124
+
125
+ # Otras diapositivas
126
+ for slide_data in slides[1:]:
127
  slide = prs.slides.add_slide(prs.slide_layouts[1])
128
+ title = slide.shapes.title
129
+ content = slide.placeholders[1]
130
+ title.text = slide_data['title']
131
+ content.text = slide_data['content']
132
+
133
+ # Diapositiva "Gracias"
134
+ slide = prs.slides.add_slide(prs.slide_layouts[0])
135
+ title = slide.shapes.title
136
+ title.text = "¡Gracias!"
137
+
138
+ apply_design(prs, design)
139
 
140
  pptx_buffer = io.BytesIO()
141
  prs.save(pptx_buffer)
 
150
 
151
  topic = st.text_input("Por favor, ingrese el tema de la presentación:")
152
 
153
+ design = st.selectbox(
154
+ "Seleccione un diseño para la presentación:",
155
+ ("Simple", "Moderno", "Corporativo")
156
+ )
157
+
158
  if st.button("Generar Presentación"):
159
  if topic:
160
  try:
 
163
 
164
  if slides:
165
  with st.spinner("Creando archivo PowerPoint..."):
166
+ pptx_buffer = create_powerpoint(slides, design)
167
 
168
  st.success("Presentación generada con éxito!")
169