amauricunha commited on
Commit
bac0d9d
·
verified ·
1 Parent(s): daa0f70

Update flask_app.py

Browse files
Files changed (1) hide show
  1. flask_app.py +45 -9
flask_app.py CHANGED
@@ -36,13 +36,15 @@ from admin_module import admin_manager, admin_required
36
  if 'app' not in globals():
37
  app = Flask(__name__)
38
 
39
- # Configuration for sessions
40
  app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'dev-key-change-in-production-hf-spaces')
41
  app.config['SESSION_TYPE'] = 'filesystem'
42
- app.config['SESSION_PERMANENT'] = False
43
  app.config['SESSION_USE_SIGNER'] = True
44
  app.config['SESSION_KEY_PREFIX'] = 'englishhelper:'
45
  app.config['PERMANENT_SESSION_LIFETIME'] = 86400 # 24 hours
 
 
46
 
47
  # Configuração para HF Spaces
48
  app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 # Evitar cache de arquivos
@@ -59,10 +61,18 @@ else:
59
 
60
  # Ensure flask_session directory exists
61
  import os
62
- session_dir = 'flask_session'
63
  if not os.path.exists(session_dir):
64
- os.makedirs(session_dir)
65
- print(f"Created session directory: {session_dir}")
 
 
 
 
 
 
 
 
66
 
67
  # Database initialization (handled by app.py)
68
  def initialize_database():
@@ -148,6 +158,9 @@ def list_models():
148
 
149
  # --- ROTAS PRINCIPAIS ---
150
 
 
 
 
151
  @app.route('/tts-proxy', methods=['POST'])
152
  def tts_proxy():
153
  data = request.get_json()
@@ -159,18 +172,41 @@ def tts_proxy():
159
  if len(text) > 10000:
160
  return jsonify({"error": "Text is too long. Maximum 10,000 characters allowed."}), 400
161
 
 
 
 
 
162
  try:
163
- # Log para debug
164
- print(f"TTS request: {len(text)} characters, tld: {tld}")
 
 
 
 
 
 
 
165
 
166
  tts = gTTS(text=text, lang='en', tld=tld)
167
  mp3_fp = io.BytesIO()
168
  tts.write_to_fp(mp3_fp)
169
  mp3_fp.seek(0)
170
 
171
- return send_file(mp3_fp, mimetype='audio/mpeg')
 
 
 
 
 
 
 
 
 
 
 
 
172
  except Exception as e:
173
- print(f"TTS Error: {e}")
174
  return jsonify({"error": f"Failed to generate audio via gTTS: {e}"}), 500
175
 
176
  # Primeira função explain_proxy removida - duplicata
 
36
  if 'app' not in globals():
37
  app = Flask(__name__)
38
 
39
+ # Configuration for sessions - Otimizado para HF Spaces
40
  app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'dev-key-change-in-production-hf-spaces')
41
  app.config['SESSION_TYPE'] = 'filesystem'
42
+ app.config['SESSION_PERMANENT'] = True # Mudança para True
43
  app.config['SESSION_USE_SIGNER'] = True
44
  app.config['SESSION_KEY_PREFIX'] = 'englishhelper:'
45
  app.config['PERMANENT_SESSION_LIFETIME'] = 86400 # 24 hours
46
+ app.config['SESSION_FILE_DIR'] = '/tmp/flask-session' # Diretório específico
47
+ app.config['SESSION_FILE_THRESHOLD'] = 500 # Max arquivos de sessão
48
 
49
  # Configuração para HF Spaces
50
  app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 # Evitar cache de arquivos
 
61
 
62
  # Ensure flask_session directory exists
63
  import os
64
+ session_dir = '/tmp/flask-session'
65
  if not os.path.exists(session_dir):
66
+ os.makedirs(session_dir, exist_ok=True)
67
+ print(f"Created session directory: {session_dir}")
68
+
69
+ # Adicionar middleware para debug de sessão
70
+ @app.before_request
71
+ def debug_session():
72
+ if request.endpoint and 'admin' in request.endpoint:
73
+ print(f"🔍 Session Debug - Endpoint: {request.endpoint}")
74
+ print(f"🔍 Session Data: {dict(session)}")
75
+ print(f"🔍 Session ID: {request.cookies.get('session', 'no-session')}")
76
 
77
  # Database initialization (handled by app.py)
78
  def initialize_database():
 
158
 
159
  # --- ROTAS PRINCIPAIS ---
160
 
161
+ # Cache de áudio TTS em memória
162
+ tts_cache = {}
163
+
164
  @app.route('/tts-proxy', methods=['POST'])
165
  def tts_proxy():
166
  data = request.get_json()
 
172
  if len(text) > 10000:
173
  return jsonify({"error": "Text is too long. Maximum 10,000 characters allowed."}), 400
174
 
175
+ # Criar chave de cache baseada no texto e TLD
176
+ import hashlib
177
+ cache_key = hashlib.md5(f"{text}_{tld}".encode()).hexdigest()
178
+
179
  try:
180
+ # Verificar se está no cache
181
+ if cache_key in tts_cache:
182
+ print(f"🎵 TTS Cache HIT: {len(text)} chars")
183
+ cached_audio = tts_cache[cache_key]
184
+ audio_fp = io.BytesIO(cached_audio)
185
+ return send_file(audio_fp, mimetype='audio/mpeg', as_attachment=False)
186
+
187
+ # Gerar novo áudio
188
+ print(f"🎵 TTS Cache MISS: Gerando áudio para {len(text)} chars, tld: {tld}")
189
 
190
  tts = gTTS(text=text, lang='en', tld=tld)
191
  mp3_fp = io.BytesIO()
192
  tts.write_to_fp(mp3_fp)
193
  mp3_fp.seek(0)
194
 
195
+ # Salvar no cache
196
+ audio_data = mp3_fp.read()
197
+ tts_cache[cache_key] = audio_data
198
+
199
+ # Limitar cache a 50 entradas
200
+ if len(tts_cache) > 50:
201
+ oldest_key = next(iter(tts_cache))
202
+ del tts_cache[oldest_key]
203
+
204
+ # Retornar áudio
205
+ audio_fp = io.BytesIO(audio_data)
206
+ return send_file(audio_fp, mimetype='audio/mpeg', as_attachment=False)
207
+
208
  except Exception as e:
209
+ print(f"TTS Error: {e}")
210
  return jsonify({"error": f"Failed to generate audio via gTTS: {e}"}), 500
211
 
212
  # Primeira função explain_proxy removida - duplicata