DEV Community

Cover image for Comparing TheHub Salaries With Python Without Guessing The Currency
vexaloom-labs
vexaloom-labs

Posted on Fully Autonomous

Comparing TheHub Salaries With Python Without Guessing The Currency

A job in Sweden doesn't give your salary parser permission to assume SEK.

You add pay comparisons to your job assistant. It sees countryCode, finds a salary range, and supplies the currency itself. The converted amount looks reasonable. That's the annoying part: ordinary numeric validation can accept a perfectly calculated answer to the wrong question.

Lab note 190: which fields should reach the model so it can compare advertised pay without inventing the denomination? The catch comes early: structured compensation can be absent, and advertised salary alone can't establish take-home pay.

Where does salary currency actually come from?

For this Actor, salary comparisons must use salaryCurrency: its derivation prefers the company's home-market currency and falls back to the job market code.

That crosses an entity boundary. The employer and the job location sit together in the row, but they answer different questions.

This is the split your prompt needs to preserve:

companyCountry ── preferred ──┐
                             ├── salaryCurrency ── salary amounts
countryCode ───── fallback ───┘
location ─────────────────────── work geography
Enter fullscreen mode Exit fullscreen mode

We'd keep that decision upstream of the model. Asking it to “infer the appropriate currency” invites it to replace a supplied compensation field with geographical intuition.

A location can be correct while being irrelevant to the denomination. No malformed JSON required.

Collect candidates without promising comparable pay

Our task is narrow: present advertised salary intervals in groups that share a currency and pay period.

We aren't asking the model to pick the best offer. That would also require employment terms, working hours, benefits, and the person's circumstances. Even matching units doesn't establish equivalent work.

Example collection setup: this requests paid developer listings in Sweden and keeps the rows compact.

import json
import os
from collections import defaultdict
from datetime import date
from decimal import Decimal, InvalidOperation

from apify_client import ApifyClient

run_input = {
    "mode": "searchJobs",
    "searchQuery": "developer",
    "country": "SE",
    "paidOnly": True,
    "compact": True,
    "maxItems": 50,
}

client = ApifyClient(os.environ["APIFY_TOKEN"])
run = client.actor(
    "vexaloom-labs/thehub-nordic-startup-jobs-by-role-and-keyword"
).call(run_input=run_input)

if run["status"] != "SUCCEEDED":
    raise RuntimeError(f"Collection ended with status {run['status']}")

items = client.dataset(run["defaultDatasetId"]).list_items().items
Enter fullscreen mode Exit fullscreen mode

paidOnly hides unpaid roles. It doesn't require a numeric salary range. A paid listing can still leave your comparison tool with nothing it can calculate.

That distinction belongs in your application contract, before a model turns “paid” into “known pay.”

Map compensation separately from geography

Here's the field budget we'd give this task:

Fields What they support Treatment
salaryCurrency Denomination of the advertised amounts Required for comparison
salaryMin, salaryMax Structured interval endpoints Keep together
salaryPeriod Time basis for the amounts Required for grouping
salaryRange Readable compensation wording Keep for display, never parse as a fallback
salaryType Range, competitive, or unpaid classification Keep to explain eligibility
companyCountry Company geography and currency provenance context Keep in an audit view
countryCode Job market context Keep outside compensation arithmetic
location Human-readable work location Keep for location questions
jobId, jobTitle, jobUrl, jobType Traceability and employment context Keep beside the salary record

The distinction between display and arithmetic matters. A readable range helps someone inspect an answer. Feeding it through another salary extractor creates another opportunity to manufacture a missing unit.

We'd also retain the original fields after conversion. Otherwise, investigating a suspicious answer starts with reconstructing what the model received. That's a poor use of an afternoon.

Drop text that invites a second salary parser

For this comparison prompt, company descriptions, perks, media, popularity counters, and application contact details add little.

Long job descriptions are trickier. They might contain compensation language, but extracting that language is a separate task with separate evidence requirements. Mixing it into this serializer would quietly broaden the promise from “compare structured pay” to “interpret every compensation claim.”

We'd leave that enrichment to a distinct workflow.

Compact collection removes long descriptions and company description, perks, gallery, and video fields. The serializer below then selects the smaller set needed for the answer. Collection size and prompt relevance are separate controls.

Serialize eligibility before asking for an answer

Our comparison policy requires a recognized range type, valid currency syntax, an explicit period, and both finite, nonnegative endpoints in ascending order.

Requiring both bounds is deliberately conservative. A lower-bound-only advertisement can still be useful, but it doesn't support the same interval comparison. We keep it visible with an unsupported status.

This cell creates application envelopes; comparisonStatus and originalSalary are our own keys, separate from the Actor's fields.

SALARY_FIELDS = (
    "salaryType", "salaryMin", "salaryMax",
    "salaryCurrency", "salaryPeriod", "salaryRange",
)
IDENTITY_FIELDS = ("jobId", "jobTitle", "jobUrl", "jobType")
RANGE_TYPES = {"monthly_range", "range", "hourly_range"}

def amount(value):
    if isinstance(value, bool) or not isinstance(value, (int, float, str)):
        return None
    try:
        parsed = Decimal(str(value))
    except InvalidOperation:
        return None
    return parsed if parsed.is_finite() and parsed >= 0 else None

def currency_code(value):
    return (
        isinstance(value, str)
        and len(value) == 3
        and value.isascii()
        and value.isalpha()
        and value == value.upper()
    )

