souzafcb commited on
Commit
fb584e7
·
verified ·
1 Parent(s): 44dbb52

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +119 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,121 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import whisper
3
+ import tempfile
4
+ from pathlib import Path
5
+ import torch
6
 
7
+
8
+ def format_timestamp(seconds: float) -> str:
9
+ """Converte segundos em timestamp HH:MM:SS.mmm para legenda."""
10
+ ms = int((seconds - int(seconds)) * 1000)
11
+ seconds = int(seconds)
12
+ s = seconds % 60
13
+ minutes = (seconds // 60) % 60
14
+ hours = seconds // 3600
15
+ return f"{hours:02d}:{minutes:02d}:{s:02d}.{ms:03d}"
16
+
17
+
18
+ def segments_to_vtt(segments) -> str:
19
+ """Converte segments do Whisper em arquivo WEBVTT."""
20
+ lines = ["WEBVTT", ""]
21
+ for idx, seg in enumerate(segments, start=1):
22
+ start = format_timestamp(seg["start"])
23
+ end = format_timestamp(seg["end"])
24
+ text = seg["text"].strip()
25
+ lines.append(f"{idx}")
26
+ lines.append(f"{start} --> {end}")
27
+ lines.append(text)
28
+ lines.append("")
29
+ return "\n".join(lines)
30
+
31
+
32
+ # Configuração básica da página
33
+ st.set_page_config(
34
+ page_title="FFKeiro – Áudio → Texto",
35
+ page_icon="🎧",
36
+ layout="centered",
37
+ )
38
+
39
+ st.title("🎧 FFKeiro – Conversor de Áudio para Texto")
40
+ st.write(
41
+ "Envie um arquivo de áudio para gerar a transcrição em **texto** "
42
+ "e uma legenda sincronizada em **WEBVTT (.vtt)**."
43
+ )
44
+
45
+ # Sidebar com opções
46
+ model_size = st.sidebar.selectbox(
47
+ "Modelo Whisper",
48
+ options=["tiny", "base", "small", "medium", "large"],
49
+ index=2, # "small" como padrão
50
+ help="Modelos menores são mais rápidos; modelos maiores tendem a ter melhor qualidade.",
51
+ )
52
+
53
+ language = st.sidebar.text_input(
54
+ "Idioma (código ISO)",
55
+ value="pt",
56
+ help='Ex.: "pt" para português, "en" para inglês, etc.',
57
+ )
58
+
59
+ device = "cuda" if torch.cuda.is_available() else "cpu"
60
+ st.sidebar.write(f"Device detectado: **{device}**")
61
+
62
+ # Upload de áudio
63
+ uploaded_file = st.file_uploader(
64
+ "Envie o arquivo de áudio",
65
+ type=["wav", "mp3", "m4a", "ogg", "flac"],
66
+ )
67
+
68
+ if uploaded_file is not None:
69
+ st.audio(uploaded_file)
70
+ st.write("Arquivo recebido:", uploaded_file.name)
71
+
72
+ if st.button("🔁 Transcrever áudio"):
73
+ with st.spinner("Carregando modelo Whisper e transcrevendo..."):
74
+ # Carrega o modelo
75
+ model = whisper.load_model(model_size, device=device)
76
+
77
+ # Salva o arquivo enviado em um temp file
78
+ with tempfile.NamedTemporaryFile(
79
+ delete=False,
80
+ suffix=Path(uploaded_file.name).suffix,
81
+ ) as tmp:
82
+ tmp.write(uploaded_file.read())
83
+ tmp_path = tmp.name
84
+
85
+ # Transcreve
86
+ result = model.transcribe(tmp_path, language=language)
87
+ text = result.get("text", "").strip()
88
+ segments = result.get("segments", [])
89
+
90
+ if not text:
91
+ st.error("Não foi possível obter transcrição.")
92
+ else:
93
+ st.success("Transcrição concluída!")
94
+
95
+ # Mostra texto
96
+ st.subheader("📝 Transcrição (Texto)")
97
+ st.text_area("Texto completo", value=text, height=250)
98
+
99
+ # Gera arquivos para download
100
+ txt_bytes = text.encode("utf-8")
101
+ vtt_content = segments_to_vtt(segments) if segments else ""
102
+ vtt_bytes = vtt_content.encode("utf-8") if vtt_content else b""
103
+
104
+ col1, col2 = st.columns(2)
105
+ with col1:
106
+ st.download_button(
107
+ label="⬇️ Baixar TXT",
108
+ data=txt_bytes,
109
+ file_name=Path(uploaded_file.name).stem + ".txt",
110
+ mime="text/plain",
111
+ )
112
+ with col2:
113
+ if vtt_bytes:
114
+ st.download_button(
115
+ label="⬇️ Baixar legenda VTT",
116
+ data=vtt_bytes,
117
+ file_name=Path(uploaded_file.name).stem + ".vtt",
118
+ mime="text/vtt",
119
+ )
120
+ else:
121
+ st.info("Legenda VTT não disponível.")