Initial commit: Cleaned and Optimized NanoJason Pro

This commit is contained in:
Gemini AI
2025-12-20 04:18:55 +04:00
Unverified
commit b03366c9ac
29 changed files with 8726 additions and 0 deletions

41
.gitignore vendored Normal file
View File

@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

7
.vercelignore Normal file
View File

@@ -0,0 +1,7 @@
node_modules
build
dist
.git
.trae
.log
.figma

122
README.md Normal file
View File

@@ -0,0 +1,122 @@
# 🚀 NanoJason - Universal AI Prompt Language Translator & Optimizer
<div align="center">
![NanoJason](https://img.shields.io/badge/NanoJason-AI%20Prompt%20Optimizer-blue?style=for-the-badge&logo=sparkles)
![Version](https://img.shields.io/badge/Version-3.0-green?style=for-the-badge)
![License](https://img.shields.io/badge/License-MIT-yellow?style=for-the-badge)
![Offline](https://img.shields.io/badge/Status-Offline%20Ready-purple?style=for-the-badge)
</div>
<p align="center">
<strong>NanoJason</strong> is a revolutionary, offline-only prompt engineering tool that transforms natural language descriptions into optimized Jason format for maximum AI accuracy across all image generation services.
</p>
<p align="center">
<a href="#features">🌟 Features</a> •
<a href="#getting-started">🚀 Getting Started</a> •
<a href="#usage">💡 Usage</a> •
<a href="#tech-stack">🛠️ Tech Stack</a> •
<a href="#license">📜 License</a>
</p>
---
## 📸 **App Showcase**
<div align="center">
<img src="https://raw.githubusercontent.com/roman-ryzenadvanced/NanoJasonPro/main/public/screenshots/hero.png" alt="NanoJason Hero" width="800">
<p><em>The ultimate prompt engineering dashboard</em></p>
</div>
---
## 🌟 **Amazing Features**
### 🎯 **Three Powerful Modes**
#### 1. **Jason Translator**
- Converts natural language to universal Jason format
- Style, mood, character, and item detection
- Extracts color palette, composition, and lighting
- Perfect for AI image generation compatibility
#### 2. **NanoPrompt Optimizer**
- Deep reverse engineering for maximum AI accuracy
- Pattern mapping and keyword enhancement
- Quality descriptors and composition optimization
- Lighting and color enhancement
- Error prevention and artifact reduction
- **Accuracy Score:** Up to 95%
#### 3. **NanoCoder Technical Optimizer**
- Specialized for coding and engineering prompts
- Technical domain detection (programming, web, mobile, AI, etc.)
- Framework and language pattern recognition
- Architecture and security optimization
- Code context extraction
- **Technical Accuracy:** Up to 98%
### 🔥 **Key Benefits**
- **🚀 Offline-Only** - No internet connection required
- **⚡ Instant Results** - Real-time translation and optimization
- **🎨 Universal Compatibility** - Works with all AI image generators
- **🔒 Privacy Focused** - No data leaves your device
- **📱 Responsive Design** - Perfect for desktop and mobile
- **🎯 High Accuracy** - Advanced pattern recognition and optimization
- **🔄 Export Options** - Copy, download, and share optimized prompts
---
## 🛠️ **Tech Stack**
- **Framework:** Next.js 14 (App Router)
- **Styling:** Tailwind CSS + Shadcn UI
- **Icons:** Lucide React
- **Language:** TypeScript
- **Optimization:** Custom Reverse-Engineered Patterns
---
## 🚀 **Getting Started**
### Prerequisites
- Node.js 18+
- npm or pnpm
### Installation
1. **Clone the repository**
```bash
git clone https://github.com/roman-ryzenadvanced/NanoJasonPro.git
cd NanoJasonPro
```
2. **Install dependencies**
```bash
npm install
```
3. **Run the application**
```bash
npm run dev
```
4. **Open your browser**
```
http://localhost:3000
```
---
## 📜 **License**
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
---
<div align="center">
Developed with ❤️ for the AI Community
</div>

18
eslint.config.mjs Normal file
View File

@@ -0,0 +1,18 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
]),
]);
export default eslintConfig;

17
next.config.js Normal file
View File

@@ -0,0 +1,17 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'export',
trailingSlash: true,
distDir: 'out',
images: {
unoptimized: true,
},
eslint: {
ignoreDuringBuilds: true,
},
typescript: {
ignoreBuildErrors: true,
},
};
module.exports = nextConfig;

6125
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

33
package.json Normal file
View File

@@ -0,0 +1,33 @@
{
"name": "nanojason",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint"
},
"dependencies": {
"@radix-ui/react-slot": "^1.1.0",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"lucide-react": "^0.453.0",
"next": "14.2.15",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"tailwind-merge": "^2.5.4",
"tailwindcss-animate": "^1.0.7"
},
"devDependencies": {
"@types/node": "^20.17.0",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"autoprefixer": "^10.4.20",
"eslint": "^8.57.1",
"eslint-config-next": "14.2.15",
"postcss": "^8.4.47",
"tailwindcss": "^3.4.14",
"typescript": "^5.6.3"
}
}

8
postcss.config.mjs Normal file
View File

@@ -0,0 +1,8 @@
const config = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
export default config;

1
public/file.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

1
public/globe.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

1
public/next.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

1
public/vercel.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

1
public/window.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

BIN
src/app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

137
src/app/globals.css Normal file
View File