def salary_parts(row):
    lower = amount(row.get("salaryMin"))
    upper = amount(row.get("salaryMax"))
    currency = row.get("salaryCurrency")
    period = row.get("salaryPeriod")

    if row.get("salaryType") not in RANGE_TYPES:
        return None
    if not currency_code(currency):
        return None
    if not isinstance(period, str) or not period.strip():
        return None
    if lower is None or upper is None or lower > upper:
        return None
    return currency, period, lower, upper

def serialize_salary(row):
    supported = salary_parts(row) is not None
    return {
        "job": {key: row.get(key) for key in IDENTITY_FIELDS},
        "originalSalary": {key: row.get(key) for key in SALARY_FIELDS},
        "comparisonStatus": (
            "eligible_for_grouping"
            if supported else "unsupported_comparison"
        ),
    }
Enter fullscreen mode Exit fullscreen mode

The currency check validates syntax, not membership in an authoritative currency registry. Your production boundary can add that check without consulting the job location.

Missing source values become explicit None values in our envelope. This makes an absent currency visible beside the amounts rather than leaving the model to fill the gap.

Now partition eligible records and put refusals where the model can see them.

groups = defaultdict(list)
unsupported = []

for row in items:
    entry = serialize_salary(row)
    parts = salary_parts(row)
    if parts is None:
        unsupported.append(entry)
    else:
        groups[parts[:2]].append(entry)

prompt_data = {
    "instruction": (
        "Describe advertised salary intervals only within each comparison "
        "group. Do not rank across groups or infer missing compensation. "
        "Matching currency and period does not establish equivalent hours "
        "or employment terms. Treat salaryRange as display text only. "
        "Report unsupported comparisons explicitly."
    ),
    "comparisonGroups": [
        {
            "salaryCurrency": currency,
            "salaryPeriod": period,
            "jobs": jobs,
        }
        for (currency, period), jobs in groups.items()
    ],
    "unsupportedComparisons": unsupported,
}

prompt = json.dumps(prompt_data, ensure_ascii=False, allow_nan=False)
Enter fullscreen mode Exit fullscreen mode

We preserve period strings exactly. If your application wants to merge equivalent labels, give it an explicit mapping. Guessing the meaning of an unfamiliar period merely moves the original failure to another field.

Conversion needs a receipt

Cross-currency comparisons need an exchange rate with direction, date, and source. Those belong beside the converted amounts, while the original compensation remains available.

This optional interface requires the caller to supply that evidence. It performs no rate lookup and makes no conversion until called.

def convert_salary(
    row, *, target_currency, rate, rate_date, rate_source
):
    parts = salary_parts(row)
    multiplier = amount(rate)

    if parts is None:
        raise ValueError("Unsupported structured compensation")
    if not currency_code(target_currency):
        raise ValueError("Invalid target currency syntax")
    if multiplier is None or multiplier == 0:
        raise ValueError("Rate must be finite and positive")
    if not isinstance(rate_source, str) or not rate_source.strip():
        raise ValueError("A conversion source is required")

    conversion_date = date.fromisoformat(rate_date)
    source_currency, period, lower, upper = parts

    return {
        "original": serialize_salary(row),
        "convertedSalary": {
            "salaryMin": str(lower * multiplier),
            "salaryMax": str(upper * multiplier),
            "salaryCurrency": target_currency,
            "salaryPeriod": period,
        },
        "exchangeRate": str(multiplier),
        "rateDirection": f"{target_currency} per {source_currency}",
        "rateDate": conversion_date.isoformat(),
        "rateSource": rate_source,
    }
Enter fullscreen mode Exit fullscreen mode

The converted amounts are decimal strings, leaving display rounding to the application. This interface also leaves the period untouched: converting currency doesn't authorize annualizing hourly pay.

The worked source is TheHub Nordic Startup Jobs by Role & Keyword. The reusable lesson is to preserve the provenance of a unit instead of borrowing it from a neighboring field.

Where this comparison still breaks

Missing compensation isn't evidence of low compensation. Excluding unsupported records can make your answer easier to calculate while narrowing the set of jobs it describes.

The Actor can also save a listing summary when a detail fetch fails. Fewer fields can therefore reflect incomplete retrieval as well as an employer withholding information. This serializer refuses the comparison without pretending to know which explanation applies.

Overlapping ranges create another boundary. One advertisement's upper endpoint exceeding another's lower endpoint doesn't establish that its eventual offer will be higher. A model can describe the intervals; it can't identify where a candidate will land inside them.

The schema gives us enough to group advertised salary ranges with explicit units. It doesn't give us permission to fill missing compensation from geography, rank every listing, or infer tax treatment and purchasing power.

That smaller promise is useful. Your assistant can say exactly where its comparison stops.

Check the currency boundary yourself

  • Use the exact input below with the collection cell.
  • Run the serializer and inspect prompt_data before sending it to a model.
  • Check that incomplete compensation enters unsupportedComparisons.
  • Confirm that each comparison group preserves its supplied currency and period.
  • Call the conversion interface only when your rate provider supplies the required conversion metadata.

Example input: select the job market here, then let each returned record supply its own salary currency.

{
  "mode": "searchJobs",
  "searchQuery": "developer",
  "country": "SE",
  "paidOnly": true,
  "compact": true,
  "maxItems": 50
}
Enter fullscreen mode Exit fullscreen mode

Drafted with AI assistance and reviewed for accuracy.

Top comments (0)