item-appraiser 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,53 @@
1
+ """Estimate the value and climate impact of household goods being lent and given away.
2
+
3
+ Pick a model provider by constructing its appraiser; there's no default. With
4
+ the `claude` extra installed and ANTHROPIC_API_KEY set, or the `deepseek` extra
5
+ and DEEPSEEK_API_KEY::
6
+
7
+ from item_appraiser import ClaudeAppraiser, DeepSeekAppraiser, Listing
8
+
9
+ appraiser = ClaudeAppraiser(impacts=["money", "climate"]) # default: money only
10
+ # or: appraiser = DeepSeekAppraiser(impacts=["money", "climate"])
11
+ appraisal = appraiser.appraise(
12
+ Listing(name="Cordless drill", description="18V, two batteries", image_urls=[url])
13
+ )
14
+ appraisal.new_price_usd, appraisal.buy_value_usd, appraisal.loan_value_usd
15
+ appraisal.new_item_kg_co2e, appraisal.giveaway_kg_co2e, appraisal.loan_kg_co2e
16
+ """
17
+
18
+ from item_appraiser._version import __version__
19
+ from item_appraiser.claude import ClaudeAppraiser
20
+ from item_appraiser.climate import giveaway_kg_co2e, loan_kg_co2e, new_item_kg_co2e
21
+ from item_appraiser.deepseek import DeepSeekAppraiser
22
+ from item_appraiser.models import (
23
+ Appraisal,
24
+ AppraisalError,
25
+ Appraiser,
26
+ Condition,
27
+ Confidence,
28
+ FootprintCategory,
29
+ Impact,
30
+ Listing,
31
+ ResaleDemand,
32
+ )
33
+ from item_appraiser.policy import buy_value, loan_value
34
+
35
+ __all__ = [
36
+ "__version__",
37
+ "Appraisal",
38
+ "AppraisalError",
39
+ "Appraiser",
40
+ "ClaudeAppraiser",
41
+ "Condition",
42
+ "Confidence",
43
+ "DeepSeekAppraiser",
44
+ "FootprintCategory",
45
+ "Impact",
46
+ "Listing",
47
+ "ResaleDemand",
48
+ "buy_value",
49
+ "giveaway_kg_co2e",
50
+ "loan_kg_co2e",
51
+ "loan_value",
52
+ "new_item_kg_co2e",
53
+ ]
@@ -0,0 +1,6 @@
1
+ from importlib.metadata import PackageNotFoundError, version
2
+
3
+ try:
4
+ __version__ = version("item-appraiser")
5
+ except PackageNotFoundError: # running from a source tree that isn't installed
6
+ __version__ = "0.0.0"
@@ -0,0 +1,39 @@
1
+ """Trivial appraisers that set the floor any real appraiser has to beat."""
2
+
3
+ from collections import defaultdict
4
+ from collections.abc import Iterable, Mapping
5
+ from statistics import median
6
+
7
+ from item_appraiser.dataset import LabeledItem
8
+ from item_appraiser.models import Appraisal, Condition, Listing
9
+
10
+
11
+ class CategoryMedianAppraiser:
12
+ """Predicts the median new price of training items in the same category.
13
+
14
+ Categories come from the labeled data, looked up by `item_id`, since
15
+ appraisers don't see them. Falls back to the overall median for unseen
16
+ categories, and always guesses USED, the most common condition.
17
+ """
18
+
19
+ model_version = "category-median"
20
+
21
+ def __init__(self, training: Iterable[LabeledItem], categories: Mapping[str, str]):
22
+ by_category = defaultdict(list)
23
+ prices = []
24
+ for item in training:
25
+ by_category[item.category].append(item.label.new_price_usd)
26
+ prices.append(item.label.new_price_usd)
27
+ if not prices:
28
+ raise ValueError("CategoryMedianAppraiser needs at least one training item")
29
+ self.overall = median(prices)
30
+ self.by_category = {category: median(p) for category, p in by_category.items()}
31
+ self.categories = categories
32
+
33
+ def appraise(self, listing: Listing) -> Appraisal:
34
+ category = self.categories.get(listing.item_id or "")
35
+ return Appraisal(
36
+ new_price_usd=self.by_category.get(category, self.overall),
37
+ condition=Condition.USED,
38
+ model_version=self.model_version,
39
+ )
@@ -0,0 +1,39 @@
1
+ """A small on-disk store for model responses, keyed by everything that shaped the request.
2
+
3
+ Provider-neutral: an appraiser builds a JSON-serializable key from the model,
4
+ prompt and listing, and stores whatever record it needs to rebuild an appraisal.
5
+ """
6
+
7
+ import hashlib
8
+ import json
9
+ import os
10
+ from pathlib import Path
11
+
12
+
13
+ def digest(key: dict) -> str:
14
+ """A stable hex digest of a JSON-serializable key."""
15
+ return hashlib.sha256(json.dumps(key, sort_keys=True).encode()).hexdigest()
16
+
17
+
18
+ class ResponseCache:
19
+ def __init__(self, directory: str | os.PathLike):
20
+ self.directory = Path(directory)
21
+
22
+ def path(self, key: dict) -> Path:
23
+ return self.directory / f"{digest(key)}.json"
24
+
25
+ def __contains__(self, key: dict) -> bool:
26
+ return self.path(key).exists()
27
+
28
+ def get(self, key: dict) -> dict | None:
29
+ path = self.path(key)
30
+ if not path.exists():
31
+ return None
32
+ return json.loads(path.read_text(encoding="utf-8"))
33
+
34
+ def put(self, key: dict, record: dict) -> None:
35
+ path = self.path(key)
36
+ path.parent.mkdir(parents=True, exist_ok=True)
37
+ temporary = path.with_suffix(".tmp")
38
+ temporary.write_text(json.dumps(record, indent=1), encoding="utf-8")
39
+ os.replace(temporary, path) # atomic, so a crash never leaves half a record
@@ -0,0 +1,278 @@
1
+ """Appraise listings with Claude.
2
+
3
+ Needs the `claude` extra (`pip install item-appraiser[claude]`) and an
4
+ `ANTHROPIC_API_KEY` in the environment, or a configured `anthropic.Anthropic`
5
+ client passed in.
6
+
7
+ Each listing is one API call: the fixed system prompt, then the photos and the
8
+ listing text, with structured JSON back. With a `cache_dir`, every usable
9
+ response is stored on disk, so appraising the same listing again costs nothing.
10
+ """
11
+
12
+ import json
13
+ from collections.abc import Callable, Iterable
14
+ from dataclasses import dataclass
15
+ from datetime import UTC, datetime
16
+ from os import PathLike
17
+
18
+ try:
19
+ import anthropic
20
+ except ImportError: # the core package works without it; only this appraiser needs it
21
+ anthropic = None
22
+
23
+ from item_appraiser import prompt
24
+ from item_appraiser.cache import ResponseCache, digest
25
+ from item_appraiser.images import image_is_reachable
26
+ from item_appraiser.models import MONEY_ONLY, Appraisal, AppraisalError, Impact, Listing
27
+
28
+ HAIKU = "claude-haiku-5-5"
29
+ SONNET = "claude-sonnet-5-5"
30
+ OPUS = "claude-opus-5-5"
31
+
32
+ # The settings scored on the hand-valued test sets (see the README).
33
+ DEFAULT_MODEL = SONNET
34
+
35
+ EFFORT = "low"
36
+ MAX_TOKENS = 16000 # thinking counts toward this, so leave plenty of room
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class Price:
41
+ """USD per million tokens."""
42
+
43
+ input: float
44
+ output: float
45
+ cache_write: float
46
+ cache_read: float
47
+
48
+
49
+ PRICES = {
50
+ HAIKU: Price(input=0.10, output=0.50, cache_write=0.125, cache_read=0.01),
51
+ SONNET: Price(input=2.00, output=10.00, cache_write=2.50, cache_read=0.20),
52
+ OPUS: Price(input=4.00, output=20.00, cache_write=5.00, cache_read=0.20),
53
+ }
54
+
55
+ # Rough sizes for the pre-run estimate, on the high side so it errs toward overstating.
56
+ ESTIMATED_CHARS_PER_TOKEN = 3
57
+ ESTIMATED_TOKENS_PER_IMAGE = 650 # the largest photos in the test set come to about 640
58
+ ESTIMATED_OUTPUT_TOKENS = 400 # the JSON plus low-effort thinking
59
+
60
+
61
+ def response_text(response: dict) -> str:
62
+ # A response can begin with thinking blocks, so find the answer by type.
63
+ for block in response.get("content", []):
64
+ if block.get("type") == "text":
65
+ return block["text"]
66
+ raise AppraisalError(f"no text in the response (stop_reason {response.get('stop_reason')})")
67
+
68
+
69
+ def usage_cost(usage: dict, price: Price) -> float:
70
+ tokens = (
71
+ usage.get("input_tokens", 0) * price.input
72
+ + usage.get("output_tokens", 0) * price.output
73
+ + (usage.get("cache_creation_input_tokens") or 0) * price.cache_write
74
+ + (usage.get("cache_read_input_tokens") or 0) * price.cache_read
75
+ )
76
+ return tokens / 1_000_000
77
+
78
+
79
+ class ClaudeAppraiser:
80
+ """Appraise listings with one Claude call each.
81
+
82
+ `impacts` chooses what the appraisal is for: "money" (the default, and the
83
+ tested prompt), "climate", or both. Climate adds a footprint category to the
84
+ same call; the new price is estimated either way, since most emission factors
85
+ are per dollar.
86
+
87
+ `appraise()` raises AppraisalError when the model gives no usable answer for a
88
+ listing, or the API rejects or fails that one request; other listings may
89
+ still succeed. Authentication and permission errors propagate unchanged.
90
+
91
+ Any Claude model works. Costs are tracked for the models in `PRICES`; for
92
+ another model, pass its `price` or go without cost tracking.
93
+ """
94
+
95
+ def __init__(
96
+ self,
97
+ model: str = DEFAULT_MODEL,
98
+ use_images: bool = True,
99
+ use_quantity: bool = True,
100
+ cache_dir: str | PathLike | None = None,
101
+ client: "anthropic.Anthropic | None" = None,
102
+ image_check: Callable[[str], bool] | None = None,
103
+ impacts: Iterable[Impact | str] = MONEY_ONLY,
104
+ price: Price | None = None,
105
+ ):
106
+ if client is None and anthropic is None:
107
+ raise ImportError(
108
+ "ClaudeAppraiser needs the anthropic package: pip install 'item-appraiser[claude]'"
109
+ )
110
+ self.model = model
111
+ self.price = price or PRICES.get(model) # None: costs aren't tracked
112
+ self.use_images = use_images
113
+ self.use_quantity = use_quantity
114
+ self.impacts = prompt.normalize_impacts(impacts)
115
+ self.cache = ResponseCache(cache_dir) if cache_dir is not None else None
116
+ self.model_version = (
117
+ f"{model}/{prompt.PROMPT_VERSION}"
118
+ f"+{'img' if use_images else 'text'}+{'qty' if use_quantity else 'total'}"
119
+ )
120
+ if Impact.CLIMATE in self.impacts:
121
+ self.model_version += f"+co2-{prompt.FOOTPRINT_VERSION}"
122
+ # What this object paid for, including unusable responses; stays 0 without a price.
123
+ self.spent_usd = 0.0
124
+ self._client = client
125
+ self._image_check = image_check or image_is_reachable
126
+ self._system = prompt.system_prompt(use_quantity, self.impacts)
127
+ self._schema = prompt.output_schema(use_quantity, self.impacts)
128
+
129
+ @property
130
+ def client(self) -> "anthropic.Anthropic":
131
+ # Built on first use, so answering from the cache needs no API key.
132
+ if self._client is None:
133
+ self._client = anthropic.Anthropic()
134
+ return self._client
135
+
136
+ def _image_urls(self, listing: Listing) -> tuple[str, ...]:
137
+ return listing.image_urls if self.use_images else ()
138
+
139
+ def _cache_key(self, listing: Listing) -> dict:
140
+ """Everything that shapes the request, so any change to it misses the cache."""
141
+ urls = self._image_urls(listing)
142
+ key = {
143
+ "model": self.model,
144
+ "prompt_version": prompt.PROMPT_VERSION,
145
+ "effort": EFFORT,
146
+ "system": self._system,
147
+ "schema": self._schema,
148
+ "image_urls": list(urls),
149
+ "text": prompt.listing_text(listing, len(urls)),
150
+ }
151
+ # The system prompt and schema already differ by impact; this is for anyone
152
+ # reading the key. Money-only keys stay as they were, so old responses still hit.
153
+ if Impact.CLIMATE in self.impacts:
154
+ key["footprint_version"] = prompt.FOOTPRINT_VERSION
155
+ return key
156
+
157
+ def fingerprint(self, listing: Listing) -> str:
158
+ """Identifies everything a fresh appraisal of `listing` would depend on.
159
+
160
+ The same value is stored on each `Appraisal`; when they differ, the listing
161
+ (name, description, photos) or the appraiser's model or prompt has changed
162
+ since it was estimated.
163
+ """
164
+ return digest(self._cache_key(listing))
165
+
166
+ def _require_price(self) -> Price:
167
+ if self.price is None:
168
+ raise ValueError(f"no pricing for model {self.model}; pass price= to track costs")
169
+ return self.price
170
+
171
+ def uncached(self, listings: Iterable[Listing]) -> list[Listing]:
172
+ """The listings that would need an API call (all of them, without a cache)."""
173
+ if self.cache is None:
174
+ return list(listings)
175
+ return [listing for listing in listings if self._cache_key(listing) not in self.cache]
176
+
177
+ def estimate_cost(self, listings: Iterable[Listing]) -> float:
178
+ """Upper-end USD estimate for calling the API on `listings`, ignoring prompt caching."""
179
+ price = self._require_price()
180
+ prompt_chars = len(self._system) + len(json.dumps(self._schema))
181
+ total = 0.0
182
+ for listing in listings:
183
+ images = len(self._image_urls(listing))
184
+ chars = prompt_chars + len(prompt.listing_text(listing, images))
185
+ input_tokens = chars / ESTIMATED_CHARS_PER_TOKEN + images * ESTIMATED_TOKENS_PER_IMAGE
186
+ total += input_tokens * price.input + ESTIMATED_OUTPUT_TOKENS * price.output
187
+ return total / 1_000_000
188
+
189
+ def stored_cost(self, listings: Iterable[Listing]) -> float:
190
+ """What the cached responses for `listings` cost when they were made."""
191
+ price = self._require_price()
192
+ if self.cache is None:
193
+ return 0.0
194
+ total = 0.0
195
+ for listing in listings:
196
+ record = self.cache.get(self._cache_key(listing))
197
+ if record is not None:
198
+ total += usage_cost(record["response"].get("usage", {}), price)
199
+ return total
200
+
201
+ def _request(self, listing: Listing, urls: tuple[str, ...]) -> dict:
202
+ images = [{"type": "image", "source": {"type": "url", "url": url}} for url in urls]
203
+ return {
204
+ "model": self.model,
205
+ "max_tokens": MAX_TOKENS,
206
+ "system": [
207
+ {"type": "text", "text": self._system, "cache_control": {"type": "ephemeral"}}
208
+ ],
209
+ "messages": [
210
+ {
211
+ "role": "user",
212
+ "content": [
213
+ *images,
214
+ {"type": "text", "text": prompt.listing_text(listing, len(urls))},
215
+ ],
216
+ }
217
+ ],
218
+ "output_config": {
219
+ "effort": EFFORT,
220
+ "format": {"type": "json_schema", "schema": self._schema},
221
+ },
222
+ }
223
+
224
+ def _call_api(self, listing: Listing) -> dict:
225
+ urls = self._image_urls(listing)
226
+ reachable = tuple(url for url in urls if self._image_check(url))
227
+ retryable = (
228
+ (
229
+ anthropic.BadRequestError,
230
+ anthropic.RateLimitError,
231
+ anthropic.InternalServerError,
232
+ anthropic.APIConnectionError,
233
+ )
234
+ if anthropic is not None
235
+ else ()
236
+ )
237
+ try:
238
+ message = self.client.messages.create(**self._request(listing, reachable))
239
+ except retryable as e:
240
+ raise AppraisalError(f"API error: {e}") from e
241
+ response = message.model_dump(mode="json")
242
+ if self.price is not None:
243
+ self.spent_usd += usage_cost(response.get("usage", {}), self.price)
244
+ return {
245
+ "model_version": self.model_version,
246
+ "created_at": datetime.now(UTC).isoformat(),
247
+ "images_sent": len(reachable),
248
+ "images_unreachable": len(urls) - len(reachable),
249
+ "response": response,
250
+ }
251
+
252
+ def _parse(self, record: dict, fingerprint: str) -> Appraisal:
253
+ response = record["response"]
254
+ if response.get("stop_reason") != "end_turn":
255
+ raise AppraisalError(f"stopped early: {response.get('stop_reason')}")
256
+ try:
257
+ return prompt.parse_output(
258
+ json.loads(response_text(response)),
259
+ self.use_quantity,
260
+ self.impacts,
261
+ model_version=record["model_version"],
262
+ estimated_at=datetime.fromisoformat(record["created_at"]),
263
+ fingerprint=fingerprint,
264
+ )
265
+ except (json.JSONDecodeError, KeyError, TypeError, ValueError) as e:
266
+ raise AppraisalError(f"unusable output: {e!r}") from e
267
+
268
+ def appraise(self, listing: Listing) -> Appraisal:
269
+ key = self._cache_key(listing)
270
+ fingerprint = digest(key)
271
+ if self.cache is not None and (record := self.cache.get(key)) is not None:
272
+ return self._parse(record, fingerprint)
273
+ record = self._call_api(listing)
274
+ # Only usable responses are stored, so failures are retried next time.
275
+ appraisal = self._parse(record, fingerprint)
276
+ if self.cache is not None:
277
+ self.cache.put(key, record)
278
+ return appraisal