File size: 4,046 Bytes
b0e994e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Protect resumable sidecars from malformed output and transport failures."""

import json
import os
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
import urllib.error

from PIL import Image

import decode_sources as decode


class DecodeSidecarTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.addCleanup(self.temp.cleanup)
        self.root = Path(self.temp.name)
        self.source = self.root / "SKING_DDJ_v54" / "ABC" / "ABC123_source.png"
        self.source.parent.mkdir(parents=True)
        Image.new("RGB", (16, 16), "blue").save(self.source)
        self.output = self.source.with_name("ABC123_decode.json")
        self.decoder = decode.Decoder("http://qwen.invalid/v1", "test-key", "test-model", attempts=1)
        self.patch = patch.object(decode, "DATASET", self.root)
        self.patch.start()
        self.addCleanup(self.patch.stop)

    def test_api_error_does_not_create_a_false_safety_label(self):
        error = urllib.error.HTTPError("http://local", 503, "unavailable", {}, None)
        with patch.object(self.decoder, "request", side_effect=error):
            result = self.decoder.decode(self.source)
        self.assertEqual(result["status"], "error")
        self.assertNotIn("valid", result)
        self.assertFalse(self.output.exists())

    def test_invalid_or_truncated_responses_never_write_sidecars(self):
        cases = [
            ("stop", {"valid": "false", "description": "A blue image."}),
            ("stop", {"valid": True, "description": "word " * 101}),
            ("stop", {"valid": True, "description": "A blue image.", "extra": 1}),
            ("length", {"valid": True, "description": "A blue image."}),
        ]
        for finish, content in cases:
            with self.subTest(finish=finish, content=content):
                response = {"choices": [{"finish_reason": finish, "message": {"content": json.dumps(content)}}]}
                with patch.object(self.decoder, "request", return_value=response):
                    result = self.decoder.decode(self.source)
                self.assertEqual(result["status"], "error")
                self.assertFalse(self.output.exists())

    def test_valid_false_is_saved_and_resume_preserves_existing_result(self):
        value = {"valid": False, "description": "Explicit sexual content."}
        response = {"choices": [{"finish_reason": "stop", "message": {"content": json.dumps(value)}}]}
        with patch.object(self.decoder, "request", return_value=response) as request:
            self.assertEqual(self.decoder.decode(self.source)["status"], "written")
            before = self.output.read_bytes()
            self.assertEqual(self.decoder.decode(self.source)["status"], "skipped")
            request.assert_called_once()
        self.assertEqual(json.loads(before), value)
        self.assertEqual(self.output.read_bytes(), before)


class ConfigTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.addCleanup(self.temp.cleanup)
        self.env_file = Path(self.temp.name) / ".env"
        patcher = patch.object(decode, "ENV_FILE", self.env_file)
        patcher.start()
        self.addCleanup(patcher.stop)
        env = patch.dict(os.environ, {}, clear=True)
        env.start()
        self.addCleanup(env.stop)

    def test_reads_env_file_and_environment_takes_priority(self):
        self.env_file.write_text("# comment\nQWEN_BASE_URL='http://file.invalid/v1/'\nQWEN_API_KEY=file-key\n")
        os.environ["QWEN_API_KEY"] = "shell-key"
        self.assertEqual(decode.qwen_config(), ("http://file.invalid/v1", "shell-key"))

    def test_missing_settings_fail_without_a_default_address(self):
        self.env_file.write_text("QWEN_API_KEY=file-key\n")
        with self.assertRaises(SystemExit) as raised:
            decode.qwen_config()
        self.assertIn("QWEN_BASE_URL", str(raised.exception))


if __name__ == "__main__":
    unittest.main()