ciyidogan commited on
Commit
8f23c35
·
verified ·
1 Parent(s): 6cf7b79

Update admin_routes.py

Browse files
Files changed (1) hide show
  1. admin_routes.py +39 -93
admin_routes.py CHANGED
@@ -452,7 +452,6 @@ async def get_environment(username: str = Depends(verify_token)):
452
  })
453
  }
454
 
455
-
456
  @router.put("/environment")
457
  async def update_environment(
458
  update: EnvironmentUpdate,
@@ -495,103 +494,51 @@ async def update_environment(
495
  # Encrypt API keys if needed
496
  from encryption_utils import encrypt
497
 
498
- # TTS key encryption debug
499
  if update.tts_engine_api_key:
500
  encrypted_tts_key = encrypt(update.tts_engine_api_key)
501
  log(f"🔐 Encrypted TTS key: {encrypted_tts_key[:20]}...")
502
  else:
503
  encrypted_tts_key = ""
504
- log("⚠️ No TTS key to encrypt")
505
 
506
- if update.tts_settings:
507
- config["config"]["tts_settings"] = update.tts_settings
508
-
509
- if update.stt_settings:
510
- config["config"]["stt_settings"] = update.stt_settings
511
 
512
  # Update config
513
  config["config"]["work_mode"] = update.work_mode
514
- config["config"]["cloud_token"] = update.cloud_token or ""
515
  config["config"]["spark_endpoint"] = update.spark_endpoint
516
  config["config"]["internal_prompt"] = update.internal_prompt or ""
517
  config["config"]["tts_engine"] = update.tts_engine
518
- config["config"]["tts_engine_api_key"] = encrypted_tts_key # Direkt encrypted değeri kullan
519
  config["config"]["stt_engine"] = update.stt_engine
520
- config["config"]["stt_engine_api_key"] = encrypt(update.stt_engine_api_key) if update.stt_engine_api_key else ""
521
  config["config"]["last_update_date"] = get_timestamp()
522
  config["config"]["last_update_user"] = username
523
 
524
- # Save öncesi kontrol
525
- log(f"💾 Config before save - TTS key: {config['config'].get('tts_engine_api_key', 'NOT SET')[:20]}...")
 
 
 
526
 
527
- # Add activity log - Güncellendi
528
  add_activity_log(config, username, "UPDATE_ENVIRONMENT", "config", None,
529
- "environment", f"Changed to {update.work_mode}, TTS: {update.tts_engine}, STT: {update.stt_engine}")
530
- # Save
 
531
  save_config(config)
532
 
 
 
 
 
533
  log(f"✅ Environment updated to {update.work_mode} with TTS: {update.tts_engine}, STT: {update.stt_engine} by {username}")
534
  return {"success": True}
535
 
536
- # ===================== TTS Endpoints =====================
537
- @router.post("/tts/generate")
538
- async def generate_tts(
539
- request: TTSRequest,
540
- username: str = Depends(verify_token)
541
- ):
542
- """Generate TTS audio from text"""
543
- try:
544
- config = load_config()
545
- env_config = config.get("config", {})
546
-
547
- tts_engine = env_config.get("tts_engine", "no_tts")
548
- if tts_engine == "no_tts":
549
- raise HTTPException(status_code=400, detail="TTS is not configured")
550
-
551
- # Get TTS provider
552
- from config_provider import ConfigProvider
553
- cfg = ConfigProvider.get()
554
- api_key = cfg.global_config.get_tts_api_key()
555
-
556
- if not api_key:
557
- raise HTTPException(status_code=400, detail="TTS API key not configured")
558
-
559
- # Import here to avoid circular dependency
560
- from tts_interface import create_tts_provider
561
-
562
- tts_provider = create_tts_provider(tts_engine, api_key)
563
- if not tts_provider:
564
- raise HTTPException(status_code=500, detail="Failed to create TTS provider")
565
-
566
- log(f"🎤 Generating TTS for {len(request.text)} characters using {tts_engine}")
567
-
568
- # Generate audio
569
- audio_data = await tts_provider.synthesize(
570
- text=request.text,
571
- voice_id=request.voice_id,
572
- model_id=request.model_id,
573
- output_format=request.output_format
574
- )
575
-
576
- # Return audio data
577
- from fastapi.responses import Response
578
-
579
- content_type = "audio/mpeg" if request.output_format.startswith("mp3") else "audio/wav"
580
-
581
- return Response(
582
- content=audio_data,
583
- media_type=content_type,
584
- headers={
585
- "Content-Disposition": f"attachment; filename=tts_output.{request.output_format.split('_')[0]}"
586
- }
587
- )
588
-
589
- except HTTPException:
590
- raise
591
- except Exception as e:
592
- log(f"❌ TTS generation error: {e}")
593
- raise HTTPException(status_code=500, detail=str(e))
594
-
595
  # ===================== Project Endpoints =====================
596
  @router.get("/projects/names")
597
  def list_enabled_projects():
@@ -1590,27 +1537,21 @@ async def generate_tts(
1590
  ):
1591
  """Generate TTS audio from text"""
1592
  try:
1593
- config = load_config()
1594
- env_config = config.get("config", {})
 
 
 
 
1595
 
1596
- tts_engine = env_config.get("tts_engine", "no_tts")
1597
  if tts_engine == "no_tts":
1598
  raise HTTPException(status_code=400, detail="TTS is not configured")
1599
 
1600
- # Get TTS provider
1601
- from config_provider import ConfigProvider
1602
- cfg = ConfigProvider.get()
1603
  api_key = cfg.global_config.get_tts_api_key()
1604
 
1605
- # Debug log - API key'in ilk ve son karakterlerini göster
1606
- if api_key:
1607
- masked_key = f"{api_key[:4]}...{api_key[-4:]}" if len(api_key) > 8 else "***"
1608
- log(f"🔑 TTS API Key (masked): {masked_key}")
1609
- log(f"🔑 Key starts with 'enc:': {api_key.startswith('enc:')}")
1610
- else:
1611
- log("❌ TTS API key is None!")
1612
-
1613
  if not api_key:
 
1614
  raise HTTPException(status_code=400, detail="TTS API key not configured")
1615
 
1616
  # Import here to avoid circular dependency
@@ -1621,6 +1562,7 @@ async def generate_tts(
1621
  raise HTTPException(status_code=500, detail="Failed to create TTS provider")
1622
 
1623
  log(f"🎤 Generating TTS for {len(request.text)} characters using {tts_engine}")
 
1624
 
1625
  # Generate audio
1626
  audio_data = await tts_provider.synthesize(
@@ -1629,24 +1571,28 @@ async def generate_tts(
1629
  model_id=request.model_id,
1630
  output_format=request.output_format
1631
  )
 
1632
  # Return audio data
1633
  from fastapi.responses import Response
1634
 
1635
- content_type = "audio/mpeg" if request.output_format.startswith("mp3") else "audio/wav"
1636
 
1637
  return Response(
1638
  content=audio_data,
1639
  media_type=content_type,
1640
  headers={
1641
- "Content-Disposition": f"attachment; filename=tts_output.{request.output_format.split('_')[0]}"
1642
  }
1643
  )
1644
 
1645
  except HTTPException:
1646
  raise
1647
  except Exception as e:
1648
- log(f"❌ TTS generation error: {e}")
1649
- raise HTTPException(status_code=500, detail=str(e))
 
 
 
1650
 
1651
  # ===================== Activity Log Endpoints =====================
1652
  @router.get("/activity-log")
 
452
  })
453
  }
454
 
 
455
  @router.put("/environment")
456
  async def update_environment(
457
  update: EnvironmentUpdate,
 
494
  # Encrypt API keys if needed
495
  from encryption_utils import encrypt
496
 
497
+ # TTS key encryption
498
  if update.tts_engine_api_key:
499
  encrypted_tts_key = encrypt(update.tts_engine_api_key)
500
  log(f"🔐 Encrypted TTS key: {encrypted_tts_key[:20]}...")
501
  else:
502
  encrypted_tts_key = ""
 
503
 
504
+ # STT key encryption
505
+ if update.stt_engine_api_key:
506
+ encrypted_stt_key = encrypt(update.stt_engine_api_key)
507
+ else:
508
+ encrypted_stt_key = ""
509
 
510
  # Update config
511
  config["config"]["work_mode"] = update.work_mode
512
+ config["config"]["cloud_token"] = encrypt(update.cloud_token) if update.cloud_token else ""
513
  config["config"]["spark_endpoint"] = update.spark_endpoint
514
  config["config"]["internal_prompt"] = update.internal_prompt or ""
515
  config["config"]["tts_engine"] = update.tts_engine
516
+ config["config"]["tts_engine_api_key"] = encrypted_tts_key
517
  config["config"]["stt_engine"] = update.stt_engine
518
+ config["config"]["stt_engine_api_key"] = encrypted_stt_key
519
  config["config"]["last_update_date"] = get_timestamp()
520
  config["config"]["last_update_user"] = username
521
 
522
+ if update.tts_settings:
523
+ config["config"]["tts_settings"] = update.tts_settings
524
+
525
+ if update.stt_settings:
526
+ config["config"]["stt_settings"] = update.stt_settings
527
 
528
+ # Add activity log
529
  add_activity_log(config, username, "UPDATE_ENVIRONMENT", "config", None,
530
+ "environment", f"Changed to {update.work_mode}, TTS: {update.tts_engine}, STT: {update.stt_engine}")
531
+
532
+ # Save config
533
  save_config(config)
534
 
535
+ # Reload ConfigProvider to reflect changes
536
+ from config_provider import ConfigProvider
537
+ ConfigProvider.reload()
538
+
539
  log(f"✅ Environment updated to {update.work_mode} with TTS: {update.tts_engine}, STT: {update.stt_engine} by {username}")
540
  return {"success": True}
541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
542
  # ===================== Project Endpoints =====================
543
  @router.get("/projects/names")
544
  def list_enabled_projects():
 
1537
  ):
1538
  """Generate TTS audio from text"""
1539
  try:
1540
+ # ConfigProvider'dan reload ederek güncel config'i alalım
1541
+ from config_provider import ConfigProvider
1542
+ cfg = ConfigProvider.reload()
1543
+
1544
+ tts_engine = cfg.global_config.tts_engine
1545
+ log(f"🔧 TTS Engine: {tts_engine}")
1546
 
 
1547
  if tts_engine == "no_tts":
1548
  raise HTTPException(status_code=400, detail="TTS is not configured")
1549
 
1550
+ # Get decrypted API key
 
 
1551
  api_key = cfg.global_config.get_tts_api_key()
1552
 
 
 
 
 
 
 
 
 
1553
  if not api_key:
1554
+ log("❌ TTS API key not found in config")
1555
  raise HTTPException(status_code=400, detail="TTS API key not configured")
1556
 
1557
  # Import here to avoid circular dependency
 
1562
  raise HTTPException(status_code=500, detail="Failed to create TTS provider")
1563
 
1564
  log(f"🎤 Generating TTS for {len(request.text)} characters using {tts_engine}")
1565
+ log(f"📝 Voice: {request.voice_id}, Model: {request.model_id}, Format: {request.output_format}")
1566
 
1567
  # Generate audio
1568
  audio_data = await tts_provider.synthesize(
 
1571
  model_id=request.model_id,
1572
  output_format=request.output_format
1573
  )
1574
+
1575
  # Return audio data
1576
  from fastapi.responses import Response
1577
 
1578
+ content_type = "audio/mpeg" if request.output_format and request.output_format.startswith("mp3") else "audio/wav"
1579
 
1580
  return Response(
1581
  content=audio_data,
1582
  media_type=content_type,
1583
  headers={
1584
+ "Content-Disposition": f"attachment; filename=tts_output.{request.output_format.split('_')[0] if request.output_format else 'mp3'}"
1585
  }
1586
  )
1587
 
1588
  except HTTPException:
1589
  raise
1590
  except Exception as e:
1591
+ log(f"❌ TTS generation error: {str(e)}")
1592
+ import traceback
1593
+ log(traceback.format_exc())
1594
+ raise HTTPException(status_code=500, detail=f"TTS generation failed: {str(e)}")
1595
+
1596
 
1597
  # ===================== Activity Log Endpoints =====================
1598
  @router.get("/activity-log")