Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 32 additions & 5 deletions apps/api/src/lib/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ import {
SupabaseGenerationJobRepository,
SupabaseProductRepository,
} from '@minimalblock/data';
import { createGenerativeModel, ANALYSIS_MODEL_ID, GeminiModelGenerator, GeminiVisualQa, buildTrendyolListingPrompt } from '@minimalblock/ai';
import { createGenerativeModel, ANALYSIS_MODEL_ID, GeminiModelGenerator, GeminiVisualQa, buildTrendyolListingPrompt, GenerationFeedbackService } from '@minimalblock/ai';
import { TrendyolClient } from '@minimalblock/trendyol';
import { ProductImportService } from './product-import.service.js';
import type {
Expand Down Expand Up @@ -742,11 +742,19 @@ async function createConversionForProduct(
}),
);
} else {
const generator = new GeminiModelGenerator(createGenerativeModel(ctx.env.geminiApiKey));
const generator = new GeminiModelGenerator(
createGenerativeModel(ctx.env.geminiApiKey),
createGenerativeModel(ctx.env.geminiApiKey, ANALYSIS_MODEL_ID),
);
const generated = await generator.generate({
sourceAsset: sourceAssets[0],
productCategory: product.category,
qualityHint: req.qualityHint,
sourceAsset: sourceAssets[0],
sourceAssets: sourceAssets,
productCategory: product.category,
qualityHint: req.qualityHint,
productTitle: product.name,
productDimensions: product.importData?.fields?.dimensions?.value ?? undefined,
inferredMaterialFinish: product.importData?.inferredMaterialFinish ?? undefined,
inferredGeometryComplexity: product.importData?.inferredGeometryComplexity ?? undefined,
});
outputAsset = await uploadGeneratedModel(ctx.admin, ctx.user.id, generated.outputAsset, product.name);
job = await jobRepo.save(
Expand Down Expand Up @@ -858,6 +866,16 @@ async function handleApproveConversion(ctx: RequestContext, conversionId: string
const approved = await conversionRepo.save(conversion.approve(ctx.user.id));
await eventsRepo.track(approved.productId, ctx.user.id, 'conversion_approved');
await eventsRepo.track(approved.productId, ctx.user.id, 'product_published');

// Phase I: Record approval signal for feedback loop
await new GenerationFeedbackService(ctx.admin, ctx.user.id)
.recordApproval(
approved.productId,
approved.id,
undefined,
typeof approved.qualityReport?.geminiQaScore === 'number' ? approved.qualityReport.geminiQaScore : undefined,
).catch(() => { /* non-fatal */ });

return { conversion: toConversionSnapshot(approved) };
}

Expand All @@ -871,6 +889,15 @@ async function handleRejectConversion(
const conversion = await getOwnedConversion(ctx, conversionId);
const rejected = await conversionRepo.save(conversion.reject(req.reason));
await eventsRepo.track(rejected.productId, ctx.user.id, 'conversion_rejected', { reason: req.reason });

// Phase I: Record rejection signal for feedback loop
await new GenerationFeedbackService(ctx.admin, ctx.user.id)
.recordRejection(
rejected.productId,
rejected.id,
req.reason ?? 'no reason given',
).catch(() => { /* non-fatal */ });

return { conversion: toConversionSnapshot(rejected) };
}

Expand Down
12 changes: 12 additions & 0 deletions libs/ai/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,17 @@ export type { Convert2DTo3DResponse, ImageAnalysisResponse } from './lib/types/a
export type { ReturnRiskItem } from './lib/gemini/gemini-risk-analyzer.js';
export type { ReturnRiskInput } from './lib/prompts/return-risk-analysis.prompt.js';

// v2 pipeline — scene graph types
export type { SceneGraph, ScenePart, ScenePartMaterial, GeometryFamily, PrimitiveShape } from './lib/types/scene-graph.types.js';
export type { ProductUnderstanding, GeometryIntelligence, ScaleBounds, PbrMaterialMap } from './lib/types/product-understanding.types.js';
export type { ValidationReport, ValidationIssue } from './lib/types/validation.types.js';

// v2 pipeline — feedback service
export { GenerationFeedbackService } from './lib/feedback/generation-feedback.service.js';

// v2 pipeline — validators (exported for server use)
export { SceneGraphValidator, autoRepairSceneGraph } from './lib/validation/scene-graph-validator.js';
export { GlbValidator } from './lib/validation/glb-validator.js';

// Mock provider (replaceable — real Gemini implements the same interface)
export { getMockAnalysis } from './lib/mock/mock-analyzer.js';
85 changes: 85 additions & 0 deletions libs/ai/src/lib/feedback/generation-feedback.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import type { SupabaseClient } from '@supabase/supabase-js';
import type { FeedbackSignal } from '../types/feedback.types.js';
import type { SceneGraph } from '../types/scene-graph.types.js';

interface FeedbackRow {
product_id: string;
conversion_id: string;
owner_id: string;
signal: FeedbackSignal;
rejection_reason?: string;
detected_subtype: string;
geometry_family: string;
qa_score?: number;
validation_score?: number;
scene_graph_snapshot?: Record<string, unknown>;
}

export class GenerationFeedbackService {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
constructor(private readonly supabase: SupabaseClient<any>, private readonly ownerId: string) {}

async recordApproval(
productId: string,
conversionId: string,
sceneGraph?: SceneGraph,
qaScore?: number,
validationScore?: number,
): Promise<void> {
await this.insert({
product_id: productId,
conversion_id: conversionId,
owner_id: this.ownerId,
signal: 'approved',
detected_subtype: sceneGraph?.productSubtype ?? 'unknown',
geometry_family: sceneGraph?.geometryFamily ?? 'hard-surface',
qa_score: qaScore,
validation_score: validationScore,
scene_graph_snapshot: sceneGraph
? { boundingBox: sceneGraph.boundingBox, partCount: sceneGraph.parts.length, confidence: sceneGraph.confidence }
: undefined,
});
}

async recordRejection(
productId: string,
conversionId: string,
reason: string,
sceneGraph?: SceneGraph,
qaScore?: number,
): Promise<void> {
await this.insert({
product_id: productId,
conversion_id: conversionId,
owner_id: this.ownerId,
signal: 'rejected',
rejection_reason: reason,
detected_subtype: sceneGraph?.productSubtype ?? 'unknown',
geometry_family: sceneGraph?.geometryFamily ?? 'hard-surface',
qa_score: qaScore,
scene_graph_snapshot: sceneGraph
? { boundingBox: sceneGraph.boundingBox, partCount: sceneGraph.parts.length, confidence: sceneGraph.confidence }
: undefined,
});
}

async recordRegeneration(productId: string, conversionId: string, sceneGraph?: SceneGraph): Promise<void> {
await this.insert({
product_id: productId,
conversion_id: conversionId,
owner_id: this.ownerId,
signal: 'regenerated',
detected_subtype: sceneGraph?.productSubtype ?? 'unknown',
geometry_family: sceneGraph?.geometryFamily ?? 'hard-surface',
});
}

private async insert(row: FeedbackRow): Promise<void> {
try {
const { error } = await this.supabase.from('generation_feedback').insert(row);
if (error) console.error('[GenerationFeedbackService] Insert failed:', error);
} catch (err) {
console.error('[GenerationFeedbackService] Unexpected error:', err);
}
}
}
Loading
Loading