"""AI orchestrator Lambda for the integrated lab. Routes incoming S3 events to one AWS AI service based on the input folder prefix and writes the result to ``output//`` in the same bucket. Designed for Lab 06: Integrated AI Solution. Routing (one service per file, no chaining): - input/images/. -> Rekognition labels + faces -> output/vision/.json - input/documents/. -> Textract text detection -> output/vision/.json - input/text/. -> Comprehend sentiment + key phrases -> output/language/.json - input/audio/. -> starts a Transcribe job; Transcribe writes output/speech/.json when it finishes Environment variables (set by the lambda component): - LOG_LEVEL: Python logging level (default INFO) - OUTPUT_BUCKET: target bucket for results (defaults to event source bucket) - OUTPUT_PREFIX: folder prefix for results (default ``output/``) """ from __future__ import annotations import json import logging import os import urllib.parse import uuid from datetime import datetime, timezone from typing import Any import boto3 LOG = logging.getLogger() LOG.setLevel(os.environ.get("LOG_LEVEL", "INFO")) OUTPUT_PREFIX = os.environ.get("OUTPUT_PREFIX", "output/").rstrip("/") + "/" # Comprehend DetectSentiment accepts at most 5000 bytes of UTF-8 text per # call. We Range-fetch only that many bytes so a huge text file cannot exhaust # Lambda memory, then trim by bytes (not characters) before calling Comprehend. TEXT_BYTE_CAP = 5000 # Transcribe supports a fixed set of media formats. Anything else falls back # to mp3 - Transcribe then accepts or rejects the file based on its content. _TRANSCRIBE_FORMATS = {"mp3", "mp4", "wav", "flac", "ogg", "amr", "webm", "m4a"} s3 = boto3.client("s3") rekognition = boto3.client("rekognition") textract = boto3.client("textract") comprehend = boto3.client("comprehend") transcribe = boto3.client("transcribe") def handler(event: dict[str, Any], context: Any) -> dict[str, Any]: """Entry point for S3 ObjectCreated events.""" LOG.info("event=%s", json.dumps(event)[:2000]) results = [] for record in event.get("Records", []): bucket = record["s3"]["bucket"]["name"] key = urllib.parse.unquote_plus(record["s3"]["object"]["key"]) size = record["s3"]["object"].get("size") if key.endswith("/") or size == 0: # Folder placeholders and empty uploads have nothing to analyze. LOG.info("skipping empty object or folder marker %s", key) results.append({"key": key, "skipped": True}) continue try: results.append(_route(bucket, key)) except Exception as exc: # noqa: BLE001 - surface in logs, keep loop alive LOG.exception("processing failed for s3://%s/%s: %s", bucket, key, exc) results.append({"key": key, "error": str(exc)}) return {"statusCode": 200, "results": results} def _route(bucket: str, key: str) -> dict[str, Any]: if key.startswith("input/images/"): return _process_image(bucket, key) if key.startswith("input/documents/"): return _process_document(bucket, key) if key.startswith("input/audio/"): return _process_audio(bucket, key) if key.startswith("input/text/"): return _process_text(bucket, key) LOG.info("ignoring %s - no router match", key) return {"key": key, "skipped": True} def _process_image(bucket: str, key: str) -> dict[str, Any]: """Detect labels + faces with Rekognition.""" labels = rekognition.detect_labels( Image={"S3Object": {"Bucket": bucket, "Name": key}}, MaxLabels=10, ) faces = rekognition.detect_faces( Image={"S3Object": {"Bucket": bucket, "Name": key}}, Attributes=["DEFAULT"], ) payload = { "source": f"{bucket}/{key}", "labels": _strip_metadata(labels).get("Labels", []), "faces": _strip_metadata(faces).get("FaceDetails", []), "timestamp": _now(), } return _write_output(bucket, key, "vision", payload) def _process_document(bucket: str, key: str) -> dict[str, Any]: """Extract text with Textract (sync API: JPEG, PNG, TIFF, single-page PDF).""" response = textract.detect_document_text( Document={"S3Object": {"Bucket": bucket, "Name": key}}, ) blocks = response.get("Blocks", []) text = "\n".join(b["Text"] for b in blocks if b.get("BlockType") == "LINE") payload = { "source": f"{bucket}/{key}", "text": text, "block_count": len(blocks), "timestamp": _now(), } return _write_output(bucket, key, "vision", payload) def _process_audio(bucket: str, key: str) -> dict[str, Any]: """Start an async transcription job. Transcribe writes the transcript to ``output/speech/.json`` when the job finishes (OutputKey ends with "/", so Transcribe appends the job name). The Lambda does not wait for the job. The job name includes a UUID so simultaneous events (S3 at-least-once retries, bursts within the same second) produce distinct jobs instead of colliding with ``ConflictException``. """ job_name = f"orchestrator-{int(datetime.now(timezone.utc).timestamp())}-{uuid.uuid4().hex[:8]}" media_format = _media_format_from_key(key) transcribe.start_transcription_job( TranscriptionJobName=job_name, Media={"MediaFileUri": f"s3://{bucket}/{key}"}, MediaFormat=media_format, LanguageCode="en-US", OutputBucketName=bucket, OutputKey=f"{OUTPUT_PREFIX}speech/", ) return {"source": f"{bucket}/{key}", "job_name": job_name, "service": "transcribe"} def _media_format_from_key(key: str) -> str: """Pick a Transcribe-supported format from the S3 key's extension. Looks only at the file basename (not the full key) so a directory named "foo.bar/baz" doesn't get mistaken for an extension. Falls back to "mp3" when there is no extension or the extension isn't in the supported set. """ basename = key.rsplit("/", 1)[-1] if "." not in basename: return "mp3" ext = basename.rsplit(".", 1)[-1].lower() return ext if ext in _TRANSCRIBE_FORMATS else "mp3" def _truncate_utf8(text: str, max_bytes: int) -> str: """Trim ``text`` so its UTF-8 encoding is at most ``max_bytes`` bytes. Drops a multi-byte character that would be cut in half instead of producing invalid UTF-8. """ encoded = text.encode("utf-8") if len(encoded) <= max_bytes: return text return encoded[:max_bytes].decode("utf-8", errors="ignore") def _process_text(bucket: str, key: str) -> dict[str, Any]: """Run sentiment + key-phrase analysis with Comprehend. Range-fetches only the first ``TEXT_BYTE_CAP`` bytes instead of pulling the whole object, then trims by UTF-8 bytes to stay within the Comprehend per-call limit. """ obj = s3.get_object(Bucket=bucket, Key=key, Range=f"bytes=0-{TEXT_BYTE_CAP - 1}") raw = obj["Body"].read() # The range can end in the middle of a multi-byte character; "ignore" # drops that partial character instead of adding a replacement char. body = _truncate_utf8(raw.decode("utf-8", errors="ignore"), TEXT_BYTE_CAP) if not body.strip(): LOG.info("skipping %s - no text to analyze", key) return {"key": key, "skipped": True} sentiment = comprehend.detect_sentiment(Text=body, LanguageCode="en") key_phrases = comprehend.detect_key_phrases(Text=body, LanguageCode="en") payload = { "source": f"{bucket}/{key}", "sentiment": _strip_metadata(sentiment), "key_phrases": _strip_metadata(key_phrases).get("KeyPhrases", []), "timestamp": _now(), } return _write_output(bucket, key, "language", payload) def _write_output(bucket: str, src_key: str, service: str, payload: dict[str, Any]) -> dict[str, Any]: """Write ``payload`` as JSON to ``output//.json``. ```` is the source file name without its extension, so input/images/cat.jpg becomes output/vision/cat.json. Two inputs with the same base name in the same service folder overwrite each other. """ target_bucket = os.environ.get("OUTPUT_BUCKET") or bucket base = src_key.split("/")[-1].rsplit(".", 1)[0] out_key = f"{OUTPUT_PREFIX}{service}/{base}.json" s3.put_object( Bucket=target_bucket, Key=out_key, Body=json.dumps(payload, default=str).encode("utf-8"), ContentType="application/json", ) LOG.info("wrote s3://%s/%s", target_bucket, out_key) return {"source": f"{bucket}/{src_key}", "output": f"{target_bucket}/{out_key}"} def _strip_metadata(response: dict[str, Any]) -> dict[str, Any]: """Return a shallow copy of an AWS API response without ``ResponseMetadata``.""" return {k: v for k, v in response.items() if k != "ResponseMetadata"} def _now() -> str: return datetime.now(timezone.utc).isoformat()