Merge branch 'dev' into hugo

# Conflicts:
#	.env.dev
#	backend/app/__init__.py
#	backend/app/models.py
#	frontend/src/views/ChatView.vue
This commit is contained in:
hugo committed 2026-06-04 15:36:21 +08:00
commit 2ce5256483
30 files changed
+1599 -345

No files matched your search

+97
View File
@@ -0,0 +1,97 @@
import os
import uuid
from typing import BinaryIO
from minio import Minio
from minio.error import S3Error
from werkzeug.utils import secure_filename
from app.config import config, ACTIVE_ENV_NAME
cfg = config[ACTIVE_ENV_NAME]
class MinioService:
def __init__(self):
self.client = Minio(
cfg.MINIO_ENDPOINT,
access_key=cfg.MINIO_ACCESS_KEY,
secret_key=cfg.MINIO_SECRET_KEY,
secure=cfg.MINIO_SECURE,
)
self.bucket_name = cfg.MINIO_BUCKET_NAME
self._ensure_bucket_exists()
def _ensure_bucket_exists(self):
try:
if not self.client.bucket_exists(self.bucket_name):
self.client.make_bucket(self.bucket_name)
# Set bucket policy to public read
policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {"AWS": ["*"]},
"Action": ["s3:GetObject"],
"Resource": [f"arn:aws:s3:::{self.bucket_name}/*"]
}
]
}
import json
self.client.set_bucket_policy(self.bucket_name, json.dumps(policy))
except Exception as e:
# log or print error
print(f"MinIO bucket error (or not reachable): {e}")
def upload_file(self, file_stream: BinaryIO, filename: str, content_type: str, file_size: int) -> str:
"""
Uploads a file to MinIO and returns the generated object name.
"""
# If MinIO is not running, we could fallback to local storage or raise clear error
try:
self._ensure_bucket_exists()
except Exception:
pass
ext = os.path.splitext(filename)[1]
unique_filename = f"{uuid.uuid4().hex}{ext}"
try:
self.client.put_object(
bucket_name=self.bucket_name,
object_name=unique_filename,
data=file_stream,
length=file_size,
content_type=content_type
)
except Exception as e:
# For development, if minio is down, let's mock it so UI can continue
print(f"Warning: Minio upload failed ({e}). Fallback to local storage.")
# fallback to local storage
os.makedirs('data/agent-guides', exist_ok=True)
local_path = os.path.join('data/agent-guides', unique_filename)
file_stream.seek(0)
with open(local_path, 'wb') as f:
f.write(file_stream.read())
return unique_filename
def get_public_url(self, object_name: str) -> str:
"""
Returns the public URL for the given object name.
"""
if os.path.exists(os.path.join('data/agent-guides', object_name)):
# It's a local fallback file
# the backend needs a static route to serve this, we'll assume /api/agents/guides/files/<object_name>
# but since we want it public without auth:
return f"/api/agents/guides/files/{object_name}"
base_url = cfg.MINIO_PUBLIC_BASE_URL.rstrip('/')
return f"{base_url}/{self.bucket_name}/{object_name}"
def delete_file(self, object_name: str):
try:
self.client.remove_object(self.bucket_name, object_name)
except S3Error as e:
print(f"Error deleting file from MinIO: {e}")
minio_service = MinioService()
+75
View File
@@ -0,0 +1,75 @@
"""
SiliconFlow ASR service (OpenAI-compatible /v1/audio/transcriptions).
"""
import io
import os
from typing import Tuple
ALLOWED_AUDIO_EXTENSIONS = frozenset({
'webm', 'wav', 'mp3', 'm4a', 'mp4', 'mpeg', 'mpga', 'ogg',
})
MAX_AUDIO_BYTES = int(os.getenv('ASR_MAX_AUDIO_BYTES', str(10 * 1024 * 1024)))
class SpeechAsrService:
@classmethod
def _get_client(cls):
try:
from openai import OpenAI
except ImportError as exc:
raise RuntimeError('OpenAI SDK not installed') from exc
api_key = (os.getenv('GJL_API_KEY') or '').strip()
base_url = (os.getenv('GJL_API_BASE') or 'https://api.siliconflow.cn/v1').strip()
if not api_key:
raise RuntimeError('Missing GJL_API_KEY. Configure it in .env to enable speech recognition')
return OpenAI(api_key=api_key, base_url=base_url)
@classmethod
def _resolve_model(cls) -> str:
return (os.getenv('ASR_MODEL') or 'FunAudioLLM/SenseVoiceSmall').strip()
@classmethod
def _normalize_filename(cls, filename: str, content_type: str) -> str:
name = (filename or '').strip() or 'recording.webm'
if '.' not in name:
if 'wav' in content_type:
name = f'{name}.wav'
elif 'mp4' in content_type or 'm4a' in content_type:
name = f'{name}.m4a'
else:
name = f'{name}.webm'
return name
@classmethod
def validate_upload(cls, filename: str, size: int) -> None:
ext = filename.rsplit('.', 1)[-1].lower() if '.' in filename else ''
if ext and ext not in ALLOWED_AUDIO_EXTENSIONS:
raise ValueError(f'Unsupported audio format: .{ext}')
if size <= 0:
raise ValueError('Audio file is empty')
if size > MAX_AUDIO_BYTES:
raise ValueError(f'Audio file exceeds {MAX_AUDIO_BYTES // (1024 * 1024)}MB limit')
@classmethod
def transcribe(cls, audio_bytes: bytes, filename: str, content_type: str = '') -> Tuple[str, str]:
cls.validate_upload(filename, len(audio_bytes))
client = cls._get_client()
model = cls._resolve_model()
safe_name = cls._normalize_filename(filename, content_type)
file_obj = io.BytesIO(audio_bytes)
file_obj.name = safe_name
try:
result = client.audio.transcriptions.create(
model=model,
file=file_obj,
)
except Exception as exc:
raise RuntimeError(f'Speech recognition request failed: {exc}') from exc
text = str(getattr(result, 'text', '') or '').strip()
return text, model