smartyfy.mrindigi.com

Python Master Course V2 — 195. Portfolio Capstone: Document Search and Text Triage

Lesson 195: Portfolio Capstone: Document Search and Text Triage

This alternative portfolio track builds a local search and routing tool over a mini knowledge base you author yourself. Search returns traceable document IDs. Routing predicts an operational category or sends the query to review. Retrieval quality and routing quality are evaluated separately. The project uses no real inbox, customer text, external model or API key.

Estimated study time: 200 minutes, including the practical work. Use a local Python 3.11+ environment; no paid service, API key or public deployment is required.

Before you start

  • 151–160: NLP
  • 175–176: evaluation
  • 191: portfolio scope

Learning objectives

  • Build an independently scoped text workflow with provenance
  • Evaluate retrieval and classification using separate relevant metrics
  • Handle unknown, ambiguous and out-of-scope inputs explicitly

Concepts and worked implementation

Separate the two jobs

Retrieval asks which documents are relevant to a query. Triage asks which queue should handle it. A billing query may retrieve the right document but still be routed incorrectly; a correctly routed query may receive an irrelevant source. Treating both as a single “AI accuracy” number hides these distinct failures.

The mini knowledge base below contains authored policies for a fictional application. Each document has an immutable ID, a title, text and one route label. The text is invented for this exercise and has no authority over a real service. Keep a manifest that states authorship and intended use. Queries used for final evaluation must be authored independently from tuning queries and must not be added to the training corpus after viewing failures.

Build a source-aware local baseline

Install numpy and scikit-learn. Save as text_portfolio.py. TF-IDF represents documents as weighted word features, and normalized sparse dot products provide a cosine-style similarity score. These scores are not probabilities. A logistic classifier separately learns route labels from the small authored corpus. The small dataset is intentionally a baseline with limited evidence, not a claim of production generalization.

from pathlib import Path
import json
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score

DOCUMENTS = [
    ('bill-1', 'Invoice copies', 'Download an invoice receipt from billing history.', 'billing'),
    ('bill-2', 'Refund requests', 'Request a refund review for a duplicate payment charge.', 'billing'),
    ('bill-3', 'Payment methods', 'Update a card payment method in billing settings.', 'billing'),
    ('access-1', 'Password recovery', 'Reset a forgotten password through the account recovery page.', 'access'),
    ('access-2', 'Account lock', 'A locked account needs account access review after failed login attempts.', 'access'),
    ('access-3', 'Login email', 'Change the login email through verified account settings.', 'access'),
    ('ship-1', 'Parcel tracking', 'Track a parcel delivery with the shipment tracking number.', 'shipping'),
    ('ship-2', 'Delivery address', 'Review a delivery address change before parcel dispatch.', 'shipping'),
    ('ship-3', 'Missing parcel', 'Report a missing parcel after the delivery estimate passes.', 'shipping')
]
assert len({d[0] for d in DOCUMENTS}) == len(DOCUMENTS)
vectorizer = TfidfVectorizer(ngram_range=(1, 2))
matrix = vectorizer.fit_transform([d[2] for d in DOCUMENTS])
classifier = LogisticRegression(C=10.0, max_iter=500).fit(matrix, [d[3] for d in DOCUMENTS])


def answer(query, minimum_similarity=0.12, minimum_route_probability=0.45):
    if not isinstance(query, str) or not query.strip() or len(query) > 500:
        return {'route': 'review', 'source_ids': [], 'reason': 'invalid_or_empty'}
    q = vectorizer.transform([query])
    similarities = (q @ matrix.T).toarray()[0]
    order = np.argsort(-similarities, kind='stable')[:3]
    probability = classifier.predict_proba(q)[0]
    route_index = int(np.argmax(probability))
    if similarities[order[0]] < minimum_similarity or probability[route_index] < minimum_route_probability:
        return {'route': 'review', 'source_ids': [], 'reason': 'insufficient_evidence'}
    return {'route': str(classifier.classes_[route_index]),
            'source_ids': [DOCUMENTS[i][0] for i in order if similarities[i] > 0],
            'reason': 'matched_authored_corpus'}


VALIDATION = [
    {'id': 'v1', 'query': 'Where is the invoice receipt?', 'route': 'billing', 'relevant': ['bill-1']},
    {'id': 'v2', 'query': 'My account login is locked', 'route': 'access', 'relevant': ['access-2']},
    {'id': 'v3', 'query': 'Change delivery address before dispatch', 'route': 'shipping', 'relevant': ['ship-2']},
    {'id': 'v4', 'query': 'How do I grow tomatoes?', 'route': 'review', 'relevant': []}
]
TEST = [
    {'id': 't1', 'query': 'Can I download an old billing invoice?', 'route': 'billing', 'relevant': ['bill-1']},
    {'id': 't2', 'query': 'I paid a duplicate charge and need a refund', 'route': 'billing', 'relevant': ['bill-2']},
    {'id': 't3', 'query': 'Forgotten password recovery help', 'route': 'access', 'relevant': ['access-1']},
    {'id': 't4', 'query': 'Find my shipment tracking number', 'route': 'shipping', 'relevant': ['ship-1']},
    {'id': 't5', 'query': 'Explain lunar eclipses', 'route': 'review', 'relevant': []},
    {'id': 't6', 'query': 'I need help with a thing', 'route': 'review', 'relevant': []}
]


