(null);
+
+ async function sync() {
+ setState("working");
+ const res = await fetch("/api/organizer/index", { method: "POST", headers: { "Content-Type": "application/json" } });
+ if (!res.ok) return setState("failed");
+ setAssets(((await res.json()) as { assets: Asset[] }).assets);
+ setState("idle");
+ }
+
+ return (
+
+
+
+
+ Cloudinary asset index
+
+
Tag every session in Cloudinary with its concepts and details, then query them with the Search API.
+
+
+ {state === "working" ? "Syncing…" : assets ? "Sync again" : "Sync tags"}
+
+
+ {state === "failed" && Couldn't sync. Check that you're signed in as an organizer.
}
+ {assets && (
+ <>
+
+ Cloudinary's Search API found {assets.length} tagged {assets.length === 1 ? "asset" : "assets"}.
+
+
+ >
+ )}
+
+ );
+}
diff --git a/src/components/Studio.tsx b/src/components/Studio.tsx
index 049b7fb..fe05325 100644
--- a/src/components/Studio.tsx
+++ b/src/components/Studio.tsx
@@ -3,6 +3,7 @@
import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
+import { CloudinaryIndex } from "@/components/CloudinaryIndex";
import { EmbedCode } from "@/components/EmbedCode";
import { InsightsPanel } from "@/components/InsightsPanel";
import { StatusBadge } from "@/components/StatusBadge";
@@ -114,6 +115,7 @@ export function Studio({ demo = false }: { demo?: boolean }) {
) : (
<>
+ {!demo && }
): string[] {
+ const tags = [ROOT_TAG, ...(language ? [`lang-${language.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`] : [])];
+ for (const name of concepts) {
+ const key = conceptKey(name);
+ if (key) tags.push(`concept-${key}`);
+ }
+ return [...new Set(tags)].slice(0, MAX_TAGS);
+}
+
+// Cloudinary's context syntax: key=value pairs joined by |, with = and | escaped inside a value.
+const escapeValue = (v: string) => v.replace(/([=|\\])/g, "\\$1").replace(/\s+/g, " ").trim().slice(0, 250);
+
+export function assetContext(facts: AssetFacts): string {
+ const pairs: [string, string | null][] = [
+ ["title", facts.title],
+ ["speaker", facts.speaker],
+ ["language", facts.language],
+ ["concepts", facts.concepts.join(", ")],
+ ["moments", String(facts.moments)],
+ ];
+ return pairs
+ .filter(([, v]) => v)
+ .map(([k, v]) => `${k}=${escapeValue(v!)}`)
+ .join("|");
+}
diff --git a/src/lib/cloudinary-index.ts b/src/lib/cloudinary-index.ts
new file mode 100644
index 0000000..eeebcc6
--- /dev/null
+++ b/src/lib/cloudinary-index.ts
@@ -0,0 +1,64 @@
+import "server-only";
+
+import { assetContext, assetTags, ROOT_TAG } from "@/lib/asset-metadata";
+import { cld } from "@/lib/cloudinary";
+import { query } from "@/lib/db";
+import type { Lecture } from "@/lib/lectures";
+import { log } from "@/lib/log";
+import type { StudyPack } from "@/lib/study-pack-schema";
+
+// Tags and contextual metadata on the Cloudinary asset itself: the media library stays organised and
+// searchable in Cloudinary even without our database. Best-effort, like every polish step (NFR4).
+export async function syncAssetMetadata(lecture: Pick, pack: StudyPack): Promise {
+ try {
+ const [row] = await query<{ language: string | null; moments: string }>(
+ `SELECT language, (SELECT count(*) FROM segments WHERE lecture_id = $1) AS moments FROM lectures WHERE id = $1`,
+ [lecture.id],
+ );
+ const facts = {
+ title: lecture.title,
+ speaker: lecture.speaker,
+ language: row?.language ?? null,
+ concepts: pack.concepts.map((c) => c.name),
+ moments: Number(row?.moments ?? 0),
+ };
+ const tags = assetTags(facts);
+ const options = { resource_type: "video" as const };
+ await cld().uploader.add_tag(tags.join(","), [lecture.publicId], options);
+ await cld().uploader.add_context(assetContext(facts), [lecture.publicId], options);
+ log("cloudinary.index.synced", { lectureId: lecture.id, tags: tags.length });
+ return true;
+ } catch (error) {
+ log("cloudinary.index.failed", { lectureId: lecture.id, error: error instanceof Error ? error.message.slice(0, 160) : String(error) });
+ return false;
+ }
+}
+
+export type IndexedAsset = { publicId: string; tags: string[]; context: Record };
+
+// Cloudinary's Search API over our assets: everything tagged "pravaha", optionally narrowed to one tag.
+export async function searchAssets(tag?: string): Promise {
+ const expression = `resource_type:video AND tags=${ROOT_TAG}${tag ? ` AND tags=${tag}` : ""}`;
+ const result = await cld().search.expression(expression).with_field(["tags", "context"]).max_results(50).execute();
+ type Resource = { public_id: string; tags?: string[]; context?: Record };
+ return ((result.resources ?? []) as Resource[]).map((r) => ({ publicId: r.public_id, tags: r.tags ?? [], context: contextOf(r.context) }));
+}
+
+// Organizer backfill: tag every session that already has a Study Pack.
+export async function syncAllAssets(): Promise<{ synced: number; skipped: number }> {
+ const rows = await query<{ id: string; public_id: string; title: string; speaker: string | null; pack: StudyPack }>(
+ `SELECT l.id, l.public_id, l.title, l.speaker, sp.pack
+ FROM study_packs sp JOIN lectures l ON l.id = sp.lecture_id WHERE l.trial_expires_at IS NULL`,
+ );
+ let synced = 0;
+ for (const r of rows) {
+ if (await syncAssetMetadata({ id: r.id, publicId: r.public_id, title: r.title, speaker: r.speaker }, r.pack)) synced++;
+ }
+ return { synced, skipped: rows.length - synced };
+}
+
+// The Search API returns contextual metadata flat; the Admin API nests it under "custom".
+function contextOf(context: Record | undefined): Record {
+ const flat = (context?.custom ?? context ?? {}) as Record;
+ return Object.fromEntries(Object.entries(flat).filter(([, v]) => typeof v === "string")) as Record;
+}
diff --git a/src/lib/study-packs.ts b/src/lib/study-packs.ts
index 9ec0008..7f867ef 100644
--- a/src/lib/study-packs.ts
+++ b/src/lib/study-packs.ts
@@ -1,6 +1,7 @@
import "server-only";
import { generateJson } from "@/lib/ai";
+import { syncAssetMetadata } from "@/lib/cloudinary-index";
import { query } from "@/lib/db";
import { formatTime } from "@/lib/format";
import { getSegments, type Lecture } from "@/lib/lectures";
@@ -36,6 +37,7 @@ export async function generateStudyPack(lecture: Lecture): Promise {
+ it("tags the root, the language and each concept, with no commas or spaces", () => {
+ const tags = assetTags({ language: "en-US", concepts: ["Overfitting", "Learning Rate Influence"] });
+ expect(tags).toEqual(["pravaha", "lang-en-us", "concept-overfitting", "concept-influence-learning-rate"]);
+ expect(tags.every((t) => !/[,\s]/.test(t))).toBe(true);
+ });
+
+ it("dedupes and caps the tag count", () => {
+ const concepts = Array.from({ length: 20 }, (_, i) => `Concept ${i}`);
+ expect(assetTags({ language: null, concepts })).toHaveLength(MAX_TAGS);
+ expect(assetTags({ language: null, concepts: ["Momentum", "momentum"] })).toEqual(["pravaha", "concept-momentum"]);
+ });
+});
+
+describe("assetContext", () => {
+ it("joins key=value pairs with | and omits empty values", () => {
+ expect(assetContext({ title: "Lecture 1", speaker: null, language: "en", concepts: ["A", "B"], moments: 12 })).toBe(
+ "title=Lecture 1|language=en|concepts=A, B|moments=12",
+ );
+ });
+
+ it("escapes the separators inside a value", () => {
+ const context = assetContext({ title: "a=b|c", speaker: null, language: null, concepts: [], moments: 1 });
+ expect(context).toBe("title=a\\=b\\|c|moments=1");
+ });
+});
From a6c4d95c549b38362d982fc5eebfc6b7e77bce61 Mon Sep 17 00:00:00 2001
From: im-rk
Date: Sat, 3 Oct 2026 10:05:28 +0530
Subject: [PATCH 3/3] docs(phase-19): concept map, Cloudinary asset index, API
and README
---
CHANGELOG.md | 4 +++
README.md | 2 ++
docs/API.md | 14 ++++++++
docs/IMPLEMENTATION_PLAN.md | 1 +
.../PHASE-19-concept-map-cloudinary-index.md | 24 ++++++++++++++
openapi.yaml | 32 +++++++++++++++++++
6 files changed, 77 insertions(+)
create mode 100644 docs/phases/PHASE-19-concept-map-cloudinary-index.md
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 402fd6d..ed3809c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,10 @@ Format: [Keep a Changelog](https://keepachangelog.com/); versioning: [SemVer](ht
## [Unreleased]
+### Added
+- Concept Map `/concepts` and Compare view `/concepts/[key]`: the same concept from every teacher as one Compare Reel (Phase 19)
+- Cloudinary asset index: tags and contextual metadata on each session's asset, synced from the Studio and read back with the Search API (Phase 19)
+
## [1.0.0] — 2026-10-03
The hackathon submission. Live at https://pravaha-cyan.vercel.app; PR numbers refer to `Monolithic-Dev/Pravaha`.
diff --git a/README.md b/README.md
index 23f252a..50ccce9 100644
--- a/README.md
+++ b/README.md
@@ -75,6 +75,8 @@ Colleges, clubs and coaching institutes record hundreds of hours of lectures and
| **Find** | Search every session for what was *said* and land on the exact second. |
| **Ask** | Ask a question in plain language. The answer comes **only** from your recordings, and every claim links to a **playable clip** of the moment it came from. Progress streams live while it works, and the answer suggests follow-up questions. If the library doesn't cover a question, Pravaha says so instead of guessing. |
| **Answer Reels** | The moments an answer cites, from different speakers and sessions, stitched into one labelled video. |
+| **Concept Map** | `/concepts` lines up every concept your lectures teach and how many different teachers explain it. Open one and hear the same idea from each lecturer, back to back, as one Cloudinary-spliced video, until one explanation clicks. |
+| **Learning Paths** | `/learn`: type a topic and get a 3–5 step course, ordered basics first, drawn from moments across the library and edited into one video. |
| **Study Packs** | Every session gets a summary, key concepts, a quiz whose explanations **play the moment** the teacher explains it, and a "Session in 60 seconds" highlight reel. Pravaha generates them automatically from the transcript. |
| **Moments** | One tap turns any cited clip into a vertical, AI-cropped, subtitled short for WhatsApp or Instagram, with its own share page and preview card. The short is just a Cloudinary URL; nothing is rendered. |
| **Insights** | Organizers see what learners ask, the **knowledge gaps** the library can't answer yet (what to record next), and which Moments get shared. Every report downloads as CSV. Visitors can explore a read-only demo of the Studio. |
diff --git a/docs/API.md b/docs/API.md
index 06d8951..ff04f4a 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -146,3 +146,17 @@ Adds `checks.aiLive.models[{ model, ok, ms, error? }]`, one tiny real call per m
### `POST /api/ask` (behaviour)
Retrieval now rewrites a question into the library's vocabulary when it is in another script or keyword retrieval is thin. The stream gains an `{ "type": "understanding" }` event, and `retrieved` carries `expanded: boolean`.
+
+## Phase 19 additions
+
+### `GET /api/concepts`
+- **Auth:** public
+- **Response:** `[{ key, name, sessions }]`: every concept the published library teaches, most-taught first
+
+### `GET /api/concepts/[key]`
+- **Auth:** public
+- **Response:** `{ key, name, moments: [{ lectureId, title, speaker, startS, endS, text, related }] }` (up to 5, one per session; `related` is true for a session that teaches it without naming it a key concept) · `404` unknown key
+
+### `POST /api/organizer/index` · `GET /api/organizer/index`
+- **Auth:** organizer cookie (`401` otherwise) · `maxDuration` 60 s
+- `POST` writes tags and contextual metadata onto every session's Cloudinary asset, then returns `{ synced, skipped, assets }` read back with the Search API. `GET` returns just `{ assets: [{ publicId, tags, context }] }`
diff --git a/docs/IMPLEMENTATION_PLAN.md b/docs/IMPLEMENTATION_PLAN.md
index a0d5ab7..63a19de 100644
--- a/docs/IMPLEMENTATION_PLAN.md
+++ b/docs/IMPLEMENTATION_PLAN.md
@@ -93,3 +93,4 @@ The core loop (Phases 01–09) is built and verified on real Cloudinary + Neon.
**PR policy (team lead, Oct 1):** a PR is opened only once a feature branch carries **at least 20 changed files**, so related phases ship together (`GIT_WORKFLOW.md`).
| 18 | Query understanding, Learning Paths, AI reliability | Rewrite questions into the library's words (and translate them), honest near-miss answers, `/learn` micro-courses as one Cloudinary reel, circuit breaker + deep health | ✅ done (Oct 3) |
+| 19 | Concept Map & Cloudinary asset index | Same concept, every teacher, as one Compare Reel; tags + contextual metadata on Cloudinary assets, read back with the Search API | ✅ done (Oct 3) |
diff --git a/docs/phases/PHASE-19-concept-map-cloudinary-index.md b/docs/phases/PHASE-19-concept-map-cloudinary-index.md
new file mode 100644
index 0000000..eb4d89f
--- /dev/null
+++ b/docs/phases/PHASE-19-concept-map-cloudinary-index.md
@@ -0,0 +1,24 @@
+# Phase 19 — Concept Map & Cloudinary Asset Index
+
+**Status: DONE (Oct 3)** · branch `feature/concept-map-cloudinary-index`
+
+## Why this phase exists
+A learner who doesn't understand an idea from one lecturer usually doesn't need *more* material, they need the same idea *explained differently*. Libraries bury that: the explanation that would click is in another session, under another title. Pravaha already knows every session's key concepts (the Study Packs), so it can line them up.
+
+The second half closes a gap with Cloudinary itself: until now Pravaha's knowledge lived only in Postgres, and the Cloudinary media library knew nothing about it.
+
+## What shipped
+1. **Concept Map** (`/concepts`, `src/lib/concept-map.ts`, `src/lib/concepts.ts`): every key concept from every published Study Pack, grouped across sessions by a normalised key (case, punctuation, plurals and word order ignored). Concepts taught by more than one lecturer come first. No extra AI call: it reads what the Study Packs already hold.
+2. **Compare view** (`/concepts/[key]`, `ConceptView.tsx`): the moments the Study Packs point at, then the closest moment from any session that teaches the idea without listing it as a key concept (found with the same retrieval Ask uses). They are spliced into **one Compare Reel** with `fl_splice`, each clip labelled with its speaker, plus one card per explanation (thumbnail, quote, open session, share as Moment). Shared with its own Cloudinary share card; a link back into `/learn` turns the concept into a course.
+3. **Cloudinary asset index** (`src/lib/cloudinary-index.ts`, `src/lib/asset-metadata.ts`): when a Study Pack is built, the session's Cloudinary asset is tagged (`pravaha`, `lang-en`, `concept-…`) and given contextual metadata (`title`, `speaker`, `language`, `concepts`, `moments`). The Studio's **Cloudinary asset index** panel (organizer) backfills every session and reads the result back with the **Search API** (`resource_type:video AND tags=pravaha`), proving the round trip.
+4. `ReelPlayer` extracted so Learning Paths and Compare share one reel button.
+
+## Decisions
+- **No audio-only "Listen mode".** Tried and measured: Cloudinary rejects splicing mixed-size sources when the output is audio (`.mp3`/`.m4a`/`.aac`), because the frame resize is skipped. It would have needed a video render first, which defeats the point, so it was dropped.
+- Concept keys sort tokens and stem a trailing `s`, so tags read `concept-influence-learning-rate`. Keys are stable identifiers, not display text.
+- The Search API is organizer-only (it can return unlisted assets); public pages never expose it.
+
+## Verification
+- 11 new unit tests (`concept-map`, `asset-metadata`).
+- Live: `/concepts/overfitting` → three teachers (IIT Kharagpur, IIT Madras, NPTEL TensorFlow), Compare Reel 200 `video/mp4` 1.8 MB / 46 s.
+- Live: organizer sync wrote tags and context for every Study Pack; the Search API read them back.
diff --git a/openapi.yaml b/openapi.yaml
index 834ad27..2061082 100644
--- a/openapi.yaml
+++ b/openapi.yaml
@@ -460,3 +460,35 @@ paths:
'200': { description: 'CSV with a UTF-8 byte-order mark, as an attachment', content: { text/csv: { schema: { type: string } } } }
'400': { description: Unknown report, content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
'401': { description: Not an organizer and the demo Studio is off }
+ /concepts:
+ get:
+ summary: The concept map, every concept the published library teaches
+ operationId: listConcepts
+ security: [{}]
+ responses:
+ '200': { description: Concepts, most-taught first, content: { application/json: { schema: { type: array, items: { type: object, properties: { key: { type: string }, name: { type: string }, sessions: { type: integer } } } } } } }
+ /concepts/{key}:
+ get:
+ summary: One concept and the moments, across sessions, that explain it
+ operationId: getConcept
+ security: [{}]
+ parameters:
+ - { name: key, in: path, required: true, schema: { type: string, pattern: '^[a-z0-9-]{1,80}$' } }
+ responses:
+ '200': { description: The concept and up to 5 moments, content: { application/json: { schema: { type: object } } } }
+ '404': { description: No such concept, content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } } }
+ /organizer/index:
+ post:
+ summary: Tag every session's Cloudinary asset and read the tags back with the Search API
+ operationId: syncCloudinaryIndex
+ security: [{ organizerCookie: [] }]
+ responses:
+ '200': { description: Sync result, content: { application/json: { schema: { type: object } } } }
+ '401': { description: Not an organizer }
+ get:
+ summary: The tagged assets, from Cloudinary's Search API
+ operationId: listCloudinaryIndex
+ security: [{ organizerCookie: [] }]
+ responses:
+ '200': { description: Assets with tags and contextual metadata, content: { application/json: { schema: { type: object } } } }
+ '401': { description: Not an organizer }