-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbackend.py
More file actions
6713 lines (5740 loc) · 307 KB
/
backend.py
File metadata and controls
6713 lines (5740 loc) · 307 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, request, jsonify, Response, send_file
from flask_cors import CORS
import os
import io
import zipfile
import re
import requests
import json
import time
from dotenv import load_dotenv
import tempfile
import base64
import re
from datetime import datetime
import shutil
from markdownify import markdownify
from bs4 import BeautifulSoup
from whisper_cpp_wrapper import WhisperCppWrapper
from sensevoice_wrapper import get_sensevoice_wrapper
# Optional import for speaker diarization
try:
from speaker_diarization import get_speaker_diarization_wrapper
SPEAKER_DIARIZATION_AVAILABLE = True
except ImportError as e:
print(f"Warning: Speaker diarization not available: {e}")
SPEAKER_DIARIZATION_AVAILABLE = False
def get_speaker_diarization_wrapper():
return None
try:
from mermaid import Mermaid
except Exception as e: # noqa: F401
print(f"Warning: Mermaid diagrams not available: {e}")
class Mermaid:
def __init__(self, *args, **kwargs):
pass
def add(self, *args, **kwargs):
pass
from concept_graph import build_graph, build_concept_graph
import ast
import string
from pydub import AudioSegment
def extract_json(text: str):
"""Try to extract and parse a JSON object from raw text."""
if not text:
return None
# Remove common code block delimiters
text = text.strip()
if text.startswith('```'):
text = re.sub(r'^```(?:json)?', '', text)
text = re.sub(r'```$', '', text)
# Find the first JSON object in the string
match = re.search(r'{.*}', text, re.DOTALL)
if match:
text = match.group(0)
try:
return json.loads(text)
except Exception:
pass
fixed = re.sub(r",\s*([}\]])", r"\1", text)
fixed = fixed.replace("'", '"')
try:
return json.loads(fixed)
except Exception:
try:
return ast.literal_eval(text)
except Exception:
return None
import threading
# ---------- Path utilities ----------
def sanitize_filename(filename: str) -> str:
"""Return the base name of a filename, removing any path components."""
return os.path.basename(filename)
def is_path_within_directory(base_dir: str, path: str) -> bool:
"""Check that the absolute path resides within the base directory."""
abs_base = os.path.abspath(base_dir)
abs_path = os.path.abspath(path)
try:
return os.path.commonpath([abs_path, abs_base]) == abs_base
except ValueError:
return False
# Cargar variables de entorno
load_dotenv()
app = Flask(__name__)
# Allow uploads up to 4GB for large whisper.cpp models
app.config['MAX_CONTENT_LENGTH'] = 4 * 1024 * 1024 * 1024 # 4GB
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 # Disable caching for development
# Configurar CORS para permitir acceso desde el frontend
cors_origins = os.getenv('CORS_ORIGINS', 'http://localhost:3000,http://127.0.0.1:3000,https://localhost:5037').split(',')
CORS(app, origins=cors_origins)
# Configuración de APIs
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')
DEEPSEEK_API_KEY = os.getenv('DEEPSEEK_API_KEY')
OPENROUTER_API_KEY = os.getenv('OPENROUTER_API_KEY')
GROQ_API_KEY = os.getenv('GROQ_API_KEY')
LMSTUDIO_HOST = os.getenv('LMSTUDIO_HOST', '127.0.0.1')
LMSTUDIO_PORT = os.getenv('LMSTUDIO_PORT', '1234')
OLLAMA_HOST = os.getenv('OLLAMA_HOST', '127.0.0.1')
OLLAMA_PORT = os.getenv('OLLAMA_PORT', '11434')
# Enable or disable multi-user support (default True)
MULTI_USER = os.getenv('MULTI_USER', 'true').lower() != 'false'
def load_server_config():
"""Load host/port settings from database if available."""
global LMSTUDIO_HOST, LMSTUDIO_PORT, OLLAMA_HOST, OLLAMA_PORT
try:
from db import get_setting
LMSTUDIO_HOST = get_setting('lmstudio_host', LMSTUDIO_HOST)
LMSTUDIO_PORT = get_setting('lmstudio_port', LMSTUDIO_PORT)
OLLAMA_HOST = get_setting('ollama_host', OLLAMA_HOST)
OLLAMA_PORT = get_setting('ollama_port', OLLAMA_PORT)
except Exception:
# If database is not available or settings don't exist, use defaults
pass
def save_server_config():
"""Persist current host/port settings to database."""
try:
from db import set_setting
set_setting('lmstudio_host', LMSTUDIO_HOST)
set_setting('lmstudio_port', LMSTUDIO_PORT)
set_setting('ollama_host', OLLAMA_HOST)
set_setting('ollama_port', OLLAMA_PORT)
except Exception as e:
print(f"Error saving server config to database: {e}")
raise
# Load persisted config if present
load_server_config()
# Opcional: enviar las notas guardadas a un flujo de trabajo externo
WORKFLOW_WEBHOOK_URL = os.getenv('WORKFLOW_WEBHOOK_URL')
WORKFLOW_WEBHOOK_TOKEN = os.getenv('WORKFLOW_WEBHOOK_TOKEN')
WORKFLOW_WEBHOOK_USER = os.getenv('WORKFLOW_WEBHOOK_USER')
# ---------- User management with PostgreSQL ---------
SAVE_LOCK = threading.Lock()
SESSIONS = {}
ALL_TRANSCRIPTION_PROVIDERS = ["openai", "local", "sensevoice"]
ALL_POSTPROCESS_PROVIDERS = ["openai", "google", "openrouter", "lmstudio", "ollama", "groq"]
OPENROUTER_FREE_MODELS = [
"google/gemma-3-27b-it:free",
"google/gemini-2.0-flash-exp:free",
"meta-llama/llama-4-maverick:free",
"meta-llama/llama-4-scout:free",
"deepseek/deepseek-chat-v3-0324:free",
"qwen/qwen3-32b:free",
"mistralai/mistral-small-3.1-24b-instruct:free",
"moonshotai/kimi-k2:free",
]
# Paid models include all non-free variants of the above plus
# additional explicitly paid-only models.
OPENROUTER_PAID_MODELS = [model.replace(":free", "") for model in OPENROUTER_FREE_MODELS] + [
"openai/gpt-oss-20b",
"openai/gpt-oss-120b",
]
def user_allows_openrouter_paid_models(username: str) -> bool:
"""Check user config to see if paid OpenRouter models are allowed."""
try:
user_dir = os.path.join('user_data', username)
config_file = os.path.join(user_dir, 'config.json')
if os.path.exists(config_file):
with open(config_file, 'r', encoding='utf-8') as f:
cfg = json.load(f)
return cfg.get('showOpenRouterPaidModels', False)
except Exception:
pass
return False
from argon2 import PasswordHasher, exceptions as argon2_exceptions
from argon2.low_level import Type
from db import (
init_db,
migrate_json,
migrate_server_config_to_db,
get_user,
list_users as db_list_users,
create_user as db_create_user,
update_password as db_update_password,
update_user_providers as db_update_user_providers,
delete_user as db_delete_user,
get_user_preference,
set_user_preference,
get_user_preferences,
)
HASHER = PasswordHasher(time_cost=2, memory_cost=65536, parallelism=2, hash_len=32, type=Type.ID)
init_db()
migrate_json(hasher=HASHER)
migrate_server_config_to_db() # Migrate server config from JSON to database
# Load server configuration from database
load_server_config()
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD")
if not ADMIN_PASSWORD:
raise RuntimeError("ADMIN_PASSWORD environment variable not set")
def ensure_admin_user():
admin_user = get_user('admin')
expected_password_hash = HASHER.hash(ADMIN_PASSWORD)
if not admin_user:
# Create admin user if it doesn't exist
db_create_user(
'admin',
expected_password_hash,
True,
ALL_TRANSCRIPTION_PROVIDERS,
ALL_POSTPROCESS_PROVIDERS,
)
else:
# Update admin password if it's different from the expected one
try:
HASHER.verify(admin_user['password'], ADMIN_PASSWORD)
# Password is correct, no need to update
except argon2_exceptions.VerifyMismatchError:
# Password is different, update it
print("Updating admin password to match ADMIN_PASSWORD environment variable")
db_update_password('admin', expected_password_hash)
ensure_admin_user()
def get_user_providers(username):
user = get_user(username)
if not user:
return [], []
if username == 'admin':
return ALL_TRANSCRIPTION_PROVIDERS, ALL_POSTPROCESS_PROVIDERS
return user.get('transcription_providers', []), user.get('postprocess_providers', [])
def migrate_notes_to_admin_folder():
"""Move existing notes in saved_notes/ to saved_notes/admin"""
root_dir = os.path.join(os.getcwd(), 'saved_notes')
if not os.path.isdir(root_dir):
return
admin_dir = os.path.join(root_dir, 'admin')
moved = 0
for fname in os.listdir(root_dir):
path = os.path.join(root_dir, fname)
if os.path.isfile(path) and (fname.endswith('.md') or fname.endswith('.meta')):
os.makedirs(admin_dir, exist_ok=True)
shutil.move(path, os.path.join(admin_dir, fname))
moved += 1
if moved:
print(f"Migrated {moved} notes to {admin_dir}")
def parse_note_id_from_md(path):
"""Try to extract a note ID from the markdown file"""
try:
with open(path, 'r', encoding='utf-8') as f:
content = f.read()
match = re.search(r"\*Nota ID:\s*(\d+)\*", content)
if not match:
match = re.search(r"\*Note ID:\s*(\d+)\*", content)
if match:
return match.group(1)
except Exception:
pass
return None
def generate_note_id_from_filename(filename: str) -> str:
"""Return a stable note ID derived from the filename"""
base = os.path.splitext(os.path.basename(filename))[0]
return re.sub(r"[^a-zA-Z0-9]+", "-", base).strip("-").lower()
def create_missing_meta_files():
"""Ensure every note has a corresponding .meta file with an ID"""
root_dir = os.path.join(os.getcwd(), 'saved_notes')
if not os.path.isdir(root_dir):
return 0
created = 0
for user in os.listdir(root_dir):
user_dir = os.path.join(root_dir, user)
if not os.path.isdir(user_dir):
continue
for fname in os.listdir(user_dir):
if not fname.endswith('.md'):
continue
md_path = os.path.join(user_dir, fname)
meta_path = f"{md_path}.meta"
if os.path.exists(meta_path):
continue
note_id = parse_note_id_from_md(md_path)
if not note_id:
note_id = generate_note_id_from_filename(fname)
stat = os.stat(md_path)
metadata = {
"id": note_id,
"title": os.path.splitext(fname)[0],
"updated": datetime.fromtimestamp(stat.st_mtime).isoformat(),
"tags": []
}
try:
with open(meta_path, 'w', encoding='utf-8') as mf:
json.dump(metadata, mf, ensure_ascii=False, indent=2)
created += 1
except Exception as e:
print(f"Error creating meta for {md_path}: {e}")
if created:
print(f"Created {created} metadata files")
return created
migrate_notes_to_admin_folder()
create_missing_meta_files()
def get_current_username():
if not MULTI_USER:
return 'admin'
token = request.headers.get('Authorization')
if not token:
return None
return SESSIONS.get(token)
# Inicializar el wrapper de whisper.cpp local
try:
whisper_wrapper = WhisperCppWrapper()
WHISPER_CPP_AVAILABLE = whisper_wrapper.is_ready()
print(f"Whisper.cpp local available: {WHISPER_CPP_AVAILABLE}")
except Exception as e:
print(f"Error initializing whisper.cpp: {e}")
WHISPER_CPP_AVAILABLE = False
whisper_wrapper = None
# Inicializar el wrapper de SenseVoice
try:
sensevoice_wrapper = get_sensevoice_wrapper()
print("SenseVoice wrapper initialized")
# Check initial availability (for logging purposes)
initial_sensevoice_available = sensevoice_wrapper.is_available()
print(f"SenseVoice initially available: {initial_sensevoice_available}")
# Note: We'll check availability dynamically instead of caching it
except Exception as e:
print(f"Error initializing SenseVoice wrapper: {e}")
sensevoice_wrapper = None
@app.route('/health', methods=['GET'])
def health_check():
"""Endpoint para verificar que el backend está funcionando"""
return jsonify({"status": "ok", "message": "Backend funcionando correctamente"})
# --- Authentication and user management endpoints ---
@app.route('/api/login', methods=['POST'])
def login_user():
data = request.get_json() or {}
username = data.get('username')
password = data.get('password')
user = get_user(username)
if not user:
return jsonify({"success": False}), 401
try:
HASHER.verify(user['password'], password)
except argon2_exceptions.VerifyMismatchError:
return jsonify({"success": False}), 401
if HASHER.check_needs_rehash(user['password']):
db_update_password(username, HASHER.hash(password))
token = base64.urlsafe_b64encode(os.urandom(24)).decode('utf-8')
SESSIONS[token] = username
tp, pp = get_user_providers(username)
return jsonify({
"success": True,
"token": token,
"is_admin": user.get('is_admin', False),
"transcription_providers": tp,
"postprocess_providers": pp,
})
@app.route('/api/logout', methods=['POST'])
def logout_user():
token = request.headers.get('Authorization')
if token in SESSIONS:
SESSIONS.pop(token, None)
return jsonify({"success": True})
@app.route('/api/session-info', methods=['GET'])
def session_info():
"""Return information about the current session if the token is valid"""
if not MULTI_USER:
username = 'admin'
else:
token = request.headers.get('Authorization')
username = SESSIONS.get(token)
if not username:
return jsonify({"authenticated": False}), 401
user = get_user(username) or {}
tp, pp = get_user_providers(username)
return jsonify({
"authenticated": True,
"username": username,
"is_admin": user.get('is_admin', False),
"transcription_providers": tp,
"postprocess_providers": pp,
})
@app.route('/api/change-password', methods=['POST'])
def change_password():
username = get_current_username()
if not username:
return jsonify({"error": "Unauthorized"}), 401
data = request.get_json() or {}
current = data.get('current_password')
new_password = data.get('new_password')
if not current or not new_password:
return jsonify({"error": "Password required"}), 400
user = get_user(username)
if not user:
return jsonify({"error": "User not found"}), 404
try:
HASHER.verify(user['password'], current)
except argon2_exceptions.VerifyMismatchError:
return jsonify({"error": "Current password incorrect"}), 400
new_hash = HASHER.hash(new_password)
db_update_password(username, new_hash)
return jsonify({"success": True})
@app.route('/api/create-user', methods=['POST'])
def create_user():
admin = get_current_username()
admin_info = get_user(admin)
if not admin or not admin_info or not admin_info.get('is_admin'):
return jsonify({"error": "Unauthorized"}), 401
data = request.get_json() or {}
username = data.get('username')
password = data.get('password')
if not username or not password:
return jsonify({"error": "Username and password required"}), 400
if get_user(username) or username == 'admin':
return jsonify({"error": "User exists"}), 400
db_create_user(
username,
HASHER.hash(password),
False,
data.get('transcription_providers', []),
data.get('postprocess_providers', []),
)
return jsonify({"success": True})
@app.route('/api/list-users', methods=['GET'])
def list_users():
admin = get_current_username()
admin_info = get_user(admin)
if not admin or not admin_info or not admin_info.get('is_admin'):
return jsonify({"error": "Unauthorized"}), 401
return jsonify({"users": db_list_users()})
@app.route('/api/update-user-providers', methods=['POST'])
def update_user_providers():
admin = get_current_username()
admin_info = get_user(admin)
if not admin or not admin_info or not admin_info.get('is_admin'):
return jsonify({"error": "Unauthorized"}), 401
data = request.get_json() or {}
username = data.get('username')
user = get_user(username)
if not user:
return jsonify({"error": "User not found"}), 404
if username == 'admin':
return jsonify({"error": "Cannot modify admin"}), 400
db_update_user_providers(
username,
data.get('transcription_providers', user.get('transcription_providers', [])),
data.get('postprocess_providers', user.get('postprocess_providers', [])),
)
return jsonify({"success": True})
@app.route('/api/delete-user', methods=['POST'])
def delete_user():
"""Remove a non-admin user and delete their notes folder"""
admin = get_current_username()
admin_info = get_user(admin)
if not admin or not admin_info or not admin_info.get('is_admin'):
return jsonify({"error": "Unauthorized"}), 401
data = request.get_json() or {}
username = data.get('username')
if not username or not get_user(username):
return jsonify({"error": "User not found"}), 404
if username == 'admin':
return jsonify({"error": "Cannot delete admin"}), 400
db_delete_user(username)
user_dir = os.path.join(os.getcwd(), 'saved_notes', username)
try:
shutil.rmtree(user_dir)
except FileNotFoundError:
pass
return jsonify({"success": True})
@app.route('/api/transcribe', methods=['POST'])
def transcribe_audio():
"""Endpoint para transcribir audio usando OpenAI o whisper.cpp local"""
try:
username = get_current_username()
if not username:
return jsonify({"error": "Unauthorized"}), 401
# Obtener el archivo de audio del request
if 'audio' not in request.files:
return jsonify({"error": "No se encontró archivo de audio"}), 400
audio_file = request.files['audio']
if audio_file.filename == '':
return jsonify({"error": "Archivo de audio vacío"}), 400
# Obtener parámetros del request
language = request.form.get('language', None) # None = detección automática
provider = request.form.get('provider', 'openai') # openai o local
enable_speaker_diarization = request.form.get('enable_speaker_diarization', 'false').lower() == 'true'
tp, _ = get_user_providers(username)
if tp and provider not in tp:
return jsonify({"error": "Transcription provider not allowed"}), 403
model_name = request.form.get('model')
# Verificar disponibilidad del proveedor
if provider == 'local':
if not WHISPER_CPP_AVAILABLE:
return jsonify({"error": "Whisper.cpp local no está disponible"}), 500
if not model_name:
return jsonify({"error": "Model not specified"}), 400
audio_bytes = audio_file.read()
models_dir = os.path.join(os.getcwd(), 'whisper-cpp-models')
model_filename = sanitize_filename(model_name)
model_path = os.path.join(models_dir, model_filename)
if not is_path_within_directory(models_dir, model_path):
return jsonify({"error": "Invalid model path"}), 400
result = whisper_wrapper.transcribe_audio_from_bytes(
audio_bytes,
audio_file.filename,
language,
model_path
)
if result.get('success'):
transcription = result.get('transcription', '')
# Apply speaker diarization if enabled
if enable_speaker_diarization and transcription:
try:
diarization_wrapper = get_speaker_diarization_wrapper()
if diarization_wrapper.is_available() or diarization_wrapper.initialize():
segments = diarization_wrapper.diarize_audio_bytes(audio_bytes, audio_file.filename)
if segments:
transcription = diarization_wrapper.apply_diarization_to_transcription(transcription, segments)
print(f"Applied speaker diarization: {len(segments)} segments found")
else:
print("Speaker diarization not available, continuing without it")
except Exception as e:
print(f"Error applying speaker diarization: {e}")
# Continue without diarization
return jsonify({
"transcription": transcription,
"provider": "local",
"model": result.get('model')
})
else:
return jsonify({"error": f"Error en transcripción local: {result.get('error', 'Unknown error')}"}), 500
elif provider == 'sensevoice':
# Check SenseVoice availability dynamically
sensevoice_available = sensevoice_wrapper and sensevoice_wrapper.is_available()
if not sensevoice_available:
return jsonify({"error": "SenseVoice no está disponible. Asegúrate de haber descargado el modelo SenseVoiceSmall."}), 500
# Usar SenseVoice
audio_bytes = audio_file.read()
# Obtener opciones adicionales
detect_emotion = request.form.get('detect_emotion', 'true').lower() == 'true'
detect_events = request.form.get('detect_events', 'true').lower() == 'true'
use_itn = request.form.get('use_itn', 'true').lower() == 'true'
result = sensevoice_wrapper.transcribe_audio_from_bytes(
audio_bytes,
audio_file.filename,
language,
detect_emotion=detect_emotion,
detect_events=detect_events,
use_itn=use_itn
)
if result.get('success'):
transcription = result.get('transcription', '')
# Apply speaker diarization if enabled
if enable_speaker_diarization and transcription:
try:
diarization_wrapper = get_speaker_diarization_wrapper()
if diarization_wrapper.is_available() or diarization_wrapper.initialize():
segments = diarization_wrapper.diarize_audio_bytes(audio_bytes, audio_file.filename)
if segments:
transcription = diarization_wrapper.apply_diarization_to_transcription(transcription, segments)
print(f"Applied speaker diarization: {len(segments)} segments found")
else:
print("Speaker diarization not available, continuing without it")
except Exception as e:
print(f"Error applying speaker diarization: {e}")
# Continue without diarization
response_data = {
"transcription": transcription,
"provider": "sensevoice",
"model": result.get('model', 'SenseVoiceSmall'),
"language_detected": result.get('language_detected'),
}
# Agregar información adicional si está disponible
if result.get('emotion'):
response_data["emotion"] = result.get('emotion')
if result.get('events'):
response_data["events"] = result.get('events')
return jsonify(response_data)
else:
return jsonify({"error": f"Error en transcripción SenseVoice: {result.get('error', 'Unknown error')}"}), 500
else: # OpenAI
if not OPENAI_API_KEY:
return jsonify({"error": "API key de OpenAI no configurada"}), 500
if not model_name:
return jsonify({"error": "Model not specified"}), 400
# Preparar la petición a OpenAI
model_to_use = model_name
files = {
'file': (audio_file.filename, audio_file.stream, audio_file.content_type),
'model': (None, model_to_use)
}
# Solo añadir language si se especifica (None = auto-detectar)
if language and language != 'auto':
files['language'] = (None, language)
headers = {
'Authorization': f'Bearer {OPENAI_API_KEY}'
}
response = requests.post(
'https://api.openai.com/v1/audio/transcriptions',
files=files,
headers=headers
)
if response.status_code == 200:
result = response.json()
return jsonify({
"transcription": result.get('text', ''),
"provider": "openai",
"model": model_to_use
})
else:
return jsonify({"error": "Error en la transcripción"}), response.status_code
except Exception as e:
return jsonify({"error": f"Error interno: {str(e)}"}), 500
@app.route('/api/improve-text', methods=['POST'])
def improve_text():
"""Endpoint para mejorar texto usando OpenAI o Google AI"""
try:
username = get_current_username()
if not username:
return jsonify({"error": "Unauthorized"}), 401
data = request.get_json()
if not data:
return jsonify({"error": "Faltan parámetros requeridos"}), 400
# Chat assistant support
if 'messages' in data:
provider = data.get('provider', 'openai')
_, pp = get_user_providers(username)
if pp and provider not in pp:
return jsonify({"error": "Post-process provider not allowed"}), 403
stream = data.get('stream', False)
model = data.get('model')
note = data.get('note', '')
messages = data['messages']
if note:
messages = [{'role': 'system', 'content': note}] + messages
if not model:
return jsonify({"error": "Model not specified"}), 400
if stream:
if provider == 'openai':
return chat_openai_stream(messages, model)
elif provider == 'google':
return chat_google_stream(messages, model)
elif provider == 'openrouter':
if model in OPENROUTER_PAID_MODELS and not user_allows_openrouter_paid_models(username):
return jsonify({"error": "OpenRouter paid models are disabled"}), 403
return chat_openrouter_stream(messages, model)
elif provider == 'groq':
return chat_groq_stream(messages, model)
elif provider == 'lmstudio':
host = data.get('host', LMSTUDIO_HOST)
port = data.get('port', LMSTUDIO_PORT)
return chat_lmstudio_stream(messages, model, host, port)
elif provider == 'ollama':
host = data.get('host', OLLAMA_HOST)
port = data.get('port', OLLAMA_PORT)
return chat_ollama_stream(messages, model, host, port)
else:
return jsonify({"error": "Proveedor no soportado para streaming"}), 400
else:
return jsonify({"error": "Non-streaming chat not supported"}), 400
if 'text' not in data or 'improvement_type' not in data:
return jsonify({"error": "Faltan parámetros requeridos"}), 400
text = data['text']
improvement_type = data['improvement_type']
provider = data.get('provider', 'openai') # openai o google
_, pp = get_user_providers(username)
if pp and provider not in pp:
return jsonify({"error": "Post-process provider not allowed"}), 403
stream = data.get('stream', False) # Nuevo parámetro para streaming
custom_prompt = data.get('custom_prompt') # Nuevo parámetro para prompts personalizados
if stream:
if provider == 'openai':
model = data.get('model')
if not model:
return jsonify({"error": "Model not specified"}), 400
return improve_text_openai_stream(text, improvement_type, model, custom_prompt)
elif provider == 'google':
model = data.get('model')
if not model:
return jsonify({"error": "Model not specified"}), 400
return improve_text_google_stream(text, improvement_type, model, custom_prompt)
elif provider == 'openrouter':
model = data.get('model')
if not model:
return jsonify({"error": "Model not specified"}), 400
return improve_text_openrouter_stream(text, improvement_type, model, custom_prompt)
elif provider == 'groq':
model = data.get('model')
if not model:
return jsonify({"error": "Model not specified"}), 400
return improve_text_groq_stream(text, improvement_type, model, custom_prompt)
elif provider == 'lmstudio':
model = data.get('model')
host = data.get('host', LMSTUDIO_HOST)
port = data.get('port', LMSTUDIO_PORT)
return improve_text_lmstudio_stream(text, improvement_type, model, host, port, custom_prompt)
elif provider == 'ollama':
model = data.get('model')
host = data.get('host', OLLAMA_HOST)
port = data.get('port', OLLAMA_PORT)
return improve_text_ollama_stream(text, improvement_type, model, host, port, custom_prompt)
else:
return jsonify({"error": "Proveedor no soportado para streaming"}), 400
else:
if provider == 'openai':
model = data.get('model')
if not model:
return jsonify({"error": "Model not specified"}), 400
return improve_text_openai(text, improvement_type, model, custom_prompt)
elif provider == 'google':
model = data.get('model')
if not model:
return jsonify({"error": "Model not specified"}), 400
return improve_text_google(text, improvement_type, model, custom_prompt)
elif provider == 'openrouter':
model = data.get('model')
if not model:
return jsonify({"error": "Model not specified"}), 400
if model in OPENROUTER_PAID_MODELS and not user_allows_openrouter_paid_models(username):
return jsonify({"error": "OpenRouter paid models are disabled"}), 403
return improve_text_openrouter(text, improvement_type, model, custom_prompt)
elif provider == 'groq':
model = data.get('model')
if not model:
return jsonify({"error": "Model not specified"}), 400
return improve_text_groq(text, improvement_type, model, custom_prompt)
elif provider == 'lmstudio':
model = data.get('model')
host = data.get('host', LMSTUDIO_HOST)
port = data.get('port', LMSTUDIO_PORT)
return improve_text_lmstudio(text, improvement_type, model, host, port, custom_prompt)
elif provider == 'ollama':
model = data.get('model')
host = data.get('host', OLLAMA_HOST)
port = data.get('port', OLLAMA_PORT)
return improve_text_ollama(text, improvement_type, model, host, port, custom_prompt)
else:
return jsonify({"error": "Proveedor no soportado"}), 400
except Exception as e:
return jsonify({"error": f"Error interno: {str(e)}"}), 500
def improve_text_openai(text, improvement_type, model, custom_prompt=None):
"""Mejorar texto usando OpenAI"""
if not OPENAI_API_KEY:
return jsonify({"error": "API key de OpenAI no configurada"}), 500
if not model:
return jsonify({"error": "Model not specified"}), 400
# Si se proporciona un prompt personalizado, usarlo directamente
if custom_prompt:
prompt = f"{custom_prompt}\n\n{text}"
else:
# Definir prompts según el tipo de mejora (solo para estilos predeterminados)
prompts = {
'clarity': f"Rewrite the following text in a clearer and more readable way. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the improved text, without additional explanations:\n\n{text}",
'formal': f"Rewrite the following text in a formal tone. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the rewritten text, without additional explanations:\n\n{text}",
'casual': f"Rewrite the following text in a casual and friendly tone. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the rewritten text, without additional explanations:\n\n{text}",
'academic': f"Rewrite the following text in an academic style. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the rewritten text, without additional explanations:\n\n{text}",
'narrative': f"Improve the following narrative text or novel dialogue, preserving the literary style and narrative voice. Enhance flow, description and literary quality while keeping the essence of the text. Respond ONLY with the improved text, without additional explanations:\n\n{text}",
'academic_v2': f"Improve the following academic text by making minimal changes to preserve the author's words. Use more precise wording when necessary, improve the structure and remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Keep the original style and vocabulary as much as possible. Respond ONLY with the improved text, without additional explanations:\n\n{text}",
'summarize': f"Create a concise summary of the following text. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the summary, without additional explanations:\n\n{text}",
'expand': f"Expand the following text by adding more details and relevant context. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the expanded text, without additional explanations:\n\n{text}",
'remove_emoji': f"Remove every single emoji from this text. You MUST NOT change nothing from the text, just remove the emojis. Respond ONLY with the improved text, without additional explanations:\n\n{text}",
'diarization_fix': f"Correct the speaker diarization in this transcript. Some speaker tags may be incorrectly placed. You MUST NOT modify the text content, only adjust the position of the speaker tags or the text itself. Keep the tags in the format [SPEAKER X]. Respond ONLY with the fixed diarization text, without additional explanations:\n\n{text}",
'tabularize': f"Convert the following text into a table using the pattern [R001-C001 // Cell]. Respond ONLY with these cells in row-major order:\n\n{text}",
}
prompt = prompts.get(improvement_type, f"Improve the following text: {text}")
headers = {
'Authorization': f'Bearer {OPENAI_API_KEY}',
'Content-Type': 'application/json'
}
payload = {
'model': model,
'messages': [
{
'role': 'user',
'content': prompt
}
],
'max_tokens': 1000,
'temperature': 0.7
}
response = requests.post(
'https://api.openai.com/v1/chat/completions',
headers=headers,
json=payload
)
if response.status_code == 200:
result = response.json()
improved_text = result['choices'][0]['message']['content']
return jsonify({"improved_text": improved_text})
else:
return jsonify({"error": "Error al mejorar el texto"}), response.status_code
def improve_text_google(text, improvement_type, model, custom_prompt=None):
"""Mejorar texto usando Google AI (Gemini)"""
if not GOOGLE_API_KEY:
return jsonify({"error": "API key de Google no configurada"}), 500
if not model:
return jsonify({"error": "Model not specified"}), 400
# Si se proporciona un prompt personalizado, usarlo directamente
if custom_prompt:
prompt = f"{custom_prompt}\n\n{text}"
else:
# Definir prompts según el tipo de mejora (solo para estilos predeterminados)
prompts = {
'clarity': f"Rewrite the following text in a clearer and more readable way. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the improved text, without additional explanations:\n\n{text}",
'formal': f"Rewrite the following text in a formal tone. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the rewritten text, without additional explanations:\n\n{text}",
'casual': f"Rewrite the following text in a casual and friendly tone. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the rewritten text, without additional explanations:\n\n{text}",
'academic': f"Rewrite the following text in an academic style. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the rewritten text, without additional explanations:\n\n{text}",
'narrative': f"Improve the following narrative text or novel dialogue, preserving the literary style and narrative voice. Enhance flow, description and literary quality while keeping the essence of the text. Respond ONLY with the improved text, without additional explanations:\n\n{text}",
'academic_v2': f"Improve the following academic text by making minimal changes to preserve the author's words. Use more precise wording when necessary, improve the structure and remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Keep the original style and vocabulary as much as possible. Respond ONLY with the improved text, without additional explanations:\n\n{text}",
'summarize': f"Create a concise summary of the following text. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the summary, without additional explanations:\n\n{text}",
'expand': f"Expand the following text by adding more details and relevant context. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the expanded text, without additional explanations:\n\n{text}",
'remove_emoji': f"Remove every single emoji from this text. You MUST NOT change nothing from the text, just remove the emojis. Respond ONLY with the improved text, without additional explanations:\n\n{text}",
'diarization_fix': f"Correct the speaker diarization in this transcript. Some speaker tags may be incorrectly placed. You MUST NOT modify the text content, only adjust the position of the speaker tags or the text itself. Keep the tags in the format [SPEAKER X]. Respond ONLY with the fixed diarization text, without additional explanations:\n\n{text}",
'tabularize': f"Convert the following text into a table using the pattern [R001-C001 // Cell]. Respond ONLY with these cells in row-major order:\n\n{text}",
}
prompt = prompts.get(improvement_type, f"Improve the following text: {text}")
# Nueva URL según la documentación oficial de Gemini
url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={GOOGLE_API_KEY}"
headers = {
'Content-Type': 'application/json'
}
payload = {
'contents': [{
'parts': [{'text': prompt}]
}]
}
response = requests.post(url, headers=headers, json=payload)
if response.status_code == 200:
result = response.json()
improved_text = result['candidates'][0]['content']['parts'][0]['text']
return jsonify({"improved_text": improved_text})
else:
return jsonify({"error": "Error al mejorar el texto con Google AI"}), response.status_code
def improve_text_openai_stream(text, improvement_type, model, custom_prompt=None):
"""Mejorar texto usando OpenAI con streaming"""
if not OPENAI_API_KEY:
return jsonify({"error": "API key de OpenAI no configurada"}), 500
if not model:
return jsonify({"error": "Model not specified"}), 400
# Si se proporciona un prompt personalizado, usarlo directamente
if custom_prompt:
prompt = f"{custom_prompt}\n\n{text}"
else:
# Definir prompts según el tipo de mejora (solo para estilos predeterminados)
prompts = {
'clarity': f"Rewrite the following text in a clearer and more readable way. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the improved text, without additional explanations:\n\n{text}",
'formal': f"Rewrite the following text in a formal tone. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the rewritten text, without additional explanations:\n\n{text}",
'casual': f"Rewrite the following text in a casual and friendly tone. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the rewritten text, without additional explanations:\n\n{text}",
'academic': f"Rewrite the following text in an academic style. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the rewritten text, without additional explanations:\n\n{text}",
'narrative': f"Improve the following narrative text or novel dialogue, preserving the literary style and narrative voice. Enhance flow, description and literary quality while keeping the essence of the text. Respond ONLY with the improved text, without additional explanations:\n\n{text}",
'academic_v2': f"Improve the following academic text by making minimal changes to preserve the author's words. Use more precise wording when necessary, improve the structure and remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Keep the original style and vocabulary as much as possible. Respond ONLY with the improved text, without additional explanations:\n\n{text}",
'summarize': f"Create a concise summary of the following text. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the summary, without additional explanations:\n\n{text}",
'expand': f"Expand the following text by adding more details and relevant context. Remove any interjections or expressions typical of spoken language (mmm, ahhh, eh, um, etc.) and expressions of hesitation when speaking or thinking aloud. Respond ONLY with the expanded text, without additional explanations:\n\n{text}",
'remove_emoji': f"Remove every single emoji from this text. You MUST NOT change nothing from the text, just remove the emojis. Respond ONLY with the improved text, without additional explanations:\n\n{text}",
'diarization_fix': f"Correct the speaker diarization in this transcript. Some speaker tags may be incorrectly placed. You MUST NOT modify the text content, only adjust the position of the speaker tags or the text itself. Keep the tags in the format [SPEAKER X]. Respond ONLY with the fixed diarization text, without additional explanations:\n\n{text}",
'tabularize': f"Convert the following text into a table using the pattern [R001-C001 // Cell]. Respond ONLY with these cells in row-major order:\n\n{text}",
}
prompt = prompts.get(improvement_type, f"Improve the following text: {text}")
headers = {
'Authorization': f'Bearer {OPENAI_API_KEY}',
'Content-Type': 'application/json'
}
payload = {
'model': model,
'messages': [
{
'role': 'user',
'content': prompt
}
],
'max_tokens': 1000,
'temperature': 0.7,
'stream': True
}
def generate():
try:
response = requests.post(
'https://api.openai.com/v1/chat/completions',
headers=headers,
json=payload,
stream=True
)
if response.status_code != 200:
yield f"data: {json.dumps({'error': 'Error al mejorar el texto'})}\n\n"
return