DHEIVER commited on
Commit
947bfcc
·
verified ·
1 Parent(s): 2ec8f56

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -79
app.py CHANGED
@@ -2,10 +2,10 @@ import gradio as gr
2
  import torch
3
  from transformers import pipeline
4
 
5
- class LearningPathGenerator:
6
  def __init__(self):
7
  self.device = 0 if torch.cuda.is_available() else -1
8
- # Initialize models
9
  self.transcriber = pipeline("automatic-speech-recognition",
10
  model="openai/whisper-base",
11
  device=self.device)
@@ -13,162 +13,161 @@ class LearningPathGenerator:
13
  model="gpt2",
14
  device=self.device)
15
 
16
- def process_audio(self,
17
- audio_path: str,
18
- path_name: str,
19
- difficulty: str = "intermediate",
20
- include_resources: bool = True) -> tuple:
21
  try:
22
- # Transcribe audio
23
- transcription = self.transcriber(audio_path)["text"]
24
 
25
- # Generate learning path
26
  prompt = f"""
27
- Based on the following text, create a detailed learning path
28
- for {difficulty} level:
29
- {transcription}
30
 
31
- Learning path:
32
  """
33
 
34
- analysis = self.generator(prompt,
35
  max_length=300,
36
  num_return_sequences=1)[0]["generated_text"]
37
 
38
- if include_resources:
39
- resources = self._generate_resources()
40
- analysis += "\n\n" + resources
41
 
42
  return (
43
- gr.Textbox.update(value=transcription, visible=True),
44
- gr.Textbox.update(value=analysis, visible=True),
45
- gr.Markdown.update(visible=True, value="✅ Learning path generated successfully!"),
46
  gr.Button.update(interactive=True)
47
  )
48
  except Exception as e:
49
  return (
50
- gr.Textbox.update(value=f"Error: {str(e)}", visible=True),
51
- gr.Textbox.update(value="Could not generate analysis.", visible=True),
52
- gr.Markdown.update(visible=True, value="❌ An error occurred"),
53
  gr.Button.update(interactive=True)
54
  )
55
 
56
- def _generate_resources(self) -> str:
57
  return """
58
- 📚 Recommended Resources:
59
 
60
- 1. Books:
61
- - "Essential Guide"
62
- - "Advanced Techniques"
63
 
64
- 2. Online Courses:
65
- - Coursera: "Topic Specialization"
66
- - edX: "Advanced Course"
67
 
68
- 3. Practical Resources:
69
- - Interactive tutorials
70
- - Practice exercises
71
- - Real-world projects
72
  """
73
 
74
- def create_interface():
75
  with gr.Blocks(theme=gr.themes.Soft(
76
  primary_hue="blue",
77
  secondary_hue="purple",
78
  neutral_hue="gray"
79
  )) as app:
80
  gr.Markdown("""
81
- # 🎓 Learning Path Generator
82
 
83
- Upload an audio file describing your learning goals and receive a personalized learning path!
84
  """)
85
 
86
  with gr.Row():
87
  with gr.Column(scale=2):
88
- # Input components
89
  with gr.Group():
90
- gr.Markdown("### 📝 Input")
91
  audio_input = gr.Audio(
92
  type="filepath",
93
- label="Audio Input",
94
- description="Record or upload an audio describing your goals",
95
  sources=["microphone", "upload"],
96
  )
97
 
98
  with gr.Row():
99
- path_name = gr.Textbox(
100
- label="Path Name",
101
- placeholder="Give your learning path a name",
102
  scale=2
103
  )
104
- difficulty = gr.Dropdown(
105
- choices=["beginner", "intermediate", "advanced"],
106
- value="intermediate",
107
- label="Difficulty Level",
108
  scale=1
109
  )
110
 
111
- include_resources = gr.Checkbox(
112
- label="Include Recommended Resources",
113
  value=True,
114
- info="Add curated learning resources to your path"
115
  )
116
 