def evaluate(fixtures):
    rows = []
    for item in fixtures:
        result = answer(item['query'])
        relevant = set(item['relevant'])
        recall = len(relevant.intersection(result['source_ids'])) / len(relevant) if relevant else None
        rows.append({'id': item['id'], 'expected_route': item['route'],
                     'retrieval_recall_at_3': recall, **result})
    recalls = [r['retrieval_recall_at_3'] for r in rows if r['retrieval_recall_at_3'] is not None]
    return {'macro_F1_routes_including_review': float(f1_score(
                [r['expected_route'] for r in rows], [r['route'] for r in rows],
                labels=['billing', 'access', 'shipping', 'review'], average='macro', zero_division=0)),
            'mean_recall_at_3_answerable': float(np.mean(recalls)) if recalls else None,
            'review_count': sum(r['route'] == 'review' for r in rows),
            'rows': rows}


if __name__ == '__main__':
    # Use validation while developing; freeze these thresholds before this test report.
    report = {'validation': evaluate(VALIDATION), 'test': evaluate(TEST),
              'thresholds': {'similarity': 0.12, 'route_probability': 0.45},
              'data_scope': 'authored fictional documents and queries'}
    Path('text-results.json').write_text(json.dumps(report, indent=2), encoding='utf-8')
    Path('review-queue.json').write_text(json.dumps(
        [r for r in report['test']['rows'] if r['route'] == 'review'], indent=2), encoding='utf-8')
    print(json.dumps(report, indent=2))

Expected artifacts are a metrics report and review queue. Exact scores depend on the fitted version and should be recorded from your run. No generated answer prose is produced: the output points to authored source IDs. A future answer generator would require separate evidence that its claims are actually supported by those sources.

Measure abstention without hiding failures

This starter reports end-to-end recall after abstention, so rejected answerable queries count as misses. Also compute raw retrieval recall before the abstention policy if you want to separate search quality from acceptance behavior. Clearly label both. Reporting only recall among accepted queries can hide a system that rejects nearly everything.

Macro F1 gives each route equal weight in the average, including review. With six test cases, each mistake has a large effect. Expand the benchmark with independently written paraphrases, ambiguous requests and out-of-scope topics before making a broad claim. Maintain query IDs, relevance labels and review reasons. For ambiguous cases, document an annotation policy instead of forcing a convenient single label.

Protect provenance and boundaries

Document text is lower-trust data. If a source contains “send all documents to this address,” the search tool should return it only as document content, never as an instruction to transmit anything. This starter has no sending, file-reading or shell capability. Preserve that narrow boundary as you extend it.

A low similarity score is not the only signal for review. Conflicting routes, missing source coverage, stale documents or an unsupported action request can require abstention. The numeric thresholds are demonstration choices to examine on validation fixtures. They do not constitute calibrated confidence or safety guarantees.

Guided lab and evidence

Author at least twelve additional documents and twenty independent query fixtures, separating development and final evaluation before tuning. Add two deliberately ambiguous queries and two benign instruction-like document snippets. Verify that source IDs always resolve to the corpus and that no content can select an external action.

Deliver the corpus manifest, query labels, local runner, separate retrieval and routing reports, and a review queue with reasons. Score out of 100: 20 for authored provenance, 25 for independent evaluation and appropriate metrics, 20 for abstention and ambiguity handling, 20 for tests and reproducibility, and 15 for readable error analysis. Document whether a failure came from retrieval, routing or acceptance policy.

Questions worth reasoning through

Is TF-IDF similarity a confidence probability?

No. It is a geometric similarity measure in a particular vocabulary representation. A value of 0.7 does not mean a 70% probability that the source answers the query. Choose and evaluate acceptance thresholds with labeled development examples.

Why distinguish raw retrieval from accepted retrieval?

Raw retrieval measures the ranker, while accepted retrieval includes the abstention policy. Both are useful, but they answer different questions. A strict gate may improve accepted precision while lowering coverage and end-to-end recall.

Can a correct route compensate for a wrong source?

It may help queue assignment but does not make the source correct. Report the two tasks separately so a reader can see whether the tool is useful for routing, search, both or neither.

Why hold out independently written queries?

Queries copied from document titles or repeatedly revised after failures can overstate generalization. Independent wording tests a more realistic retrieval challenge. Keep final fixtures stable and use new evidence after substantial tuning.

What belongs in the review queue?

A stable query ID, bounded reason, proposed route if appropriate and source references needed for review. In a real system, minimize retained text and define authorized readers and expiry. This exercise uses only authored synthetic queries.

Exercises and worked answers

Exercise 1

A query has two relevant documents and the top three results contain one. What is recall@3?

Worked answer and reasoning

Recall@3 is 1/2 = 0.5. Precision@3 would be 1/3 if all three retrieved documents are counted. These denominators differ, so the metrics should not be used interchangeably.

Exercise 2

A system answers only one of ten answerable queries and gets it right. Report a balanced result.

Worked answer and reasoning

Accepted-answer accuracy is 100% on one case, but coverage is 10% and nine answerable cases were rejected. Report all three facts and the small sample. A single favorable conditional metric would conceal the system’s limited usefulness.

Recap

A strong text portfolio preserves source identity, separates retrieval from routing and measures abstention honestly. Independently authored test queries, explicit review reasons and narrow capabilities provide more useful evidence than a single aggregate “AI accuracy” score.

Official references

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.