You are an expert AI assistant tasked with building a fully functional, multi-page Next.js MVP application. The application is an AI-powered platform for developing and deploying ultra-compact, low-latency AI models optimized for edge devices like FPGAs. This platform aims to solve the problem of real-time data filtering and processing in large-scale scientific experiments and other data-intensive industries.
**1. PROJECT OVERVIEW:**
**Application Name:** Edge AI Filter (Kenar Yapay Zeka Filtresi)
**Problem Solved:** Traditional AI models are often too large and computationally expensive for real-time processing on edge devices, leading to data bottlenecks and high energy consumption. Scientific instruments like the LHC at CERN generate massive datasets that require immediate filtering.
**Core Value Proposition:** Empower researchers and engineers to develop, optimize, and deploy highly efficient, compact AI models directly onto edge hardware (FPGAs, specialized ASICs, edge servers) for real-time data analysis, anomaly detection, and filtering, significantly reducing latency, cost, and power usage.
**Target Audience:** Scientific research institutions (CERN, NASA), financial analysis firms, telecommunication companies, industrial automation, and tech companies working with embedded AI.
**2. TECH STACK:**
- **Frontend Framework:** Next.js (App Router)
- **Styling:** Tailwind CSS
- **ORM:** Drizzle ORM (PostgreSQL)
- **UI Library:** shadcn/ui
- **State Management:** React Context API / Zustand (for global state)
- **Authentication:** NextAuth.js (Credentials provider for MVP, consider OAuth for later)
- **Database:** PostgreSQL (via Vercel Postgres or similar)
- **API Layer:** Server Actions / Route Handlers
- **Form Handling:** React Hook Form + Zod for validation
- **Charting:** Recharts or Chart.js
- **Deployment:** Vercel
- **Programming Language:** TypeScript
**3. DATABASE SCHEMA (Drizzle ORM - PostgreSQL):**
```typescript
// Schema for Drizzle ORM
import { pgTable, serial, varchar, text, timestamp, integer, boolean, jsonb } from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
// User Table
export const users = pgTable('users', {
id: serial('id').primaryKey(),
name: varchar('name'),
email: varchar('email', { length: 255 }).notNull().unique(),
emailVerified: timestamp('emailVerified', { mode: 'date' }),
image: varchar('image'),
createdAt: timestamp('createdAt').defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow(),
});
// Projects Table (Represents a user's AI model development effort)
export const projects = pgTable('projects', {
id: serial('id').primaryKey(),
userId: integer('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
name: varchar('name', { length: 255 }).notNull(),
description: text('description'),
createdAt: timestamp('createdAt').defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow(),
});
// Models Table (Specific AI model configurations within a project)
export const models = pgTable('models', {
id: serial('id').primaryKey(),
projectId: integer('projectId').notNull().references(() => projects.id, { onDelete: 'cascade' }),
name: varchar('name', { length: 255 }).notNull(),
architecture: varchar('architecture', { length: 100 }), // e.g., 'CNN', 'LSTM', 'Custom'
optimizationLevel: integer('optimizationLevel').default(5), // 1 (low) to 10 (high)
targetHardware: varchar('targetHardware', { length: 100 }), // e.g., 'FPGA-Xilinx-A', 'Edge-TPU', 'Generic-CPU'
status: varchar('status', { length: 50 }).default('created'), // e.g., 'created', 'compiling', 'deployed', 'error'
compiledModelUrl: varchar('compiledModelUrl'), // Link to the compiled model artifact
createdAt: timestamp('createdAt').defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow(),
});
// Deployments Table (Tracks where and when a model was deployed)
export const deployments = pgTable('deployments', {
id: serial('id').primaryKey(),
modelId: integer('modelId').notNull().references(() => models.id, { onDelete: 'cascade' }),
deploymentName: varchar('deploymentName', { length: 255 }).notNull(),
endpointUrl: varchar('endpointUrl'), // URL for real-time data ingestion/output
deployedAt: timestamp('deployedAt').defaultNow(),
isActive: boolean('isActive').default(true),
});
// Performance Metrics Table (Real-time or batch collected metrics)
export const performanceMetrics = pgTable('performanceMetrics', {
id: serial('id').primaryKey(),
deploymentId: integer('deploymentId').notNull().references(() => deployments.id, { onDelete: 'cascade' }),
timestamp: timestamp('timestamp').defaultNow(),
latencyMs: integer('latencyMs'),
accuracy: integer('accuracy'), // Percentage
throughput: integer('throughput'), // e.g., samples per second
resourceUsageJson: jsonb('resourceUsageJson'), // e.g., { 'cpu': 10, 'memory': 20, 'fpga_util': 80 }
});
// User Relations
export const userRelations = {
projects: relations(users, ({ many }) => ({
projects: many(projects),
})),
};
// Project Relations
export const projectRelations = {
user: relations(projects, ({ one }) => ({ user: one(users) })),
models: relations(projects, ({ many }) => ({ models: many(models) })),
};
// Model Relations
export const modelRelations = {
project: relations(models, ({ one }) => ({ project: one(projects) })),
deployments: relations(models, ({ many }) => ({ deployments: many(deployments) })),
};
// Deployment Relations
export const deploymentRelations = {
model: relations(deployments, ({ one }) => ({ model: one(models) })),
metrics: relations(deployments, ({ many }) => ({ metrics: many(performanceMetrics) })),
};
```
**4. CORE FEATURES & USER FLOW:**
**a. Authentication Flow:**
- **Sign Up/Sign In:** User accesses the app. Presented with Sign In/Sign Up options.
- **Credentials:** Uses NextAuth.js with email/password. Input fields for email and password. Validation (required, email format).
- **Verification (Optional for MVP):** Email verification link sent upon signup.
- **Session Management:** Secure session handling using JWTs stored in HttpOnly cookies managed by NextAuth.js.
- **Dashboard Access:** Upon successful login, user is redirected to their personalized dashboard.
- **Sign Out:** User can click a 'Sign Out' button, which invalidates the session and redirects to the login page.
**b. Project Management:**
- **Create Project:** From the dashboard, user clicks 'New Project'. A modal or page appears asking for Project Name and Description. Uses Server Actions to create a new entry in the `projects` table linked to the current `userId`.
- **View Projects:** The dashboard lists all projects created by the user. Each project card shows Name, Description, Creation Date, and a link to its models.
- **Edit/Delete Project:** Options on each project card (or a dedicated project page) to edit its details (Name, Description) or delete the project (with confirmation).
**c. Model Creation & Configuration:**
- **Access Models:** User navigates to a specific project and sees a list of models associated with it.
- **New Model:** User clicks 'New Model' within a project. A multi-step form or page appears:
1. **Basic Info:** Model Name, Description.
2. **Architecture Selection:** Dropdown/radio buttons for common architectures (e.g., 'Simple CNN', 'Feedforward NN', 'Custom Placeholder'). Placeholder for future complex selection.
3. **Target Hardware:** Dropdown (e.g., 'FPGA-A', 'Edge-TPU', 'Generic CPU').
4. **Optimization Level:** Slider (1-10).
- **Save Model Configuration:** User clicks 'Save'. Server Action creates a new entry in the `models` table linked to the selected `projectId`.
- **View Model Details:** Clicking a model shows its configuration, status, and associated deployments.
**d. Model Compilation & Deployment:**
- **Initiate Compilation:** On the model details page, user clicks 'Compile for Deployment'.
- **Backend Process:** Server Action triggers a background job (or simulates it for MVP). This job would:
- Fetch model configuration.
- *Simulate* AI model compilation and optimization based on `architecture`, `optimizationLevel`, `targetHardware`.
- *Simulate* generation of a downloadable compiled model artifact (e.g., a `.bin` or `.hdl` file). For MVP, this could be a placeholder file.
- Update the `models.status` to 'compiling' then 'compiled'.
- Store a URL to the compiled artifact in `models.compiledModelUrl`.
- **Initiate Deployment:** Once compiled, user clicks 'Deploy'.
- **Deployment Configuration:** User provides a `deploymentName` and potentially an `endpointUrl` (for simulation).
- **Create Deployment:** Server Action creates an entry in the `deployments` table, linking to the `modelId` and setting `isActive` to `true`. Updates `models.status` to 'deployed'.
- **View Deployments:** List of active deployments for the model is shown.
**e. Performance Monitoring:**
- **Data Ingestion (Simulated):** A POST API endpoint (e.g., `/api/deployments/[id]/metrics`) is available for the deployed endpoint URL. This endpoint receives performance data.
- **Metric Logging:** When data is received at the endpoint, Server Action or Route Handler saves the data into the `performanceMetrics` table, linked to the correct `deploymentId`.
- **Dashboard Display:** The model details page includes a section that fetches and displays recent metrics (Latency, Accuracy, Throughput) using a charting library (Recharts).
- **Status Updates:** `performanceMetrics.timestamp` tracks when data was received.
**5. API & DATA FETCHING:**
- **Authentication:** Handled by NextAuth.js API routes (`/api/auth/[...nextauth]`).
- **Server Actions:** Used for all mutations (CRUD operations on projects, models, deployments) to leverage Next.js's built-in data mutation handling and avoid client-side form state management complexities for MVP.
- `createProject(name, description)`
- `updateProject(id, name, description)`
- `deleteProject(id)`
- `createModel(projectId, name, description, architecture, optimizationLevel, targetHardware)`
- `updateModel(id, ...)`
- `deleteModel(id)`
- `compileModel(id)` (Triggers background process)
- `deployModel(modelId, deploymentName)`
- **Route Handlers (API):** Primarily for external data ingestion.
- `POST /api/deployments/{deploymentId}/metrics`: Accepts JSON payload `{ latencyMs, accuracy, throughput, resourceUsageJson }`. Validates input using Zod. Logs metrics.
- **Data Fetching (Client Components):** Use `fetch` with appropriate caching/revalidation strategies or libraries like SWR within Server Components or Client Components (if necessary) to get data from the database via Server Actions or read-only Route Handlers.
- Fetch user's projects for the dashboard.
- Fetch models for a specific project.
- Fetch deployment and performance metrics for a model's detail page.
**6. COMPONENT BREAKDOWN (Next.js App Router Structure):**
- **`app/layout.tsx`:** Root layout (HTML, Head, Body, global providers, Tailwind CSS init).
- **`app/page.tsx`:** Landing Page (Marketing content, feature highlights, CTA).
- **`app/(auth)/signin/page.tsx`:** Sign In form page.
- **`app/(auth)/signup/page.tsx`:** Sign Up form page.
- **`app/dashboard/layout.tsx`:** Protected layout for authenticated users (Sidebar/Navbar).
- **`app/dashboard/page.tsx`:** Main Dashboard page. Lists user's projects. Includes 'New Project' button. Fetches `projects`.
- **`app/projects/[projectId]/page.tsx`:** Project Detail page. Shows project info and lists its `models`. Includes 'New Model' button. Fetches project details and associated models.
- **`app/projects/[projectId]/models/[modelId]/page.tsx`:** Model Detail page. Shows model config, `status`, 'Compile'/'Deploy' buttons, list of `deployments`, and performance charts. Fetches model details, deployments, and metrics.
- **`app/api/auth/[...nextauth]/route.ts`:** NextAuth.js route handler.
- **`app/api/deployments/[deploymentId]/metrics/route.ts`:** POST route for metrics ingestion.
**UI Components (inside `components/` and `components/ui/` from shadcn/ui):**
- **`AuthForm`:** Reusable sign-in/sign-up form component.
- **`Navbar`:** Top navigation bar (logo, user menu, sign out).
- **`Sidebar`:** Left-hand navigation (dashboard links, project list).
- **`ProjectCard`:** Displays summary info for a project on the dashboard.
- **`ModelCard`:** Displays summary info for a model within a project.
- **`ModelForm`:** Multi-step form for creating/editing model configurations.
- **`DeploymentList`:** Displays deployed instances of a model.
- **`MetricsChart`:** Recharts component to visualize performance data.
- **`DataTable`:** Generic table component (using shadcn/ui Table) for displaying projects, models, deployments.
- **`LoadingSpinner`:** Custom or shadcn/ui loading indicator.
- **`StatusBadge`:** Displays model/deployment status with color coding.
**State Management:**
- Global state (e.g., user auth status) managed via Context API or Zustand.
- Component-specific state managed using `useState` and `useReducer`.
- Form state managed by React Hook Form.
- Server state (data fetching) implicitly managed via Server Components and Server Actions, with client-side fetching/revalidation where needed using `fetch` or SWR.
**7. UI/UX DESIGN & VISUAL IDENTITY:**
- **Design Style:** "Modern Minimalist Gradient"
- **Color Palette:**
- Primary: Deep Blue (`#0B132B`)
- Secondary: Teal (`#5BC0BE`)
- Accent/Gradient 1: Vibrant Purple (`#8338EC`)
- Accent/Gradient 2: Bright Pink (`#FF0069`)
- Text/Background: Off-white (`#F8F9FA`), Dark Gray (`#343A40`)
- **Typography:** Sans-serif font family. Use Inter or similar from Google Fonts. Clear hierarchy for headings, subheadings, body text.
- **Layout:** Clean, spacious layout. Use a responsive grid system (Tailwind CSS). Sidebar for navigation, main content area. Cards for discrete items (projects, models).
- **Sections:** Clear separation of sections within pages. Use subtle borders or background color differences.
- **Animations:** Subtle fade-ins for content loading, smooth transitions on hover for interactive elements (buttons, cards), skeleton loaders for data fetching.
- **Responsive Rules:** Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Content reflows gracefully. Ensure all interactive elements are easily tappable on touch devices.
**8. SAMPLE/MOCK DATA:**
**a. `projects` Table:**
```json
[{"id": 1, "userId": 101, "name": "LHC Data Filter", "description": "Real-time event filtering for particle collision data.", "createdAt": "2023-10-27T10:00:00Z", "updatedAt": "2023-10-27T10:00:00Z"},{"id": 2, "userId": 101, "name": "CMSSW Optimization", "description": "Optimizing AI inference within the CMS software framework.", "createdAt": "2023-10-26T15:30:00Z", "updatedAt": "2023-10-26T15:30:00Z"}]
```
**b. `models` Table:**
```json
[{"id": 1, "projectId": 1, "name": "Event Classifier v1", "architecture": "Tiny CNN", "optimizationLevel": 8, "targetHardware": "FPGA-Xilinx-A", "status": "deployed", "compiledModelUrl": "/models/lhc-filter-v1.hdl", "createdAt": "2023-10-27T11:00:00Z", "updatedAt": "2023-10-27T14:00:00Z"},{"id": 2, "projectId": 1, "name": "Anomaly Detector v2", "architecture": "LSTM", "optimizationLevel": 6, "targetHardware": "Generic-CPU", "status": "compiled", "compiledModelUrl": "/models/anomaly-v2.bin", "createdAt": "2023-10-27T12:00:00Z", "updatedAt": "2023-10-27T13:00:00Z"}]
```
**c. `deployments` Table:**
```json
[{"id": 1, "modelId": 1, "deploymentName": "LHC-Run3-Frontend", "endpointUrl": "/api/ingest/lhc-run3", "deployedAt": "2023-10-27T14:00:00Z", "isActive": true}]
```
**d. `performanceMetrics` Table (Sample for Deployment ID 1):**
```json
[{"id": 1, "deploymentId": 1, "timestamp": "2023-10-27T14:05:00Z", "latencyMs": 15, "accuracy": 98, "throughput": 500, "resourceUsageJson": {"fpga_util": 85, "memory": 128}},{"id": 2, "deploymentId": 1, "timestamp": "2023-10-27T14:06:00Z", "latencyMs": 12, "accuracy": 97, "throughput": 520, "resourceUsageJson": {"fpga_util": 88, "memory": 130}}]
```
**9. TURKISH TRANSLATIONS:**
- **App Title:** Kenar Yapay Zeka Filtresi
- **Dashboard:** Kontrol Paneli
- **Projects:** Projeler
- **Models:** Modeller
- **Deployments:** Dağıtımlar
- **New Project:** Yeni Proje
- **Create Model:** Model Oluştur
- **Compile:** Derle
- **Deploy:** Dağıt
- **Settings:** Ayarlar
- **Sign In:** Giriş Yap
- **Sign Up:** Kayıt Ol
- **Sign Out:** Çıkış Yap
- **Name:** Ad
- **Description:** Açıklama
- **Architecture:** Mimari
- **Target Hardware:** Hedef Donanım
- **Optimization Level:** Optimizasyon Seviyesi
- **Status:** Durum
- **Created:** Oluşturuldu
- **Compiling:** Derleniyor
- **Compiled:** Derlendi
- **Deployed:** Dağıtıldı
- **Error:** Hata
- **Real-time Data:** Gerçek Zamanlı Veri
- **Performance Metrics:** Performans Metrikleri
- **Latency:** Gecikme
- **Accuracy:** Doğruluk
- **Throughput:** Verim
- **Resource Usage:** Kaynak Kullanımı
- **Save:** Kaydet
- **Cancel:** İptal
- **Are you sure?** Emin misiniz?
- **Yes, delete.** Evet, sil.
- **Model saved successfully.** Model başarıyla kaydedildi.
- **Compilation started.** Derleme başlatıldı.
- **Deployment successful.** Dağıtım başarılı.
- **Welcome!** Hoş geldiniz!
This prompt provides a detailed blueprint for generating a functional MVP application. Remember to implement robust error handling, input validation (using Zod), and consider security best practices throughout the development process.