Spaces:
Sleeping

SummarizeAV / tests /test_processing.py
SAAZIZI's picture
feat: add current Hugging Face models and reliable media analysis
63362c3 verified
Raw History Blame Contribute Delete
6.19 kB
import io
import json
from pathlib import Path
import pytest
from llama_index.embeddings.base import BaseEmbedding
from keyword_retriever.keyword_retreiver import MediaRetriever
from query_service.model_client import HostedLLM, ModelRequestError
from resource_loader.uploaded_media_loader import UploadedMediaLoader
from summarization_service.summarizer import TranscriptSummary
class MockEmbedding(BaseEmbedding):
embed_dim: int = 8
@classmethod
def class_name(cls):
return "TestEmbedding"
def _get_query_embedding(self, query):
return [1.0] * self.embed_dim
async def _aget_query_embedding(self, query):
return self._get_query_embedding(query)
def _get_text_embedding(self, text):
return [1.0] * self.embed_dim
def test_ordinary_audio_filename_is_saved_without_collisions(tmp_path, monkeypatch):
monkeypatch.setattr("resource_loader.uploaded_media_loader.output_path_audio", str(tmp_path))
first = UploadedMediaLoader(io.BytesIO(b"first recording"), "recording.WAV", "audio")
second = UploadedMediaLoader(io.BytesIO(b"second recording"), "recording.WAV", "audio")
first.download()
second.download()
assert first.filename != second.filename
assert Path(first.filename).suffix == ".wav"
assert (tmp_path / first.filename).read_bytes() == b"first recording"
assert (tmp_path / second.filename).read_bytes() == b"second recording"
def test_model_keys_are_private_and_requests_use_the_selected_model(monkeypatch):
calls = []
def request(url, **kwargs):
calls.append((url, kwargs))
return type("Response", (), {
"status_code": 200,
"json": lambda self: {"choices": [{"message": {"content": "A summary."}, "finish_reason": "stop"}]},
})()
monkeypatch.setattr("query_service.model_client.requests.post", request)
first = HostedLLM("Qwen/Qwen3.8-27B", "Hugging Face", "test-key-one")
second = HostedLLM("google/gemma-4-26B-A4B-it", "Hugging Face", "test-key-two")
assert first.complete("First transcript").text == "A summary."
assert second.complete("Second transcript").text == "A summary."
assert all(url == "https://router.huggingface.co/v1/chat/completions" for url, _ in calls)
assert [call[1]["headers"]["Authorization"] for call in calls] == ["Bearer test-key-one", "Bearer test-key-two"]
assert [call[1]["json"]["model"] for call in calls] == ["Qwen/Qwen3.8-27B", "google/gemma-4-26B-A4B-it"]
assert "test-key-one" not in json.dumps(first.to_dict())
assert "test-key-one" not in repr(first)
def test_credit_error_is_actionable_and_does_not_echo_provider_content(monkeypatch):
monkeypatch.setattr("query_service.model_client.requests.post", lambda *a, **k: type(
"Response", (), {"status_code": 402, "text": "secret-provider-debug-data"}
)())
client = HostedLLM("Qwen/Qwen3.8-27B", "Hugging Face", "test-key")
with pytest.raises(ModelRequestError, match="No inference credits remain") as error:
client.complete("A transcript")
assert "secret-provider-debug-data" not in str(error.value)
def test_hugging_face_token_is_not_sent_to_another_provider():
with pytest.raises(ModelRequestError, match="Hugging Face provider"):
HostedLLM("custom-model", "OpenAI", "hf_test_only")
@pytest.mark.parametrize("choice", [
{"message": {"content": ""}, "finish_reason": "stop"},
{"message": {"content": "Incomplete"}, "finish_reason": "length"},
])
def test_empty_or_truncated_generation_is_not_reported_as_success(monkeypatch, choice):
monkeypatch.setattr("query_service.model_client.requests.post", lambda *a, **k: type(
"Response", (), {"status_code": 200, "json": lambda self: {"choices": [choice]}}
)())
with pytest.raises(ModelRequestError):
HostedLLM("custom-model", "Hugging Face", "test-key").complete("A transcript")
def test_summary_and_answers_use_the_supplied_llm_and_local_embeddings(tmp_path, monkeypatch):
import llama_index.llm_predictor.base as predictor
original_resolver = predictor.resolve_llm
def reject_default(llm):
assert llm != "default", "The selected LLM was replaced by a default model"
return original_resolver(llm)
monkeypatch.setattr(predictor, "resolve_llm", reject_default)
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
monkeypatch.setattr("summarization_service.summarizer.output_path_transcription", str(tmp_path))
(tmp_path / "pilot.json").write_text(json.dumps({"text": "The pilot starts on November 5. Maya owns testing."}))
calls = []
def request(url, **kwargs):
calls.append((url, kwargs["json"]))
return type("Response", (), {
"status_code": 200,
"json": lambda self: {"choices": [{"message": {"content": "The pilot starts on November 5; Maya owns testing."}, "finish_reason": "stop"}]},
})()
monkeypatch.setattr("query_service.model_client.requests.post", request)
summary = TranscriptSummary("pilot", "Qwen/Qwen3.8-27B", "Hugging Face", "test-key", embed_model=MockEmbedding(embed_dim=8))
assert "Maya" in summary.get_document_summary()
assert "Maya" in summary.query_summary("Who owns testing?")
assert len(calls) >= 2
assert all(body["model"] == "Qwen/Qwen3.8-27B" for _, body in calls)
assert all(url.startswith("https://router.huggingface.co/") for url, _ in calls)
def test_chroma_index_retains_segment_timestamps_without_an_api_key(tmp_path, monkeypatch):
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
monkeypatch.setattr("config.output_path_transcription", str(tmp_path))
(tmp_path / "clip.json").write_text(json.dumps({"segments": [
{"text": "Maya owns testing.", "start": 2.5, "end": 5},
{"text": "The pilot starts in November.", "start": 6, "end": 10},
]}))
retriever = MediaRetriever("clip", similarity_top_k=2, embed_model=MockEmbedding(embed_dim=8))
results = retriever.search("testing")
assert len(results) == 2
assert {result.node.metadata["start"] for result in results} == {2.5, 6}
assert len(retriever.search("testing", similarity_top_k=1)) == 1