117
- process_btn = gr.Button(
118
- "🚀 Generate Learning Path",
119
  variant="primary",
120
  scale=2
121
  )
122
 
123
- # Output components
124
  with gr.Column(scale=2):
125
  with gr.Group():
126
- gr.Markdown("### 📊 Output")
127
  status = gr.Markdown(visible=False)
128
 
129
- with gr.Accordion("Audio Transcription", open=False):
130
- transcription = gr.Textbox(
131
- label="What we heard",
132
  lines=4,
133
  visible=False
134
  )
135
 
136
- analysis = gr.Textbox(
137
- label="Your Learning Path",
138
  lines=10,
139
  visible=False
140
  )
141
 
142
- # Event handlers
143
- process_btn.click(
144
- fn=LearningPathGenerator().process_audio,
145
- inputs=[audio_input, path_name, difficulty, include_resources],
146
- outputs=[transcription, analysis, status, process_btn],
147
- api_name="generate_path"
148
  )
149
 
150
- # Examples
151
  gr.Examples(
152
  examples=[
153
- ["path_audio.mp3", "Python Programming", "beginner", True],
154
- ["path_audio2.mp3", "Data Science", "intermediate", True],
155
  ],
156
- inputs=[audio_input, path_name, difficulty, include_resources],
157
- outputs=[transcription, analysis, status, process_btn],
158
  cache_examples=True,
159
  )
160
 
161
- # Add additional info
162
  gr.Markdown("""
163
- ### 📌 Tips
164
- - Speak clearly and describe your learning goals in detail
165
- - Mention any previous experience in the subject
166
- - Include any specific areas you want to focus on
167
  """)
168
 
169
  return app
170
 
171
  if __name__ == "__main__":
172
- app = create_interface()
173
  app.queue()
174
  app.launch()
 
2
  import torch
3
  from transformers import pipeline
4
 
5
+ class GeradorTrilhaAprendizado:
6
  def __init__(self):
7
  self.device = 0 if torch.cuda.is_available() else -1
8
+ # Inicializa modelos
9
  self.transcriber = pipeline("automatic-speech-recognition",
10
  model="openai/whisper-base",
11
  device=self.device)
 
13
  model="gpt2",
14
  device=self.device)
15
 
16
+ def processar_audio(self,
17
+ audio_path: str,
18
+ nome_trilha: str,
19
+ nivel: str = "intermediário",
20
+ incluir_recursos: bool = True) -> tuple:
21
  try:
22
+ # Transcrição do áudio
23
+ transcricao = self.transcriber(audio_path)["text"]
24
 
25
+ # Geração da trilha
26
  prompt = f"""
27
+ Com base no seguinte texto, crie uma trilha de aprendizado detalhada
28
+ para nível {nivel}:
29
+ {transcricao}
30
 
31
+ Trilha de aprendizado:
32
  """
33
 
34
+ analise = self.generator(prompt,
35
  max_length=300,
36
  num_return_sequences=1)[0]["generated_text"]
37
 
38
+ if incluir_recursos:
39
+ recursos = self._gerar_recursos()
40
+ analise += "\n\n" + recursos
41
 
42
  return (
43
+ gr.Textbox.update(value=transcricao, visible=True),
44
+ gr.Textbox.update(value=analise, visible=True),
45
+ gr.Markdown.update(visible=True, value="✅ Trilha gerada com sucesso!"),
46
  gr.Button.update(interactive=True)
47
  )
48
  except Exception as e:
49
  return (
50
+ gr.Textbox.update(value=f"Erro: {str(e)}", visible=True),
51
+ gr.Textbox.update(value="Não foi possível gerar a análise.", visible=True),
52
+ gr.Markdown.update(visible=True, value="❌ Ocorreu um erro"),
53
  gr.Button.update(interactive=True)
54
  )
55
 