@@ -0,0 +1,137 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
--card: 0 0% 100%;
--card-foreground: 222.2 84% 4.9%;
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
--primary: 221.2 83.2% 53.3%;
--primary-foreground: 210 40% 98%;
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 46.9%;
--accent: 210 40% 96.1%;
--accent-foreground: 222.2 47.4% 11.2%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 210 40% 98%;
--border: 214.3 32% 91.4%;
--input: 214.3 32% 91.4%;
--ring: 221.2 83.2% 53.3%;
--radius: 0.5rem;
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
--card: 222.2 84% 4.9%;
--card-foreground: 210 40% 98%;
--popover: 222.2 84% 4.9%;
--popover-foreground: 210 40% 98%;
--primary: 217.2 91.2% 59.8%;
--primary-foreground: 222.2 47.4% 11.2%;
--secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 210 40% 98%;
--muted: 217.2 32.6% 17.5%;
--muted-foreground: 215 20.2% 65.1%;
--accent: 217.2 32.6% 17.5%;
--accent-foreground: 210 40% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 210 40% 98%;
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
--ring: 224.3 76.3% 48%;
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}
@layer components {
.gradient-bg {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.glass-effect {
backdrop-filter: blur(10px);
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.2);
}
.card-hover {
transition: all 0.3s ease;
&:hover {
box-shadow: 0 10px 25px -3px rgba(0, 0, 0, 0.1);
transform: scale(1.05);
}
}
.text-gradient {
background: linear-gradient(to right, hsl(var(--primary)), hsl(var(--accent)));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.btn-primary {
background: hsl(var(--primary));
color: hsl(var(--primary-foreground));
padding: 0.5rem 1.5rem;
border-radius: 0.5rem;
font-weight: 500;
transition: all 0.2s ease;
&:hover {
background: hsl(var(--primary) / 0.9);
}
}
.btn-secondary {
background: hsl(var(--secondary));
color: hsl(var(--secondary-foreground));
padding: 0.5rem 1.5rem;
border-radius: 0.5rem;
font-weight: 500;
transition: all 0.2s ease;
&:hover {
background: hsl(var(--secondary) / 0.8);
}
}
}
@layer utilities {
.animate-float {
animation: float 3s ease-in-out infinite;
}
.animate-slide-up {
animation: slideUp 0.3s ease-out;
}
.animate-fade-in {
animation: fadeIn 0.5s ease-in-out;
}
@keyframes float {
0%, 100% { transform: translateY(0px); }
50% { transform: translateY(-10px); }
}
@keyframes slideUp {
0% { transform: translateY(10px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
@keyframes fadeIn {
0% { opacity: 0; }
100% { opacity: 1; }
}
}

31
src/app/layout.tsx Normal file
View File

@@ -0,0 +1,31 @@
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import { Header } from "@/components/layout/header";
const inter = Inter({
subsets: ["latin"],
variable: "--font-sans",
});
export const metadata: Metadata = {
title: "NanoJason - AI-Powered Image Series Creation",
description: "Create stunning image series with consistent characters and narrative using AI. Transform your ideas into visual stories.",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={`${inter.variable} font-sans antialiased`}>
<Header />
<main className="min-h-screen">
{children}
</main>
</body>
</html>
);
}

768
src/app/page.tsx Normal file
View File

@@ -0,0 +1,768 @@
'use client'
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Copy, Download, Sparkles, Info, FileText } from "lucide-react"
import { jasonTranslator, JasonFormat } from "@/services/jason-translator"
import { nanoPrompt, NanoPromptResult } from "@/services/nano-prompt"
import { nanoCoder, NanoCoderResult } from "@/services/nano-coder"
export default function HomePage() {
const [inputText, setInputText] = useState('')
const [jasonFormat, setJasonFormat] = useState<JasonFormat | null>(null)
const [nanoPromptResult, setNanoPromptResult] = useState<NanoPromptResult | null>(null)
const [nanoCoderResult, setNanoCoderResult] = useState<NanoCoderResult | null>(null)
const [isTranslating, setIsTranslating] = useState(false)
const [isOptimizing, setIsOptimizing] = useState(false)
const [isCoding, setIsCoding] = useState(false)
const [copied, setCopied] = useState(false)
const [activeTab, setActiveTab] = useState<'jason' | 'nano' | 'code'>('jason')
const handleTranslate = async () => {
if (!inputText.trim()) return
setIsTranslating(true)
try {
const result = await jasonTranslator.translateToJason(inputText)
setJasonFormat(result)
setNanoPromptResult(null) // Clear nano prompt result
} catch (error) {
console.error('Translation failed:', error)
} finally {
setIsTranslating(false)
}
}
const handleNanoOptimize = async () => {
if (!inputText.trim()) return
setIsOptimizing(true)
try {
const result = await nanoPrompt.optimizePrompt(inputText)
setNanoPromptResult(result)
setJasonFormat(null) // Clear jason format result
setNanoCoderResult(null) // Clear nano coder result
} catch (error) {
console.error('Nano optimization failed:', error)
} finally {
setIsOptimizing(false)
}
}
const handleNanoCode = async () => {
if (!inputText.trim()) return
setIsCoding(true)
try {
const result = await nanoCoder.optimizePrompt(inputText)
setNanoCoderResult(result)
setJasonFormat(null) // Clear jason format result
setNanoPromptResult(null) // Clear nano prompt result
} catch (error) {
console.error('Nano coding failed:', error)
} finally {
setIsCoding(false)
}
}
const handleCopy = async () => {
if (!jasonFormat) return
try {
await navigator.clipboard.writeText(jasonFormat.jason_text)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
} catch (error) {
console.error('Failed to copy:', error)
}
}
const handleDownload = () => {
if (!jasonFormat) return
const dataStr = JSON.stringify(jasonFormat, null, 2)
const dataBlob = new Blob([dataStr], { type: 'application/json' })
const url = URL.createObjectURL(dataBlob)
const link = document.createElement('a')
link.href = url
link.download = `jason-format-${Date.now()}.json`
link.click()
URL.revokeObjectURL(url)
}
const handleCopyNanoPrompt = async () => {
if (!nanoPromptResult) return
try {
await navigator.clipboard.writeText(nanoPromptResult.jason_format)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
} catch (error) {
console.error('Failed to copy:', error)
}
}
const handleDownloadNanoPrompt = () => {
if (!nanoPromptResult) return
const dataStr = JSON.stringify(nanoPromptResult, null, 2)
const dataBlob = new Blob([dataStr], { type: 'application/json' })
const url = URL.createObjectURL(dataBlob)
const link = document.createElement('a')
link.href = url
link.download = `nano-prompt-${Date.now()}.json`
link.click()
URL.revokeObjectURL(url)
}
const handleCopyNanoCoder = async () => {
if (!nanoCoderResult) return
try {
await navigator.clipboard.writeText(nanoCoderResult.jason_format)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
} catch (error) {
console.error('Failed to copy:', error)
}
}
const handleDownloadNanoCoder = () => {
if (!nanoCoderResult) return
const dataStr = JSON.stringify(nanoCoderResult, null, 2)
const dataBlob = new Blob([dataStr], { type: 'application/json' })
const url = URL.createObjectURL(dataBlob)
const link = document.createElement('a')
link.href = url
link.download = `nano-coder-${Date.now()}.json`
link.click()
URL.revokeObjectURL(url)
}
const quickTemplates = [
{ text: "A magical forest with glowing mushrooms and fairies", label: "Fantasy Scene" },
{ text: "Futuristic city skyline at sunset with flying cars", label: "Sci-Fi City" },
{ text: "Cozy cabin in the woods with warm lights", label: "Peaceful Nature" },
{ text: "Dragon breathing fire in a medieval castle", label: "Epic Fantasy" }
]
const nanoQuickTemplates = [
{ text: "A beautiful portrait of a woman", label: "Portrait" },
{ text: "Mountains at sunset", label: "Landscape" },
{ text: "A superhero character", label: "Character" },
{ text: "A smartphone product", label: "Product" }
]
const nanoCoderQuickTemplates = [
{ text: "React web application with TypeScript", label: "Web App" },
{ text: "React Native mobile app", label: "Mobile App" },
{ text: "Node.js microservice with REST API", label: "Microservice" },
{ text: "REST API with authentication", label: "API" },
{ text: "Data visualization dashboard", label: "Dashboard" }
]
return (
<div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50">
<div className="container mx-auto px-4 py-8 max-w-6xl">
{/* Header */}
<div className="text-center mb-12">
<h1 className="text-4xl md:text-6xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent mb-4">
NanoJason
</h1>
<p className="text-xl text-gray-600 mb-2">
Universal AI Prompt Language Translator & Optimizer
</p>
<p className="text-sm text-gray-500 max-w-2xl mx-auto">
Convert natural language descriptions to Jason format and optimize for maximum AI accuracy
</p>
</div>
{/* Tabs */}
<div className="flex justify-center mb-8">
<div className="bg-white rounded-full p-1 shadow-lg border border-gray-200">
<button
onClick={() => setActiveTab('jason')}
className={`px-6 py-2 rounded-full text-sm font-medium transition-all duration-200 ${
activeTab === 'jason'
? 'bg-blue-600 text-white shadow-md'
: 'text-gray-600 hover:text-blue-600'
}`}
>
Jason Translator
</button>
<button
onClick={() => setActiveTab('nano')}
className={`px-6 py-2 rounded-full text-sm font-medium transition-all duration-200 ${
activeTab === 'nano'
? 'bg-purple-600 text-white shadow-md'
: 'text-gray-600 hover:text-purple-600'
}`}
>
NanoPrompt
</button>
<button
onClick={() => setActiveTab('code')}
className={`px-6 py-2 rounded-full text-sm font-medium transition-all duration-200 ${
activeTab === 'code'
? 'bg-green-600 text-white shadow-md'
: 'text-gray-600 hover:text-green-600'
}`}
>
NanoCoder
</button>
</div>
</div>
{/* Jason Translator */}
{activeTab === 'jason' && (
<Card className="mb-12 border-2 border-blue-200 shadow-xl">
<CardHeader className="bg-gradient-to-r from-blue-50 to-purple-50">
<CardTitle className="flex items-center gap-2 text-2xl">
<Sparkles className="h-6 w-6 text-blue-600" />
Jason Language Translator
</CardTitle>
<CardDescription className="text-lg">
Describe what you want to create, and I'll convert it to universal Jason format
</CardDescription>
</CardHeader>
<CardContent className="space-y-6 p-6">
{/* Quick Templates */}
<div>
<h4 className="font-semibold text-gray-700 mb-3">Quick Templates:</h4>
<div className="grid grid-cols-2 md:grid-cols-4 gap-2">
{quickTemplates.map((template, index) => (
<Button
key={index}
variant="outline"
size="sm"
onClick={() => setInputText(template.text)}
className="text-xs h-auto py-2 px-3 whitespace-normal text-left"
>
{template.label}
</Button>
))}
</div>
</div>
{/* Input */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Describe your image:
</label>
<textarea
value={inputText}
onChange={(e) => setInputText(e.target.value)}
placeholder="A beautiful landscape with mountains and a lake at sunset..."
className="min-h-32 border-2 border-gray-200 focus:border-blue-400 rounded-lg p-3 w-full"
/>
</div>
{/* Translate Button */}
<Button
onClick={handleTranslate}
disabled={!inputText.trim() || isTranslating}
className="w-full bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white font-semibold py-3 text-lg"
>
{isTranslating ? (
<span className="flex items-center gap-2">
<div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
Translating...
</span>
) : (
<span className="flex items-center gap-2">
<Sparkles className="h-5 w-5" />
Translate to Jason Format
</span>
)}
</Button>
{/* Results */}
{jasonFormat && (
<div className="space-y-4 mt-6">
<div className="bg-gradient-to-r from-green-50 to-blue-50 border-2 border-green-200 rounded-lg p-4">
<div className="flex items-center justify-between mb-3">
<h4 className="font-semibold text-green-800 flex items-center gap-2">
<FileText className="h-5 w-5" />
Jason Format Result
</h4>
<div className="flex gap-2">
<Button
onClick={handleCopy}
variant="outline"
size="sm"
className="text-xs"
>
{copied ? (
<span className="flex items-center gap-1 text-green-600">
<span className="w-3 h-3 bg-green-600 rounded-full"></span>
Copied!
</span>
) : (
<span className="flex items-center gap-1">
<Copy className="h-3 w-3" />
Copy
</span>
)}
</Button>
<Button
onClick={handleDownload}
variant="outline"
size="sm"
className="text-xs"
>
<Download className="h-3 w-3 mr-1" />
Download
</Button>
</div>
</div>
<div className="bg-white rounded-lg p-3 border border-gray-200">
<pre className="text-sm text-gray-800 whitespace-pre-wrap break-words">
{JSON.stringify(jasonFormat, null, 2)}
</pre>
</div>
</div>
{/* Format Info */}
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
<h5 className="font-semibold text-blue-800 mb-2 flex items-center gap-2">
<Info className="h-4 w-4" />
About Jason Format
</h5>
<p className="text-sm text-blue-700">
Jason is a universal prompt language that works with all AI image generators.
It includes detailed style, mood, character, and item information for consistent results.
</p>
</div>
{/* Style Badges */}
<div className="flex flex-wrap gap-2">
{jasonFormat.style && (
<span className="bg-blue-100 text-blue-800 px-2 py-1 rounded text-xs">
Style: {jasonFormat.style}
</span>
)}
{jasonFormat.mood && (
<span className="bg-purple-100 text-purple-800 px-2 py-1 rounded text-xs">
Mood: {jasonFormat.mood}
</span>
)}
{jasonFormat.characters && jasonFormat.characters.length > 0 && (
<span className="bg-green-100 text-green-800 px-2 py-1 rounded text-xs">
Characters: {jasonFormat.characters.join(', ')}
</span>
)}
{jasonFormat.items && jasonFormat.items.length > 0 && (
<span className="bg-orange-100 text-orange-800 px-2 py-1 rounded text-xs">
Items: {jasonFormat.items.join(', ')}
</span>
)}
</div>
</div>
)}
</CardContent>
</Card>
)}
{/* NanoPrompt Optimizer */}
{activeTab === 'nano' && (
<Card className="mb-12 border-2 border-purple-200 shadow-xl">
<CardHeader className="bg-gradient-to-r from-purple-50 to-pink-50">
<CardTitle className="flex items-center gap-2 text-2xl">
<Sparkles className="h-6 w-6 text-purple-600" />
NanoPrompt Optimizer
</CardTitle>
<CardDescription className="text-lg">
Deep reverse engineering for maximum AI accuracy and performance
</CardDescription>
</CardHeader>
<CardContent className="space-y-6 p-6">
{/* Quick Templates */}
<div>
<h4 className="font-semibold text-gray-700 mb-3">Quick Templates:</h4>
<div className="grid grid-cols-2 md:grid-cols-4 gap-2">
{nanoQuickTemplates.map((template, index) => (
<Button
key={index}
variant="outline"
size="sm"
onClick={() => setInputText(template.text)}
className="text-xs h-auto py-2 px-3 whitespace-normal text-left"
>
{template.label}
</Button>
))}
</div>
</div>
{/* Input */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Enter your English prompt:
</label>
<textarea
value={inputText}
onChange={(e) => setInputText(e.target.value)}
placeholder="A beautiful portrait of a woman..."
className="min-h-32 border-2 border-gray-200 focus:border-purple-400 rounded-lg p-3 w-full"
/>
</div>
{/* Optimize Button */}
<Button
onClick={handleNanoOptimize}
disabled={!inputText.trim() || isOptimizing}
className="w-full bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 text-white font-semibold py-3 text-lg"
>
{isOptimizing ? (
<span className="flex items-center gap-2">
<div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
Optimizing...
</span>
) : (
<span className="flex items-center gap-2">
<Sparkles className="h-5 w-5" />
Optimize with NanoPrompt
</span>
)}
</Button>
{/* Results */}
{nanoPromptResult && (
<div className="space-y-4 mt-6">
<div className="bg-gradient-to-r from-purple-50 to-pink-50 border-2 border-purple-200 rounded-lg p-4">
<div className="flex items-center justify-between mb-3">
<h4 className="font-semibold text-purple-800 flex items-center gap-2">
<FileText className="h-5 w-5" />
NanoPrompt Optimization Result
</h4>
<div className="flex gap-2">
<Button
onClick={() => handleCopyNanoPrompt()}
variant="outline"
size="sm"
className="text-xs"
>
{copied ? (
<span className="flex items-center gap-1 text-green-600">
<span className="w-3 h-3 bg-green-600 rounded-full"></span>
Copied!
</span>
) : (
<span className="flex items-center gap-1">
<Copy className="h-3 w-3" />
Copy
</span>
)}
</Button>
<Button
onClick={() => handleDownloadNanoPrompt()}
variant="outline"
size="sm"
className="text-xs"
>
<Download className="h-3 w-3 mr-1" />
Download
</Button>
</div>
</div>
{/* Score */}
<div className="bg-white rounded-lg p-3 border border-gray-200 mb-3">
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-gray-700">Accuracy Score:</span>
<span className="text-lg font-bold text-green-600">{nanoPromptResult.accuracy_score}%</span>
</div>
</div>
{/* Original vs Optimized */}
<div className="grid md:grid-cols-2 gap-3 mb-3">
<div>
<div className="text-xs text-gray-500 font-medium mb-1">Original:</div>
<div className="bg-gray-50 rounded p-2 text-sm text-gray-800">
{nanoPromptResult.original_prompt}
</div>
</div>
<div>
<div className="text-xs text-gray-500 font-medium mb-1">Optimized:</div>
<div className="bg-purple-50 rounded p-2 text-sm text-purple-800">
{nanoPromptResult.nano_prompt}
</div>
</div>
</div>
{/* Optimizations Applied */}
<div className="mb-3">
<div className="text-xs text-gray-500 font-medium mb-1">Optimizations Applied:</div>
<div className="flex flex-wrap gap-1">
{nanoPromptResult.optimizations_applied.map((opt, index) => (
<span key={index} className="bg-purple-100 text-purple-700 text-xs px-2 py-1 rounded">
{opt}
</span>
))}
</div>
</div>
{/* Performance Tips */}
<div>
<div className="text-xs text-gray-500 font-medium mb-1">Performance Tips:</div>
<ul className="text-xs text-gray-700 space-y-1">
{nanoPromptResult.performance_tips.map((tip, index) => (
<li key={index} className="flex items-start gap-1">
<span className="w-1 h-1 bg-purple-600 rounded-full mt-2 flex-shrink-0"></span>
{tip}
</li>
))}
</ul>
</div>
</div>
{/* Jason Format */}
<div className="bg-gradient-to-r from-blue-50 to-purple-50 border-2 border-blue-200 rounded-lg p-4">
<h5 className="font-semibold text-blue-800 mb-2 flex items-center gap-2">
<Info className="h-4 w-4" />
Optimized Jason Format
</h5>
<div className="bg-white rounded-lg p-3 border border-gray-200">
<pre className="text-sm text-gray-800 whitespace-pre-wrap break-words">
{nanoPromptResult.jason_format}
</pre>
</div>
</div>
</div>
)}
</CardContent>
</Card>
)}
{/* NanoCoder Optimizer */}
{activeTab === 'code' && (
<Card className="mb-12 border-2 border-green-200 shadow-xl">
<CardHeader className="bg-gradient-to-r from-green-50 to-emerald-50">
<CardTitle className="flex items-center gap-2 text-2xl">
<Sparkles className="h-6 w-6 text-green-600" />
NanoCoder Technical Optimizer
</CardTitle>
<CardDescription className="text-lg">
Deep reverse engineering for maximum coding and engineering accuracy
</CardDescription>
</CardHeader>
<CardContent className="space-y-6 p-6">
{/* Quick Templates */}
<div>
<h4 className="font-semibold text-gray-700 mb-3">Technical Templates:</h4>
<div className="grid grid-cols-2 md:grid-cols-5 gap-2">
{nanoCoderQuickTemplates.map((template, index) => (
<Button
key={index}
variant="outline"
size="sm"
onClick={() => setInputText(template.text)}
className="text-xs h-auto py-2 px-3 whitespace-normal text-left"
>
{template.label}
</Button>
))}
</div>
</div>
{/* Input */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Enter your technical prompt:
</label>
<textarea
value={inputText}
onChange={(e) => setInputText(e.target.value)}
placeholder="React web application with TypeScript..."
className="min-h-32 border-2 border-gray-200 focus:border-green-400 rounded-lg p-3 w-full"
/>
</div>
{/* Optimize Button */}
<Button
onClick={handleNanoCode}
disabled={!inputText.trim() || isCoding}
className="w-full bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700 text-white font-semibold py-3 text-lg"
>
{isCoding ? (
<span className="flex items-center gap-2">
<div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
Optimizing...
</span>
) : (
<span className="flex items-center gap-2">
<Sparkles className="h-5 w-5" />
Optimize with NanoCoder
</span>
)}
</Button>
{/* Results */}
{nanoCoderResult && (
<div className="space-y-4 mt-6">
<div className="bg-gradient-to-r from-green-50 to-emerald-50 border-2 border-green-200 rounded-lg p-4">
<div className="flex items-center justify-between mb-3">
<h4 className="font-semibold text-green-800 flex items-center gap-2">
<FileText className="h-5 w-5" />
NanoCoder Technical Result
</h4>
<div className="flex gap-2">
<Button
onClick={() => handleCopyNanoCoder()}
variant="outline"
size="sm"
className="text-xs"
>
{copied ? (
<span className="flex items-center gap-1 text-green-600">
<span className="w-3 h-3 bg-green-600 rounded-full"></span>
Copied!
</span>
) : (
<span className="flex items-center gap-1">
<Copy className="h-3 w-3" />
Copy
</span>
)}
</Button>
<Button
onClick={() => handleDownloadNanoCoder()}
variant="outline"
size="sm"
className="text-xs"
>
<Download className="h-3 w-3 mr-1" />
Download
</Button>
</div>
</div>
{/* Score */}
<div className="bg-white rounded-lg p-3 border border-gray-200 mb-3">
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-gray-700">Technical Accuracy:</span>
<span className="text-lg font-bold text-green-600">{nanoCoderResult.accuracy_score}%</span>
</div>
</div>
{/* Original vs Optimized */}
<div className="grid md:grid-cols-2 gap-3 mb-3">
<div>
<div className="text-xs text-gray-500 font-medium mb-1">Original:</div>
<div className="bg-gray-50 rounded p-2 text-sm text-gray-800">
{nanoCoderResult.original_prompt}
</div>
</div>
<div>
<div className="text-xs text-gray-500 font-medium mb-1">Technical:</div>
<div className="bg-green-50 rounded p-2 text-sm text-green-800">
{nanoCoderResult.nano_coder_prompt}
</div>
</div>
</div>
{/* Technical Specifications */}
<div className="mb-3">
<div className="text-xs text-gray-500 font-medium mb-1">Technical Specifications:</div>
<div className="flex flex-wrap gap-1">
{nanoCoderResult.technical_specifications.map((spec, index) => (
<span key={index} className="bg-green-100 text-green-700 text-xs px-2 py-1 rounded">
{spec}
</span>
))}
</div>
</div>
{/* Code Context */}
{nanoCoderResult.code_context.length > 0 && (
<div className="mb-3">
<div className="text-xs text-gray-500 font-medium mb-1">Code Context:</div>
<div className="bg-blue-50 rounded p-2 text-xs text-blue-800">
{nanoCoderResult.code_context.join(', ')}
</div>
</div>
)}
{/* Performance Tips */}
<div>
<div className="text-xs text-gray-500 font-medium mb-1">Technical Tips:</div>
<ul className="text-xs text-gray-700 space-y-1">
{nanoCoderResult.performance_tips.map((tip, index) => (
<li key={index} className="flex items-start gap-1">
<span className="w-1 h-1 bg-green-600 rounded-full mt-2 flex-shrink-0"></span>
{tip}
</li>
))}
</ul>
</div>
</div>
{/* Technical Jason Format */}
<div className="bg-gradient-to-r from-blue-50 to-green-50 border-2 border-blue-200 rounded-lg p-4">
<h5 className="font-semibold text-blue-800 mb-2 flex items-center gap-2">
<Info className="h-4 w-4" />
Technical Jason Format
</h5>
<div className="bg-white rounded-lg p-3 border border-gray-200">
<pre className="text-sm text-gray-800 whitespace-pre-wrap break-words">
{nanoCoderResult.jason_format}
</pre>
</div>
</div>
</div>
)}
</CardContent>
</Card>
)}
{/* Developer Section */}
<div className="mt-16 text-center py-8 border-t border-gray-200">
<div className="bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg p-6 max-w-4xl mx-auto">
<h3 className="text-lg font-semibold text-gray-800 mb-4">Developed by Roman | RyzenAdvanced</h3>
<div className="flex flex-col md:flex-row justify-center items-center gap-6 text-sm text-gray-600">
<div className="flex items-center gap-2">
<span className="font-medium">GitHub:</span>
<a
href="https://github.com/roman-ryzenadvanced/Custom-Engineered-Agents-and-Tools-for-Vibe-Coders"
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:text-blue-800 underline"
>
Custom Engineered Agents and Tools for Vibe Coders
</a>
</div>
<div className="flex items-center gap-2">
<span className="font-medium">Tools:</span>
<a
href="https://z.ai/subscribe?ic=R0K78RJKNW"
target="_blank"
rel="noopener noreferrer"
className="text-green-600 hover:text-green-800 underline"
>
GLM 4.6 Coding Model
</a>
</div>
<div className="flex items-center gap-2">
<span className="font-medium">Built with:</span>
<a
href="https://www.trae.ai/s/WJtxyE"
target="_blank"
rel="noopener noreferrer"
className="text-purple-600 hover:text-purple-800 underline"
>
TRAE IDE
</a>
</div>
</div>
</div>
</div>
</div>
</div>
)
}

View File

@@ -0,0 +1,76 @@
import { Sparkles, Github, Twitter, Mail } from "lucide-react"
export function Footer() {
return (
<footer className="border-t bg-white">
<div className="container mx-auto px-4 py-12">
<div className="grid md:grid-cols-4 gap-8">
<div className="space-y-4">
<div className="flex items-center space-x-2">
<Sparkles className="h-6 w-6 bg-gradient-to-r from-blue-600 to-purple-600" />
<span className="font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">NanoJason</span>
</div>
<p className="text-sm text-gray-600">
Transform your ideas into stunning visual stories with AI-powered image generation.
</p>
<div className="flex space-x-4">
<a href="#" className="text-gray-600 hover:text-gray-900">
<Github className="h-4 w-4" />
<span className="sr-only">GitHub</span>
</a>
<a href="#" className="text-gray-600 hover:text-gray-900">
<Twitter className="h-4 w-4" />
<span className="sr-only">Twitter</span>
</a>
<a href="#" className="text-gray-600 hover:text-gray-900">
<Mail className="h-4 w-4" />
<span className="sr-only">Email</span>
</a>
</div>
</div>
<div className="space-y-4">
<h4 className="text-sm font-semibold">Product</h4>
<ul className="space-y-2 text-sm text-gray-600">
<li><a href="#" className="hover:text-gray-900">Features</a></li>
<li><a href="#" className="hover:text-gray-900">Gallery</a></li>
<li><a href="#" className="hover:text-gray-900">API</a></li>
<li><a href="#" className="hover:text-gray-900">Pricing</a></li>
</ul>
</div>
<div className="space-y-4">
<h4 className="text-sm font-semibold">Resources</h4>
<ul className="space-y-2 text-sm text-gray-600">
<li><a href="#" className="hover:text-gray-900">Documentation</a></li>
<li><a href="#" className="hover:text-gray-900">Tutorials</a></li>
<li><a href="#" className="hover:text-gray-900">Blog</a></li>
<li><a href="#" className="hover:text-gray-900">Community</a></li>
</ul>
</div>
<div className="space-y-4">
<h4 className="text-sm font-semibold">Company</h4>
<ul className="space-y-2 text-sm text-gray-600">
<li><a href="#" className="hover:text-gray-900">About</a></li>
<li><a href="#" className="hover:text-gray-900">Contact</a></li>
<li><a href="#" className="hover:text-gray-900">Privacy</a></li>
<li><a href="#" className="hover:text-gray-900">Terms</a></li>
</ul>
</div>
</div>
<div className="mt-8 pt-8 border-t border-gray-200">
<div className="flex flex-col md:flex-row justify-between items-center">
<p className="text-sm text-gray-600">
© 2024 NanoJason. All rights reserved.
</p>
<p className="text-sm text-gray-600 mt-2 md:mt-0">
Powered by Qwen AI and Next.js
</p>
</div>
</div>
</div>
</footer>
)
}

View File

@@ -0,0 +1,59 @@
'use client'
import Link from "next/link"
import { Sparkles, Github, FileText } from "lucide-react"
import { Button } from "@/components/ui/button"
export function Header() {
return (
<header className="bg-white/80 backdrop-blur-md border-b border-gray-200 sticky top-0 z-50">
<div className="container mx-auto px-4 h-16 flex items-center justify-between">
<div className="flex items-center gap-2">
<Sparkles className="h-6 w-6 text-blue-600" />
<Link href="/" className="text-xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
NanoJason
</Link>
</div>
<nav className="hidden md:flex items-center gap-6">
<Link
href="/"
className="text-gray-600 hover:text-blue-600 transition-colors font-medium"
>
Translator
</Link>
<Link
href="https://github.com/your-username/nanojason"
target="_blank"
rel="noopener noreferrer"
className="text-gray-600 hover:text-blue-600 transition-colors font-medium flex items-center gap-1"
>
<Github className="h-4 w-4" />
GitHub
</Link>
<Link
href="https://jasonformat.org/docs"
target="_blank"
rel="noopener noreferrer"
className="text-gray-600 hover:text-blue-600 transition-colors font-medium flex items-center gap-1"
>
<FileText className="h-4 w-4" />
Docs
</Link>
</nav>
<div className="flex items-center gap-2">
<Button
asChild
variant="outline"
size="sm"
>
<Link href="/">
Get Started
</Link>
</Button>
</div>
</div>
</header>
)
}

View File

@@ -0,0 +1,56 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
default: "bg-blue-600 text-white hover:bg-blue-700",
destructive:
"bg-red-600 text-white hover:bg-red-700",
outline:
"border border-gray-300 bg-white hover:bg-gray-50 hover:text-gray-900",
secondary:
"bg-gray-100 text-gray-900 hover:bg-gray-200",
ghost: "hover:bg-gray-100 hover:text-gray-900",
link: "text-blue-600 underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }

View File

@@ -0,0 +1,79 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-lg border border-gray-200 bg-white text-gray-900 shadow-sm",
className
)}
{...props}
/>
))
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h3
ref={ref}
className={cn(
"text-2xl font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<p
ref={ref}
className={cn("text-sm text-gray-600", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }

View File

@@ -0,0 +1,25 @@
import * as React from "react"
import { cn } from "@/lib/utils"
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }

6
src/lib/utils.ts Normal file
View File

@@ -0,0 +1,6 @@
import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

View File

@@ -0,0 +1,262 @@
// Jason Language Translator - Offline-only version
// Converts natural language to Jason format for universal AI compatibility
export interface JasonFormat {
jason_text: string
style: string
mood: string
characters: string[]
items: string[]
setting?: string
action?: string
color_palette?: string[]
composition?: string
lighting?: string
quality?: string
}
export class JasonTranslator {
// Style detection patterns
private stylePatterns = {
realistic: ['photo', 'realistic', 'photograph', 'lifelike', 'real', 'actual'],
anime: ['anime', 'manga', 'japanese', 'studio ghibli', 'akira', 'naruto'],
fantasy: ['fantasy', 'magical', 'dragon', 'wizard', 'elf', 'fairy', 'mythical'],
scifi: ['sci-fi', 'futuristic', 'cyberpunk', 'space', 'robot', 'alien', 'technology'],
cartoon: ['cartoon', 'disney', 'pixar', 'animated', 'character', 'funny'],
oil: ['oil painting', 'canvas', 'brushstrokes', 'classical', 'renaissance'],
watercolor: ['watercolor', 'watercolor painting', 'soft', 'flowing', 'transparent'],
pixel: ['pixel art', '8-bit', '16-bit', 'retro', 'pixelated', 'minecraft'],
abstract: ['abstract', 'geometric', 'shapes', 'patterns', 'modern art'],
vintage: ['vintage', 'retro', 'old', 'antique', 'classic', '1950s', '1960s'],
minimal: ['minimal', 'simple', 'clean', 'minimalist', 'basic'],
detailed: ['detailed', 'intricate', 'complex', 'elaborate', 'fine details']
}
// Mood detection patterns
private moodPatterns = {
happy: ['happy', 'joyful', 'cheerful', 'smiling', 'bright', 'sunny'],
sad: ['sad', 'melancholy', 'somber', 'gloomy', 'depressed', 'tears'],
epic: ['epic', 'dramatic', 'heroic', 'grand', 'massive', 'breathtaking'],
peaceful: ['peaceful', 'calm', 'serene', 'tranquil', 'quiet', 'relaxing'],
mysterious: ['mysterious', 'foggy', 'dark', 'hidden', 'secret', 'enigmatic'],
energetic: ['energetic', 'dynamic', 'action', 'movement', 'fast', 'powerful'],
romantic: ['romantic', 'love', 'heart', 'candlelight', 'intimate', 'passionate'],
scary: ['scary', 'horror', 'creepy', 'dark', 'fear', 'terror']
}
// Character detection patterns
private characterPatterns = [
'person', 'man', 'woman', 'child', 'boy', 'girl', 'baby',
'wizard', 'witch', 'dragon', 'knight', 'princess', 'king', 'queen',
'robot', 'alien', 'cyborg', 'monster', 'ghost', 'vampire',
'animal', 'cat', 'dog', 'bird', 'lion', 'tiger', 'elephant',
'fairy', 'elf', 'dwarf', 'orc', 'angel', 'demon'
]
// Item detection patterns
private itemPatterns = [
'sword', 'shield', 'armor', 'crown', 'wand', 'staff', 'book',
'car', 'airplane', 'boat', 'ship', 'train', 'bicycle',
'house', 'castle', 'building', 'tower', 'bridge', 'road',
'tree', 'flower', 'mountain', 'river', 'lake', 'ocean',
'computer', 'phone', 'tablet', 'camera', 'television', 'game',
'food', 'pizza', 'cake', 'coffee', 'wine', 'fruit'
]
async translateToJason(text: string): Promise<JasonFormat> {
const lowerText = text.toLowerCase()
return {
jason_text: this.createJasonText(text),
style: this.detectStyle(lowerText),
mood: this.detectMood(lowerText),
characters: this.detectCharacters(lowerText),
items: this.detectItems(lowerText),
setting: this.extractSetting(lowerText),
action: this.extractAction(lowerText),
color_palette: this.extractColors(lowerText),
composition: this.extractComposition(lowerText),
lighting: this.extractLighting(lowerText),
quality: 'high'
}
}
private createJasonText(text: string): string {
const jasonStructure = {
prompt: text,
version: '1.0',
type: 'image_generation',
metadata: {
created_by: 'NanoJason',
timestamp: new Date().toISOString()
}
}
return JSON.stringify(jasonStructure, null, 2)
}
private detectStyle(text: string): string {
for (const [style, patterns] of Object.entries(this.stylePatterns)) {
if (patterns.some(pattern => text.includes(pattern))) {
return style
}
}
return 'realistic' // Default style
}
private detectMood(text: string): string {
for (const [mood, patterns] of Object.entries(this.moodPatterns)) {
if (patterns.some(pattern => text.includes(pattern))) {
return mood
}
}
return 'neutral' // Default mood
}
private detectCharacters(text: string): string[] {
const foundCharacters: string[] = []
for (const character of this.characterPatterns) {
if (text.includes(character)) {
foundCharacters.push(character)
}
}
return foundCharacters.slice(0, 5) // Limit to 5 characters
}
private detectItems(text: string): string[] {
const foundItems: string[] = []
for (const item of this.itemPatterns) {
if (text.includes(item)) {
foundItems.push(item)
}
}
return foundItems.slice(0, 8) // Limit to 8 items
}
private extractSetting(text: string): string | undefined {
const settingPatterns = [
'forest', 'city', 'beach', 'mountain', 'desert', 'ocean',
'space', 'underwater', 'cave', 'castle', 'house', 'garden',
'street', 'office', 'school', 'hospital', 'restaurant', 'park'
]
for (const setting of settingPatterns) {
if (text.includes(setting)) {
return setting
}
}
return undefined
}
private extractAction(text: string): string | undefined {
const actionPatterns = [
'running', 'walking', 'sitting', 'standing', 'flying', 'swimming',
'fighting', 'dancing', 'singing', 'reading', 'writing', 'cooking',
'sleeping', 'playing', 'working', 'traveling', 'exploring', 'building'
]
for (const action of actionPatterns) {
if (text.includes(action)) {
return action
}
}
return undefined
}
private extractColors(text: string): string[] {
const colorPatterns = [
'red', 'blue', 'green', 'yellow', 'orange', 'purple', 'pink',
'black', 'white', 'gray', 'brown', 'gold', 'silver',
'cyan', 'magenta', 'lime', 'navy', 'teal', 'indigo'
]
const foundColors: string[] = []
for (const color of colorPatterns) {
if (text.includes(color)) {
foundColors.push(color)
}
}
return foundColors.slice(0, 6) // Limit to 6 colors
}
private extractComposition(text: string): string | undefined {
const compositionPatterns = [
'portrait', 'landscape', 'close-up', 'wide shot', 'aerial view',
'macro', 'panorama', 'bird\'s eye view', 'low angle', 'high angle'
]
for (const composition of compositionPatterns) {
if (text.includes(composition)) {
return composition
}
}
return undefined
}
private extractLighting(text: string): string | undefined {
const lightingPatterns = [
'sunlight', 'moonlight', 'sunrise', 'sunset', 'dawn', 'dusk',
'neon', 'candlelight', 'spotlight', 'natural', 'artificial',
'bright', 'dark', 'dim', 'glowing', 'shadows'
]
for (const lighting of lightingPatterns) {
if (text.includes(lighting)) {
return lighting
}
}
return undefined
}
// Quick template generators
generateQuickTemplate(type: 'portrait' | 'landscape' | 'action' | 'fantasy' | 'sci-fi'): string {
const templates = {
portrait: 'A detailed portrait of a person with expressive eyes and soft lighting',
landscape: 'A beautiful landscape with mountains, trees, and dramatic lighting',
action: 'An action scene with dynamic movement and intense emotions',
fantasy: 'A magical fantasy scene with mystical creatures and enchanted elements',
'sci-fi': 'A futuristic sci-fi scene with advanced technology and alien worlds'
}
return templates[type]
}
// Validate Jason format
validateJasonFormat(format: JasonFormat): { isValid: boolean; errors: string[] } {
const errors: string[] = []
if (!format.jason_text || format.jason_text.trim() === '') {
errors.push('Jason text is required')
}
if (!format.style) {
errors.push('Style is required')
}
if (!format.mood) {
errors.push('Mood is required')
}
if (!format.characters || format.characters.length === 0) {
errors.push('At least one character is recommended')
}
return {
isValid: errors.length === 0,
errors
}
}
}
// Create singleton instance
export const jasonTranslator = new JasonTranslator()

315
src/services/nano-coder.ts Normal file
View File

@@ -0,0 +1,315 @@
// NanoCoder - Deep Reverse Engineered Jason Prompt Optimizer for Coding/Engineering
// Translates coding/engineering requests into optimized Jason prompts for maximum AI accuracy
export interface NanoCoderResult {
original_prompt: string
nano_coder_prompt: string
jason_format: string
technical_specifications: string[]
accuracy_score: number
performance_tips: string[]
code_context: string[]
}
export class NanoCoder {
// Technical programming patterns
private technicalPatterns = {
// Software development
programming: ['code', 'algorithm', 'function', 'class', 'method', 'variable', 'array', 'object', 'loop', 'conditional', 'recursion', 'data structure', 'API', 'framework', 'library', 'dependency'],
// System architecture
architecture: ['microservice', 'monolith', 'serverless', 'container', 'docker', 'kubernetes', 'architecture', 'design pattern', 'scalability', 'performance', 'security', 'reliability'],
// Web development
webdev: ['frontend', 'backend', 'fullstack', 'React', 'Vue', 'Angular', 'Node.js', 'Python', 'JavaScript', 'TypeScript', 'HTML', 'CSS', 'database', 'REST', 'GraphQL', 'SPA'],
// Mobile development
mobile: ['iOS', 'Android', 'React Native', 'Flutter', 'Xamarin', 'mobile app', 'cross-platform', 'native', 'responsive', 'touch interface'],
// DevOps
devops: ['CI/CD', 'pipeline', 'deployment', 'testing', 'monitoring', 'logging', 'analytics', 'automation', 'infrastructure as code', 'terraform'],
// Data & AI
dataai: ['machine learning', 'neural network', 'deep learning', 'training data', 'model', 'dataset', 'feature engineering', 'hyperparameters', 'inference'],
// Quality & Testing
quality: ['unit test', 'integration test', 'end-to-end test', 'debugging', 'refactoring', 'code review', 'performance test', 'load test', 'stress test'],
// Security
security: ['authentication', 'authorization', 'encryption', 'firewall', 'vulnerability', 'patch', 'compliance', 'security audit', 'penetration testing'],
// Performance
performance: ['optimization', 'caching', 'lazy loading', 'asynchronous', 'concurrency', 'threading', 'memory management', 'garbage collection']
}
// Technical optimization keywords
private technicalOptimizations = {
quality: [
'clean code', 'SOLID principles', 'DRY', 'KISS', 'best practices', 'technical debt',
'readability', 'maintainability', 'scalability', 'extensibility', 'modularity'
],
performance: [
'high-performance', 'efficient', 'optimized', 'fast', 'low-latency', 'high-throughput',
'responsive', 'asynchronous', 'parallel processing', 'caching strategy'
],
architecture: [
'well-architected', 'distributed', 'cloud-native', 'event-driven', 'microservices',
'service-oriented', 'domain-driven', 'clean architecture', 'hexagonal'
],
security: [
'secure by design', 'zero-trust', 'encrypted', 'authenticated', 'authorized',
'compliant', 'auditable', 'secure coding', 'OWASP standards'
],
testing: [
'test-driven', 'behavior-driven', 'continuous integration', 'automated testing',
'test coverage', 'mocking', 'stubbing', 'integration testing'
]
}
// Code-specific enhancement patterns
private codePatterns = {
languages: {
javascript: ['ES6+', 'async/await', 'promises', 'modules', 'destructuring', 'arrow functions'],
typescript: ['strong typing', 'interfaces', 'generics', 'type guards', 'decorators'],
python: ['dynamic typing', 'list comprehensions', 'decorators', 'generators', 'asyncio'],
java: ['OOP', 'interfaces', 'abstract classes', 'generics', 'concurrency'],
rust: ['memory safety', 'borrow checker', 'zero-cost abstractions', 'concurrency'],
go: ['concurrent', 'interfaces', 'goroutines', 'channels', 'garbage collector']
},
frameworks: {
react: ['components', 'hooks', 'state management', 'virtual DOM', 'React Fiber'],
vue: ['progressive framework', 'single file components', 'composition API', 'reactivity'],
angular: ['dependency injection', 'modules', 'decorators', 'change detection'],
node: ['event-driven', 'non-blocking', 'NPM', 'ECMAScript'],
django: ['MVT', 'ORM', 'admin interface', 'template engine'],
spring: ['dependency injection', 'AOP', 'transaction management', 'security']
}
}
async optimizePrompt(technicalPrompt: string): Promise<NanoCoderResult> {
const technical_specifications: string[] = []
let optimizedPrompt = technicalPrompt.toLowerCase()
// Step 1: Detect technical domain
const domain = this.detectTechnicalDomain(optimizedPrompt)
if (domain) {
optimizedPrompt = this.enhanceTechnicalDomain(optimizedPrompt, domain, technical_specifications)
}
// Step 2: Apply technical patterns
optimizedPrompt = this.applyTechnicalPatterns(optimizedPrompt, technical_specifications)
// Step 3: Add technical optimizations
optimizedPrompt = this.addTechnicalOptimizations(optimizedPrompt, technical_specifications)
// Step 4: Enhance with code context
const codeContext = this.extractCodeContext(optimizedPrompt)
// Step 5: Generate technical Jason format
const jasonFormat = this.generateTechnicalJasonFormat(optimizedPrompt, domain || 'general', codeContext)
// Step 6: Calculate accuracy score
const accuracyScore = this.calculateTechnicalAccuracy(technical_specifications)
// Step 7: Generate performance tips
const performanceTips = this.generateTechnicalTips(technical_specifications, domain || 'general')
return {
original_prompt: technicalPrompt,
nano_coder_prompt: optimizedPrompt,
jason_format: jasonFormat,
technical_specifications: technical_specifications,
accuracy_score: accuracyScore,
performance_tips: performanceTips,
code_context: codeContext
}
}
private detectTechnicalDomain(prompt: string): string | null {
for (const [domain, patterns] of Object.entries(this.technicalPatterns)) {
if (patterns.some(pattern => prompt.includes(pattern))) {
return domain
}
}
return null
}
private enhanceTechnicalDomain(prompt: string, domain: string, specifications: string[]): string {
const enhancement = this.getDomainEnhancement(domain)
if (enhancement) {
const enhanced = `${prompt}, ${enhancement}`
specifications.push(`Domain enhancement: Added "${enhancement}" for ${domain}`)
return enhanced
}
return prompt
}
private getDomainEnhancement(domain: string): string {
const enhancements = {
programming: 'well-structured and maintainable',
architecture: 'scalable and secure architecture',
webdev: 'responsive and accessible web application',
mobile: 'cross-platform mobile solution',
devops: 'automated and reliable deployment',
dataai: 'efficient and scalable data processing',
quality: 'comprehensive testing strategy',
security: 'enterprise-grade security measures',
performance: 'high-performance optimization'
}
return enhancements[domain as keyof typeof enhancements] || 'technical excellence'
}
private applyTechnicalPatterns(prompt: string, specifications: string[]): string {
let optimized = prompt
// Apply programming patterns
const programmingPatterns = ['clean code', 'DRY principle', 'SOLID principles']
const selectedPattern = programmingPatterns[Math.floor(Math.random() * programmingPatterns.length)]
if (!optimized.includes(selectedPattern)) {
optimized = `${optimized}, ${selectedPattern}`
specifications.push(`Programming pattern: Applied "${selectedPattern}"`)
}
return optimized
}
private addTechnicalOptimizations(prompt: string, specifications: string[]): string {
const optimizationTypes = ['quality', 'performance', 'architecture', 'security']
const selectedType = optimizationTypes[Math.floor(Math.random() * optimizationTypes.length)]
const optimizations = this.technicalOptimizations[selectedType as keyof typeof this.technicalOptimizations]
const selectedOptimization = optimizations[Math.floor(Math.random() * optimizations.length)]
if (!prompt.includes(selectedOptimization)) {
const enhanced = `${prompt}, ${selectedOptimization}`
specifications.push(`${selectedType} optimization: Added "${selectedOptimization}"`)
return enhanced
}
return prompt
}
private extractCodeContext(prompt: string): string[] {
const context: string[] = []
// Detect programming languages
for (const [language, patterns] of Object.entries(this.codePatterns.languages)) {
if (patterns.some(pattern => prompt.includes(pattern)) || prompt.includes(language)) {
context.push(`Programming Language: ${language.toUpperCase()}`)
}
}
// Detect frameworks
for (const [framework, patterns] of Object.entries(this.codePatterns.frameworks)) {
if (patterns.some(pattern => prompt.includes(pattern)) || prompt.includes(framework)) {
context.push(`Framework: ${framework.charAt(0).toUpperCase() + framework.slice(1)}`)
}
}
return context.slice(0, 5) // Limit to 5 context items
}
private generateTechnicalJasonFormat(optimizedPrompt: string, domain: string, codeContext: string[]): string {
const jasonStructure = {
prompt: optimizedPrompt,
version: '3.0', // Technical optimization version
type: 'technical_optimization',
optimization: {
domain: domain || 'general',
technical_level: 'advanced',
context: codeContext,
focus: 'technical_excellence'
},
metadata: {
created_by: 'NanoCoder',
optimization_level: 'deep_reverse_engineered_technical',
timestamp: new Date().toISOString()
}
}
return JSON.stringify(jasonStructure, null, 2)
}
private calculateTechnicalAccuracy(specifications: string[]): number {
// Base score starts at 70%
let score = 70
// Add points for technical enhancements
score += specifications.length * 5
// Domain bonuses
score += 10 // Technical domain recognition bonus
// Cap at 98%
return Math.min(98, score)
}
private generateTechnicalTips(specifications: string[], domain: string): string[] {
const tips: string[] = []
// Domain-specific tips
if (domain === 'programming') {
tips.push('Focus on clean, readable code with proper error handling')
tips.push('Consider testing strategies from the beginning')
} else if (domain === 'architecture') {
tips.push('Plan for scalability and future requirements')
tips.push('Consider security implications of architectural decisions')
} else if (domain === 'webdev') {
tips.push('Ensure cross-browser compatibility and responsive design')
tips.push('Optimize for performance and user experience')
} else if (domain === 'mobile') {
tips.push('Consider platform-specific guidelines and user experience')
tips.push('Optimize for mobile performance and battery usage')
} else if (domain === 'dataai') {
tips.push('Ensure data quality and proper validation')
tips.push('Consider ethical implications and data privacy')
}
// General technical tips
if (specifications.some(spec => spec.includes('quality'))) {
tips.push('Code quality improvements reduce maintenance costs')
}
if (specifications.some(spec => spec.includes('performance'))) {
tips.push('Performance optimizations should be measured and tested')
}
if (specifications.some(spec => spec.includes('security'))) {
tips.push('Security should be implemented throughout the development lifecycle')
}
return tips
}
// Technical quick templates
generateTechnicalTemplate(type: 'webapp' | 'mobileapp' | 'microservice' | 'api' | 'dashboard'): string {
const templates = {
webapp: 'React web application with TypeScript, clean architecture, responsive design, modern UI components, secure authentication',
mobileapp: 'React Native mobile application, cross-platform solution, native performance, intuitive UI, offline capabilities',
microservice: 'Node.js microservice with REST API, scalable architecture, Docker containerization, Kubernetes deployment',
api: 'REST API with Node.js/Express, database integration, authentication middleware, rate limiting, comprehensive documentation',
dashboard: 'Data visualization dashboard with React, real-time updates, responsive design, interactive charts, data analytics'
}
return templates[type]
}
// Batch optimization for technical prompts
async optimizeTechnicalBatch(prompts: string[]): Promise<NanoCoderResult[]> {
const results: NanoCoderResult[] = []
for (const prompt of prompts) {
try {
const result = await this.optimizePrompt(prompt)
results.push(result)
} catch (error) {
console.error(`Failed to optimize technical prompt: ${prompt}`, error)
}
}
return results
}
}
// Create singleton instance
export const nanoCoder = new NanoCoder()

374
src/services/nano-prompt.ts Normal file
View File

@@ -0,0 +1,374 @@
// NanoPrompt - Deep Reverse Engineered Jason Prompt Optimizer
// Translates English requests into optimized Jason prompts for maximum AI accuracy
export interface NanoPromptResult {
original_prompt: string
nano_prompt: string
jason_format: string
optimizations_applied: string[]
accuracy_score: number
performance_tips: string[]
}
export class NanoPrompt {
// AI model optimization patterns
private modelOptimizations = {
// Quality descriptors for maximum detail
quality: [
'ultra-detailed', 'high-resolution', 'photorealistic', '8k', '4k',
'masterpiece', 'best quality', 'highest detail', 'professional',
'award-winning', 'cinematic quality', 'hyperrealistic'
],
// Style-specific keywords
styles: {
realistic: ['photorealistic', 'lifelike', 'natural lighting', 'real-world', 'detailed texture'],
anime: ['anime style', 'manga art', 'japanese animation', 'studio ghibli style', 'cel shading'],
fantasy: ['fantasy art', 'magical', 'enchanted', 'mythical', 'ethereal', 'dreamlike'],
scifi: ['sci-fi art', 'futuristic', 'cyberpunk aesthetic', 'high-tech', 'advanced technology'],
abstract: ['abstract art', 'geometric patterns', 'modern art', 'contemporary', 'artistic']
},
// Composition and framing
composition: [
'perfect composition', 'rule of thirds', 'golden ratio', 'balanced framing',
'dynamic perspective', 'depth of field', 'bokeh effect', 'professional photography'
],
// Lighting keywords
lighting: [
'dramatic lighting', 'cinematic lighting', 'volumetric lighting', 'soft shadows',
'golden hour', 'blue hour', 'rim lighting', 'three-point lighting', 'natural light'
],
// Color enhancement
colors: [
'vibrant colors', 'color harmony', 'color grading', 'professional color palette',
'rich saturation', 'accurate colors', 'color correction', 'cinematic color grading'
],
// Detail and texture
details: [
'intricate details', 'fine textures', 'surface details', 'micro details',
'hyper-detailed', 'pixel-perfect', 'sharp focus', 'crisp details'
],
// Error elimination patterns
error_prevention: [
'no distortion', 'no artifacts', 'clean image', 'no noise',
'no blur', 'proper anatomy', 'correct proportions', 'no glitches'
]
}
// Common English patterns and their Jason equivalents
private patternMappings = {
// Basic descriptions
'a picture of': 'high-quality photograph of',
'an image of': 'professional photograph of',
'drawing of': 'detailed illustration of',
'painting of': 'masterpiece painting of',
'photo of': 'ultra-realistic photograph of',
// Quality improvements
'nice': 'exceptional',
'good': 'outstanding',
'beautiful': 'breathtakingly beautiful',
'pretty': 'stunningly attractive',
'cool': 'impressive',
'amazing': 'extraordinary',
// Style specifications
'simple': 'elegant minimalist',
'complex': 'intricate detailed',
'modern': 'contemporary sophisticated',
'old': 'vintage classic',
'new': 'cutting-edge',
// Lighting improvements
'bright': 'well-lit with bright illumination',
'dark': 'dramatic low-key lighting',
'sunny': 'golden hour sunlight',
'night': 'cinematic night lighting',
// Composition
'close up': 'detailed close-up shot',
'wide': 'expansive wide-angle view',
'top': 'bird\'s eye view',
'side': 'profile perspective',
// Error prevention
'without': 'excluding',
'no': 'absence of',
'avoid': 'carefully avoiding',
'don\'t': 'ensuring no'
}
async optimizePrompt(englishPrompt: string): Promise<NanoPromptResult> {
const optimizations_applied: string[] = []
let optimizedPrompt = englishPrompt.toLowerCase()
// Step 1: Apply pattern mappings
optimizedPrompt = this.applyPatternMappings(optimizedPrompt, optimizations_applied)
// Step 2: Detect and enhance style
const detectedStyle = this.detectStyle(optimizedPrompt)
if (detectedStyle) {
optimizedPrompt = this.enhanceStyle(optimizedPrompt, detectedStyle, optimizations_applied)
}
// Step 3: Add quality descriptors
optimizedPrompt = this.addQualityDescriptors(optimizedPrompt, optimizations_applied)
// Step 4: Optimize composition
optimizedPrompt = this.optimizeComposition(optimizedPrompt, optimizations_applied)
// Step 5: Enhance lighting
optimizedPrompt = this.enhanceLighting(optimizedPrompt, optimizations_applied)
// Step 6: Add color optimization
optimizedPrompt = this.optimizeColors(optimizedPrompt, optimizations_applied)
// Step 7: Add detail enhancement
optimizedPrompt = this.enhanceDetails(optimizedPrompt, optimizations_applied)
// Step 8: Add error prevention
optimizedPrompt = this.addErrorPrevention(optimizedPrompt, optimizations_applied)
// Step 9: Generate Jason format
const jasonFormat = this.generateJasonFormat(optimizedPrompt, detectedStyle)
// Step 10: Calculate accuracy score
const accuracyScore = this.calculateAccuracyScore(optimizations_applied)
// Step 11: Generate performance tips
const performanceTips = this.generatePerformanceTips(optimizations_applied, detectedStyle)
return {
original_prompt: englishPrompt,
nano_prompt: optimizedPrompt,
jason_format: jasonFormat,
optimizations_applied: optimizations_applied,
accuracy_score: accuracyScore,
performance_tips: performanceTips
}
}
private applyPatternMappings(prompt: string, optimizations: string[]): string {
let optimized = prompt
for (const [pattern, replacement] of Object.entries(this.patternMappings)) {
if (optimized.includes(pattern)) {
optimized = optimized.replace(new RegExp(pattern, 'g'), replacement)
optimizations.push(`Pattern mapping: "${pattern}" → "${replacement}"`)
}
}
return optimized
}
private detectStyle(prompt: string): string {
for (const [style, keywords] of Object.entries(this.modelOptimizations.styles)) {
if (keywords.some(keyword => prompt.includes(keyword))) {
return style
}
}
return 'realistic' // Default style
}
private enhanceStyle(prompt: string, style: string, optimizations: string[]): string {
const styleKeywords = this.modelOptimizations.styles[style as keyof typeof this.modelOptimizations.styles]
if (styleKeywords) {
const keyword = styleKeywords[Math.floor(Math.random() * styleKeywords.length)]
if (!prompt.includes(keyword)) {
const enhanced = `${prompt}, ${keyword}`
optimizations.push(`Style enhancement: Added "${keyword}" for ${style} style`)
return enhanced
}
}
return prompt
}
private addQualityDescriptors(prompt: string, optimizations: string[]): string {
const qualityKeywords = this.modelOptimizations.quality
const selectedQuality = qualityKeywords[Math.floor(Math.random() * Math.min(3, qualityKeywords.length))]
if (!prompt.includes(selectedQuality) && !prompt.includes('quality')) {
const enhanced = `${prompt}, ${selectedQuality}`
optimizations.push(`Quality enhancement: Added "${selectedQuality}"`)
return enhanced
}
return prompt
}
private optimizeComposition(prompt: string, optimizations: string[]): string {
const compositionKeywords = this.modelOptimizations.composition
const selectedComposition = compositionKeywords[Math.floor(Math.random() * compositionKeywords.length)]
if (!prompt.includes('composition') && !prompt.includes('framing')) {
const enhanced = `${prompt}, ${selectedComposition}`
optimizations.push(`Composition optimization: Added "${selectedComposition}"`)
return enhanced
}
return prompt
}
private enhanceLighting(prompt: string, optimizations: string[]): string {
const lightingKeywords = this.modelOptimizations.lighting
const selectedLighting = lightingKeywords[Math.floor(Math.random() * lightingKeywords.length)]
if (!prompt.includes('lighting') && !prompt.includes('light')) {
const enhanced = `${prompt}, ${selectedLighting}`
optimizations.push(`Lighting enhancement: Added "${selectedLighting}"`)
return enhanced
}
return prompt
}
private optimizeColors(prompt: string, optimizations: string[]): string {
const colorKeywords = this.modelOptimizations.colors
const selectedColor = colorKeywords[Math.floor(Math.random() * colorKeywords.length)]
if (!prompt.includes('color') && !prompt.includes('saturation')) {
const enhanced = `${prompt}, ${selectedColor}`
optimizations.push(`Color optimization: Added "${selectedColor}"`)
return enhanced
}
return prompt
}
private enhanceDetails(prompt: string, optimizations: string[]): string {
const detailKeywords = this.modelOptimizations.details
const selectedDetail = detailKeywords[Math.floor(Math.random() * detailKeywords.length)]
if (!prompt.includes('detail') && !prompt.includes('texture')) {
const enhanced = `${prompt}, ${selectedDetail}`
optimizations.push(`Detail enhancement: Added "${selectedDetail}"`)
return enhanced
}
return prompt
}
private addErrorPrevention(prompt: string, optimizations: string[]): string {
const errorKeywords = this.modelOptimizations.error_prevention
const selectedErrorPrevention = errorKeywords[Math.floor(Math.random() * 2)] // Use 2 for less aggressive
if (!prompt.includes('no') && !prompt.includes('without')) {
const enhanced = `${prompt}, ${selectedErrorPrevention}`
optimizations.push(`Error prevention: Added "${selectedErrorPrevention}"`)
return enhanced
}
return prompt
}
private generateJasonFormat(optimizedPrompt: string, style: string): string {
const jasonStructure = {
prompt: optimizedPrompt,
version: '2.0', // NanoPrompt enhanced version
type: 'optimized_image_generation',
optimization: {
style: style,
quality: 'maximum',
accuracy: 'enhanced',
error_reduction: 'active'
},
metadata: {
created_by: 'NanoPrompt',
optimization_level: 'deep_reverse_engineered',
timestamp: new Date().toISOString()
}
}
return JSON.stringify(jasonStructure, null, 2)
}
private calculateAccuracyScore(optimizations: string[]): number {
// Base score starts at 60%
let score = 60
// Add points for each optimization category
const categories = {
'Pattern mapping': 5,
'Style enhancement': 8,
'Quality enhancement': 10,
'Composition optimization': 7,
'Lighting enhancement': 6,
'Color optimization': 5,
'Detail enhancement': 8,
'Error prevention': 6
}
for (const optimization of optimizations) {
for (const [category, points] of Object.entries(categories)) {
if (optimization.includes(category)) {
score += points
break
}
}
}
// Cap at 95%
return Math.min(95, score)
}
private generatePerformanceTips(optimizations: string[], style: string): string[] {
const tips: string[] = []
// Style-specific tips
if (style === 'realistic') {
tips.push('Use specific camera settings for photorealistic results')
tips.push('Include lighting direction information')
} else if (style === 'anime') {
tips.push('Specify art style (e.g., Studio Ghibli, Makoto Shinkai)')
tips.push('Include character design elements')
} else if (style === 'fantasy') {
tips.push('Add magical element descriptions')
tips.push('Specify atmosphere and mood details')
}
// General tips based on optimizations
if (optimizations.some(opt => opt.includes('Quality'))) {
tips.push('High quality descriptors increase rendering time but improve results')
}
if (optimizations.some(opt => opt.includes('Error prevention'))) {
tips.push('Error prevention keywords reduce common AI generation issues')
}
if (optimizations.some(opt => opt.includes('Composition'))) {
tips.push('Composition keywords help with framing and balance')
}
return tips
}
// Quick optimization templates
generateQuickOptimization(type: 'portrait' | 'landscape' | 'character' | 'object'): string {
const templates = {
portrait: 'Professional portrait photography, ultra-detailed, perfect composition, dramatic lighting, high resolution, no artifacts',
landscape: 'Breathtaking landscape photography, wide-angle view, vibrant colors, golden hour lighting, cinematic quality, hyper-detailed',
character: 'Character design, detailed features, expressive pose, proper anatomy, clean lines, professional quality, no distortion',
object: 'Product photography, studio lighting, sharp focus, detailed textures, accurate colors, professional composition'
}
return templates[type]
}
// Batch optimization for multiple prompts
async optimizeBatch(prompts: string[]): Promise<NanoPromptResult[]> {
const results: NanoPromptResult[] = []
for (const prompt of prompts) {
try {
const result = await this.optimizePrompt(prompt)
results.push(result)
} catch (error) {
console.error(`Failed to optimize prompt: ${prompt}`, error)
}
}
return results
}
}
// Create singleton instance
export const nanoPrompt = new NanoPrompt()

37
src/utils/api-utils.ts Normal file
View File

@@ -0,0 +1,37 @@
// API utilities for safe header handling
/**
* Sanitize API key to remove problematic characters
* HTTP headers must only contain ASCII printable characters for maximum compatibility
*/
export function sanitizeApiKey(key?: string): string | null {
if (!key) return null
try {
// Remove all non-ASCII printable characters (only allow space, !, #, $, %, &, ', *, +, -, ., /, 0-9, :, =, ?, A-Z, a-z)
const sanitized = key.replace(/[^\x20-\x7E]/g, '').trim()
// Basic API key format validation
if (sanitized.length < 10 || sanitized.length > 200) {
console.warn('Invalid API key length after sanitization:', sanitized.length)
return null
}
console.log('🔧 Sanitized API key:', sanitized)
return sanitized
} catch (error) {
console.error('Failed to sanitize API key:', error)
return null
}
}
/**
* Create safe Authorization header
*/
export function createAuthHeader(token: string): string {
const sanitized = sanitizeApiKey(token)
if (!sanitized) {
throw new Error('Invalid token: contains unsupported characters')
}
return `Bearer ${sanitized}`
}

81
tailwind.config.ts Normal file
View File

@@ -0,0 +1,81 @@
import type { Config } from "tailwindcss";
const { fontFamily } = require("tailwindcss/defaultTheme")
const config: Config = {
darkMode: ["class"],
content: [
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
container: {
center: true,
padding: "2rem",
screens: {
"2xl": "1400px",
},
},
extend: {
colors: {
border: "hsl(var(--border))",
input: "hsl(var(--input))",
ring: "hsl(var(--ring))",
background: "hsl(var(--background))",
foreground: "hsl(var(--foreground))",
primary: {
DEFAULT: "hsl(var(--primary))",
foreground: "hsl(var(--primary-foreground))",
},
secondary: {
DEFAULT: "hsl(var(--secondary))",
foreground: "hsl(var(--secondary-foreground))",
},
destructive: {
DEFAULT: "hsl(var(--destructive))",
foreground: "hsl(var(--destructive-foreground))",
},
muted: {
DEFAULT: "hsl(var(--muted))",
foreground: "hsl(var(--muted-foreground))",
},
accent: {
DEFAULT: "hsl(var(--accent))",
foreground: "hsl(var(--accent-foreground))",
},
popover: {
DEFAULT: "hsl(var(--popover))",
foreground: "hsl(var(--popover-foreground))",
},
card: {
DEFAULT: "hsl(var(--card))",
foreground: "hsl(var(--card-foreground))",
},
},
borderRadius: {
lg: "var(--radius)",
md: "calc(var(--radius) - 2px)",
sm: "calc(var(--radius) - 4px)",
},
fontFamily: {
sans: ["var(--font-sans)", ...fontFamily.sans],
},
keyframes: {
"accordion-down": {
from: { height: "0" },
to: { height: "var(--radix-accordion-content-height)" },
},
"accordion-up": {
from: { height: "var(--radix-accordion-content-height)" },
to: { height: "0" },
},
},
animation: {
"accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out",
},
},
},
plugins: [require("tailwindcss-animate")],
};
export default config;

44
tsconfig.json Normal file
View File

@@ -0,0 +1,44 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": [
"./src/*"
]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts",
"out/types/**/*.ts",
"out/dev/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}