Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(asr): detect Slack audio clips by signature

cyhf6f96dfe4e20
diff --git a/core/audio_asr.py b/core/audio_asr.py
index 74a3080ff..0d913d3c2 100644
--- a/core/audio_asr.py
+++ b/core/audio_asr.py
@@ -30,6 +30,47 @@ _SUPPORTED_AUDIO_EXTENSIONS = {
".webm",
}
+AUDIO_SIGNATURE_SAMPLE_BYTES = 64
+
+
+def detect_audio_mime_from_sample(data: bytes) -> tuple[str, str] | None:
+ """Detect high-confidence audio MIME metadata from file signature bytes."""
+ if len(data) < 4:
+ return None
+
+ if len(data) >= 12 and data[4:8] == b"ftyp":
+ brands = data[8:AUDIO_SIGNATURE_SAMPLE_BYTES]
+ if data[8:12] in {b"M4A ", b"M4B "} or b"M4A " in brands or b"M4B " in brands:
+ return ("audio/mp4", ".m4a")
+ return None
+
+ if data[:4] == b"OggS":
+ return ("audio/ogg", ".ogg")
+
+ if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WAVE":
+ return ("audio/wav", ".wav")
+
+ if data[:4] == b"fLaC":
+ return ("audio/flac", ".flac")
+
+ if len(data) >= 2 and data[0] == 0xFF and (data[1] & 0xF6) == 0xF0:
+ return ("audio/aac", ".aac")
+
+ if data[:3] == b"ID3" or (
+ len(data) >= 2 and data[0] == 0xFF and (data[1] & 0xE0) == 0xE0 and (data[1] & 0x06) != 0
+ ):
+ return ("audio/mpeg", ".mp3")
+
+ return None
+
+
+def detect_audio_mime_from_file(path: Path) -> tuple[str, str] | None:
+ try:
+ with path.open("rb") as file_obj:
+ return detect_audio_mime_from_sample(file_obj.read(AUDIO_SIGNATURE_SAMPLE_BYTES))
+ except OSError:
+ return None
+
@dataclass
class AudioTranscript:
@@ -87,7 +128,12 @@ class AudioAsrService:
return True
name = attachment.name or attachment.local_path or ""
suffix = Path(name).suffix.lower()
- return suffix in _SUPPORTED_AUDIO_EXTENSIONS
+ if suffix in _SUPPORTED_AUDIO_EXTENSIONS:
+ return True
+
+ if attachment.local_path:
+ return detect_audio_mime_from_file(Path(attachment.local_path)) is not None
+ return False
def eligible_attachments(self, attachments: Iterable[FileAttachment]) -> list[FileAttachment]:
asr_config = self._get_audio_asr_config()
@@ -150,7 +196,18 @@ class AudioAsrService:
return None
asr_config = self._get_audio_asr_config()
+ detected_audio = detect_audio_mime_from_file(path)
mimetype = attachment.mimetype or mimetypes.guess_type(str(path))[0] or "application/octet-stream"
+ mimetype_lower = mimetype.lower()
+ if detected_audio and (
+ not mimetype
+ or mimetype_lower == "application/octet-stream"
+ or not mimetype_lower.startswith(("audio/", "video/"))
+ ):
+ mimetype = detected_audio[0]
+ filename = attachment.name or path.name
+ if detected_audio and not Path(filename).suffix:
+ filename = f"{filename}{detected_audio[1]}"
start = time.monotonic()
form = aiohttp.FormData()
form.add_field("model", asr_config.model)
@@ -160,7 +217,7 @@ class AudioAsrService:
form.add_field(
"file",
handle,
- filename=attachment.name or path.name,
+ filename=filename,
content_type=mimetype,
)
try:
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index dab9b19d7..bde007947 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -5,8 +5,10 @@ from datetime import datetime
from typing import List, Optional, Tuple
from core.audio_asr import (
+ AUDIO_SIGNATURE_SAMPLE_BYTES,
AudioTranscript,
append_audio_transcripts_to_message,
+ detect_audio_mime_from_sample,
format_audio_transcript_echo,
)
from modules.agents.base import AgentRequest
@@ -737,7 +739,7 @@ class MessageHandler(BaseHandler):
os.replace(temp_path, local_path)
content_size = local_path.stat().st_size
with open(local_path, "rb") as file_obj:
- detected_sample = file_obj.read(16)
+ detected_sample = file_obj.read(AUDIO_SIGNATURE_SAMPLE_BYTES)
else:
self._cleanup_partial_attachment(temp_path)
error_text = result.error or "Download failed"
@@ -749,7 +751,7 @@ class MessageHandler(BaseHandler):
with open(local_path, "wb") as f:
f.write(content)
content_size = len(content)
- detected_sample = content[:16]
+ detected_sample = content[:AUDIO_SIGNATURE_SAMPLE_BYTES]
else:
logger.warning("Failed to download file %s: download returned no content", attachment.name)
errors.append(
@@ -757,9 +759,11 @@ class MessageHandler(BaseHandler):
)
if content is not None or content_size is not None:
- # Detect actual MIME type from magic bytes for images
- # (some platforms don't provide accurate MIME, e.g. Feishu)
+ # Detect actual MIME type from magic bytes for media
+ # (some platforms don't provide accurate MIME, e.g. Feishu and Slack)
detected = self._detect_image_mime(detected_sample or b"")
+ if not detected:
+ detected = detect_audio_mime_from_sample(detected_sample or b"")
if detected:
attachment.mimetype = detected[0]
# Fix filename extension to match actual type
diff --git a/tests/test_audio_asr.py b/tests/test_audio_asr.py
index 8a70c53d0..1e6f81fbc 100644
--- a/tests/test_audio_asr.py
+++ b/tests/test_audio_asr.py
@@ -27,6 +27,22 @@ class AudioAsrServiceTests(unittest.TestCase):
self.assertFalse(service.is_audio_attachment(FileAttachment(name="wechat_voice.silk", mimetype="audio/silk")))
self.assertFalse(service.is_audio_attachment(FileAttachment(name="report.pdf", mimetype="application/pdf")))
+ def test_audio_detection_uses_local_m4a_signature_when_metadata_is_generic(self):
+ service = AudioAsrService(SimpleNamespace(audio_asr=AudioAsrConfig()))
+ with tempfile.TemporaryDirectory() as tmpdir:
+ audio_path = Path(tmpdir) / "F0B50NK1CS2"
+ audio_path.write_bytes(b"\x00\x00\x00\x18ftypM4A \x00\x00\x00\x00M4A isom")
+
+ self.assertTrue(
+ service.is_audio_attachment(
+ FileAttachment(
+ name="F0B50NK1CS2",
+ mimetype="application/octet-stream",
+ local_path=str(audio_path),
+ )
+ )
+ )
+
def test_requires_enabled_vibe_cloud_pairing(self):
service = AudioAsrService(
SimpleNamespace(
diff --git a/tests/test_message_handler_attachments.py b/tests/test_message_handler_attachments.py
index 95ee8c4a5..ebcd149a7 100644
--- a/tests/test_message_handler_attachments.py
+++ b/tests/test_message_handler_attachments.py
@@ -237,6 +237,32 @@ class MessageHandlerAttachmentTests(unittest.IsolatedAsyncioTestCase):
self.assertIsNone(file_info["url"])
self.assertEqual(file_info["slack_file_id"], "F123")
+ async def test_process_file_attachments_normalizes_slack_audio_clip_from_signature(self):
+ im_client = _StubIMClient(
+ download_result=b"\x00\x00\x00\x18ftypM4A \x00\x00\x00\x00M4A isom",
+ stream_result=True,
+ )
+ handler = MessageHandler(_StubController(im_client))
+ attachment = FileAttachment(
+ name="F0B50NK1CS2",
+ mimetype="application/octet-stream",
+ url=None,
+ size=1024,
+ )
+ attachment.__dict__["slack_file_id"] = "F0B50NK1CS2"
+ context = MessageContext(user_id="U1", channel_id="C1", platform="slack", files=[attachment])
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ with patch("config.paths.get_attachments_dir", return_value=Path(tmpdir)):
+ processed, errors = await handler._process_file_attachments(context, "/tmp/work")
+
+ self.assertIsNotNone(processed)
+ assert processed is not None
+ self.assertEqual(errors, [])
+ self.assertEqual(processed[0].name, "F0B50NK1CS2.m4a")
+ self.assertEqual(processed[0].mimetype, "audio/mp4")
+ self.assertTrue(processed[0].local_path)
+
def test_append_attachment_errors_uses_error_text_without_file_paths(self):
handler = MessageHandler(_StubController(_StubIMClient()))