56
+ def _gerar_recursos(self) -> str:
57
  return """
58
+ 📚 Recursos Recomendados:
59
 
60
+ 1. Livros:
61
+ - "Guia Essencial"
62
+ - "Técnicas Avançadas"
63
 
64
+ 2. Cursos Online:
65
+ - Coursera: "Especialização no Tema"
66
+ - edX: "Curso Avançado"
67
 
68
+ 3. Recursos Práticos:
69
+ - Tutoriais interativos
70
+ - Exercícios práticos
71
+ - Projetos do mundo real
72
  """
73
 
74
+ def criar_interface():
75
  with gr.Blocks(theme=gr.themes.Soft(
76
  primary_hue="blue",
77
  secondary_hue="purple",
78
  neutral_hue="gray"
79
  )) as app:
80
  gr.Markdown("""
81
+ # 🎓 Gerador de Trilha de Aprendizado
82
 
83
+ Grave ou faça upload de um áudio descrevendo seus objetivos e receba uma trilha personalizada!
84
  """)
85
 
86
  with gr.Row():
87
  with gr.Column(scale=2):
88
+ # Componentes de entrada
89
  with gr.Group():
90
+ gr.Markdown("### 📝 Entrada")
91
  audio_input = gr.Audio(
92
  type="filepath",
93
+ label="Áudio",
 
94
  sources=["microphone", "upload"],
95
  )
96
 
97
  with gr.Row():
98
+ nome_trilha = gr.Textbox(
99
+ label="Nome da Trilha",
100
+ placeholder=" um nome para sua trilha",
101
  scale=2
102
  )
103
+ nivel = gr.Dropdown(
104
+ choices=["iniciante", "intermediário", "avançado"],
105
+ value="intermediário",
106
+ label="Nível de Dificuldade",
107
  scale=1
108
  )
109
 
110
+ incluir_recursos = gr.Checkbox(
111
+ label="Incluir Recursos Recomendados",
112
  value=True,
113
+ info="Adicionar recursos de aprendizado curados à sua trilha"
114
  )
115
 
116
+ processar_btn = gr.Button(
117
+ "🚀 Gerar Trilha de Aprendizado",
118
  variant="primary",
119
  scale=2
120
  )
121
 
122
+ # Componentes de saída
123
  with gr.Column(scale=2):
124
  with gr.Group():
125
+ gr.Markdown("### 📊 Resultado")
126
  status = gr.Markdown(visible=False)
127
 
128
+ with gr.Accordion("Transcrição do Áudio", open=False):
129
+ transcricao = gr.Textbox(
130
+ label="O que entendemos",
131
  lines=4,
132
  visible=False
133
  )
134
 
135
+ analise = gr.Textbox(
136
+ label="Sua Trilha de Aprendizado",
137
  lines=10,
138
  visible=False
139
  )
140
 
141
+ # Manipuladores de eventos
142
+ processar_btn.click(
143
+ fn=GeradorTrilhaAprendizado().processar_audio,
144
+ inputs=[audio_input, nome_trilha, nivel, incluir_recursos],
145
+ outputs=[transcricao, analise, status, processar_btn],
146
+ api_name="gerar_trilha"
147
  )
148
 
149
+ # Exemplos
150
  gr.Examples(
151
  examples=[
152
+ ["audio_exemplo.mp3", "Programação Python", "iniciante", True],
153
+ ["audio_exemplo2.mp3", "Ciência de Dados", "intermediário", True],
154
  ],
155
+ inputs=[audio_input, nome_trilha, nivel, incluir_recursos],
156
+ outputs=[transcricao, analise, status, processar_btn],
157
  cache_examples=True,
158
  )
159
 
160
+ # Informações adicionais
161
  gr.Markdown("""
162
+ ### 📌 Dicas
163
+ - Fale claramente e descreva seus objetivos de aprendizado em detalhes
164
+ - Mencione qualquer experiência prévia no assunto
165
+ - Inclua áreas específicas em que deseja focar
166
  """)
167
 
168
  return app
169
 
170
  if __name__ == "__main__":
171
+ app = criar_interface()
172
  app.queue()
173
  app.launch()