Simplified NanoJason with offline-only features and added NanoCoder for technical prompts
- Removed online AI services (Ollama and Qwen) - Simplified Jason translator to offline-only functionality - Added NanoPrompt Optimizer for maximum AI accuracy - Added NanoCoder Technical Optimizer for coding/engineering prompts - Created tabbed interface with 3 modes: Jason Translator, NanoPrompt, NanoCoder - Added comprehensive pattern recognition and optimization features - Enhanced error prevention and performance optimization - Removed series generator and gallery components - Updated navigation to remove auth and settings links - Added quick templates for all three modes - Implemented copy/download functionality for all results
This commit is contained in:
41
Test Ideas/NanoJason/nanojason/.gitignore
vendored
Normal file
41
Test Ideas/NanoJason/nanojason/.gitignore
vendored
Normal 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
|
||||
342
Test Ideas/NanoJason/nanojason/README.md
Normal file
342
Test Ideas/NanoJason/nanojason/README.md
Normal file
@@ -0,0 +1,342 @@
|
||||
# 🎨 NanoJason - AI-Powered Image Series Creation Platform
|
||||
|
||||
Transform your ideas into stunning visual stories with AI-powered image generation and Jason language compatibility.
|
||||
|
||||
## ✨ Features
|
||||
|
||||
### 🚀 Core Capabilities
|
||||
- **AI-Powered Series Generation**: Create up to 30 images per series with consistent characters and narrative
|
||||
- **Jason Language Support**: Universal compatibility with NanoBanana, OpenAI, Midjourney, and more
|
||||
- **Qwen OAuth Integration**: Free tier with 2,000 requests/day (60 requests/minute limit)
|
||||
- **Character & Item Consistency**: Automatic tracking of visual elements across series
|
||||
- **Modern UI**: Beautiful, responsive interface inspired by Lovabale AI
|
||||
|
||||
### 🛠️ Technical Stack
|
||||
- **Frontend**: Next.js 16.1.0 with TypeScript
|
||||
- **Styling**: Tailwind CSS v4 with custom design system
|
||||
- **Authentication**: Qwen OAuth API integration
|
||||
- **State Management**: React hooks with localStorage
|
||||
- **Build Tool**: Turbopack for fast development
|
||||
|
||||
### 🎯 Key Components
|
||||
|
||||
#### Authentication System
|
||||
- **OAuth Flow**: Complete Qwen integration with token management
|
||||
- **Demo Mode**: Quick demo login for testing
|
||||
- **Session Management**: Secure token storage and refresh
|
||||
- **Access Control**: Protected routes and API endpoints
|
||||
|
||||
#### Series Generation
|
||||
- **AI Ideas**: Intelligent series concept generation
|
||||
- **Narrative Progression**: Automatic story structure creation
|
||||
- **Character Tracking**: Consistent character features across images
|
||||
- **Multi-Image Support**: 1-30 images per series
|
||||
|
||||
#### Jason Language
|
||||
- **Natural Language**: Convert descriptions to Jason format
|
||||
- **Multi-Service**: Optimization for different AI platforms
|
||||
- **Validation**: Error checking and warnings
|
||||
- **Export**: JSON format for universal compatibility
|
||||
|
||||
## 🚀 Getting Started
|
||||
|
||||
### Prerequisites
|
||||
- Node.js 18+ and npm/pnpm
|
||||
- Qwen API credentials (for production)
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# Clone the repository
|
||||
git clone <repository-url>
|
||||
cd nanojason
|
||||
|
||||
# Install dependencies
|
||||
npm install
|
||||
# or
|
||||
pnpm install
|
||||
```
|
||||
|
||||
### Environment Setup
|
||||
|
||||
Create a `.env.local` file with:
|
||||
|
||||
```env
|
||||
# Qwen API Configuration
|
||||
NEXT_PUBLIC_QWEN_CLIENT_ID=your_qwen_client_id
|
||||
NEXT_PUBLIC_QWEN_REDIRECT_URI=http://localhost:3000/auth
|
||||
QWEN_CLIENT_SECRET=your_qwen_client_secret
|
||||
|
||||
# Next.js Configuration
|
||||
NEXTAUTH_URL=http://localhost:3000
|
||||
NEXTAUTH_SECRET=your_nextauth_secret
|
||||
```
|
||||
|
||||
### Development
|
||||
|
||||
```bash
|
||||
# Start development server
|
||||
npm run dev
|
||||
# or
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
The application will be available at `http://localhost:3000`
|
||||
|
||||
## 🔐 Authentication Flow
|
||||
|
||||
### Qwen OAuth Integration
|
||||
|
||||
The application supports two authentication methods:
|
||||
|
||||
#### 1. Quick Demo Login (For Testing)
|
||||
- Click "Connect Qwen" in the header
|
||||
- Select "Quick Demo Login" on auth page
|
||||
- Instant access with mock credentials
|
||||
|
||||
#### 2. Full OAuth Flow (Production)
|
||||
- Click "Simulate Qwen OAuth" on auth page
|
||||
- Redirects to Qwen authorization URL
|
||||
- User grants permissions
|
||||
- Returns with authorization code
|
||||
- Exchanges code for access token
|
||||
- Stores token securely
|
||||
|
||||
### Token Management
|
||||
```javascript
|
||||
// Tokens are stored automatically
|
||||
localStorage.getItem('qwen_access_token') // Access token
|
||||
localStorage.getItem('qwen_authenticated') // Auth status
|
||||
```
|
||||
|
||||
### Rate Limits
|
||||
- **Free Tier**: 2,000 requests per day
|
||||
- **OAuth Rate**: 60 requests per minute
|
||||
- **Token Expiry**: 1 hour (auto-refresh available)
|
||||
|
||||
## 📚 Usage Guide
|
||||
|
||||
### Creating Image Series
|
||||
|
||||
#### 1. Describe Your Vision
|
||||
```text
|
||||
"A beautiful magical forest with glowing trees and floating islands where a young wizard discovers an ancient crystal"
|
||||
```
|
||||
|
||||
#### 2. Configure Series Settings
|
||||
- **Title**: "The Crystal Discovery"
|
||||
- **Description**: "Epic fantasy adventure"
|
||||
- **Image Count**: 1-30 images
|
||||
- **Style**: realistic, anime, cartoon, fantasy, cyberpunk
|
||||
|
||||
#### 3. Character & Item Consistency
|
||||
- **Characters**: Define visual features (hair, eyes, clothing)
|
||||
- **Items**: Track important objects
|
||||
- **Priority**: High/Medium/Low importance levels
|
||||
|
||||
#### 4. Generate with AI
|
||||
- **Narrative Progression**: Automatic story structure
|
||||
- **Consistency Rules**: Maintain character appearance
|
||||
- **Jason Output**: Universal prompt format
|
||||
|
||||
### Jason Language Examples
|
||||
|
||||
#### Basic Structure
|
||||
```json
|
||||
{
|
||||
"prompt": "enchanted forest with bioluminescent trees",
|
||||
"style": "fantasy",
|
||||
"characters": ["young_wizard", "ancient_spirit"],
|
||||
"mood": "mysterious",
|
||||
"consistency": {
|
||||
"characterFeatures": {
|
||||
"hair": "silver",
|
||||
"eyes": "blue"
|
||||
},
|
||||
"colorPalette": ["purple", "blue", "green"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Service-Specific Optimization
|
||||
```json
|
||||
// NanoBanana
|
||||
{
|
||||
"prompt": "magical forest scene",
|
||||
"consistency": {
|
||||
"characterFeatures": {
|
||||
"style": "consistent",
|
||||
"quality": "high"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// OpenAI DALL-E
|
||||
{
|
||||
"prompt": "magical forest scene, consistent character design",
|
||||
"characters": ["young_wizard"]
|
||||
}
|
||||
```
|
||||
|
||||
## 🏗️ Architecture
|
||||
|
||||
### Project Structure
|
||||
```
|
||||
nanojason/
|
||||
├── src/
|
||||
│ ├── app/ # Next.js app router
|
||||
│ │ ├── api/ # API routes
|
||||
│ │ │ ├── auth/ # Authentication endpoints
|
||||
│ │ │ └── generate/ # Generation endpoints
|
||||
│ │ ├── auth/ # Authentication pages
|
||||
│ │ └── globals.css # Global styles
|
||||
│ ├── components/ # UI components
|
||||
│ │ ├── ui/ # Reusable elements
|
||||
│ │ └── layout/ # Layout components
|
||||
│ ├── lib/ # Utilities
|
||||
│ │ └── utils.ts # Helper functions
|
||||
│ ├── services/ # Business logic
|
||||
│ │ ├── series-generator.ts # Series creation
|
||||
│ │ ├── jason-processor.ts # Jason language
|
||||
│ │ └── qwen-api.ts # Qwen integration
|
||||
│ └── hooks/ # React hooks
|
||||
│ └── use-qwen-auth.ts # Authentication state
|
||||
├── tailwind.config.ts # Tailwind configuration
|
||||
└── package.json # Dependencies
|
||||
```
|
||||
|
||||
### API Endpoints
|
||||
|
||||
#### Authentication
|
||||
- `POST /api/auth/qwen/callback` - OAuth token exchange
|
||||
- `GET /api/auth/verify` - Token validation
|
||||
|
||||
#### Generation
|
||||
- `POST /api/generate/narrative` - Story progression
|
||||
- `POST /api/generate/series` - Series creation
|
||||
- `GET /api/generate/series` - Series management
|
||||
|
||||
## 🎨 Design System
|
||||
|
||||
### Color Palette
|
||||
- **Primary**: Blue gradient (#0ea5e9 to #0284c7)
|
||||
- **Accent**: Purple gradient (#d946ef to #a21caf)
|
||||
- **Background**: Clean white/dark themes
|
||||
- **Text**: High contrast readability
|
||||
|
||||
### Typography
|
||||
- **Font**: Inter system font stack
|
||||
- **Headings**: Bold weights with gradient effects
|
||||
- **Body**: Regular weights for readability
|
||||
|
||||
### Components
|
||||
- **Cards**: Rounded corners with hover effects
|
||||
- **Buttons**: Consistent variants (primary, secondary, outline)
|
||||
- **Forms**: Clean inputs with proper labels
|
||||
- **Navigation**: Sticky header with backdrop blur
|
||||
|
||||
## 🔧 Development
|
||||
|
||||
### Build Commands
|
||||
```bash
|
||||
# Development
|
||||
npm run dev # Start dev server
|
||||
npm run build # Production build
|
||||
npm run start # Start production server
|
||||
npm run lint # Run ESLint
|
||||
npm run type-check # TypeScript check
|
||||
```
|
||||
|
||||
### Environment Variables
|
||||
```env
|
||||
NODE_ENV=development
|
||||
NEXT_PUBLIC_APP_URL=http://localhost:3000
|
||||
NEXT_PUBLIC_QWEN_CLIENT_ID=demo_client_id
|
||||
```
|
||||
|
||||
## 📱 Responsive Design
|
||||
|
||||
### Breakpoints
|
||||
- **Mobile**: < 768px (sm, md)
|
||||
- **Tablet**: 768px - 1024px (md, lg)
|
||||
- **Desktop**: > 1024px (lg, xl, 2xl)
|
||||
|
||||
### Mobile Adaptations
|
||||
- **Navigation**: Collapsible menu
|
||||
- **Cards**: Single column layout
|
||||
- **Forms**: Full-width inputs
|
||||
- **Buttons**: Touch-friendly sizing
|
||||
|
||||
## 🔒 Security
|
||||
|
||||
### Authentication Security
|
||||
- **Token Storage**: httpOnly cookies + localStorage fallback
|
||||
- **OAuth Flow**: PKCE implementation (production)
|
||||
- **CSRF Protection**: State parameter validation
|
||||
- **Token Refresh**: Automatic expiry handling
|
||||
|
||||
### API Security
|
||||
- **Input Validation**: Zod schema validation
|
||||
- **Error Handling**: Sanitized error messages
|
||||
- **Rate Limiting**: Built-in request throttling
|
||||
- **CORS**: Proper cross-origin configuration
|
||||
|
||||
## 🚀 Deployment
|
||||
|
||||
### Environment Setup
|
||||
```bash
|
||||
# Production environment variables
|
||||
NEXT_PUBLIC_QWEN_CLIENT_ID=production_client_id
|
||||
QWEN_CLIENT_SECRET=production_client_secret
|
||||
NEXTAUTH_URL=https://your-domain.com
|
||||
NODE_ENV=production
|
||||
```
|
||||
|
||||
### Build and Deploy
|
||||
```bash
|
||||
# Build for production
|
||||
npm run build
|
||||
|
||||
# Output in .next folder
|
||||
# Ready for Vercel, Netlify, etc.
|
||||
```
|
||||
|
||||
### Platform-Specific
|
||||
- **Vercel**: Automatic deployment from Git
|
||||
- **Netlify**: Build and deploy .next folder
|
||||
- **Docker**: Multi-stage build available
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
### Development Workflow
|
||||
1. Fork the repository
|
||||
2. Create feature branch (`git checkout -b feature/amazing-feature`)
|
||||
3. Commit changes (`git commit -m 'Add amazing feature'`)
|
||||
4. Push to branch (`git push origin feature/amazing-feature`)
|
||||
5. Open Pull Request
|
||||
|
||||
### Code Style
|
||||
- **TypeScript**: Strict mode enabled
|
||||
- **ESLint**: AirBnB configuration
|
||||
- **Prettier**: Automatic formatting
|
||||
- **Components**: Functional components with hooks
|
||||
|
||||
## 📄 License
|
||||
|
||||
MIT License - see LICENSE file for details.
|
||||
|
||||
## 🆘 Support
|
||||
|
||||
### Documentation
|
||||
- **API Reference**: `/docs/api`
|
||||
- **Component Library**: `/docs/components`
|
||||
- **Authentication Guide**: `/docs/auth`
|
||||
|
||||
### Community
|
||||
- **GitHub Issues**: Bug reports and feature requests
|
||||
- **Discord**: Real-time chat and support
|
||||
- **Blog**: Tutorials and announcements
|
||||
|
||||
---
|
||||
|
||||
**Made with ❤️ by the NanoJason Team**
|
||||
18
Test Ideas/NanoJason/nanojason/eslint.config.mjs
Normal file
18
Test Ideas/NanoJason/nanojason/eslint.config.mjs
Normal 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;
|
||||
8
Test Ideas/NanoJason/nanojason/next.config.ts
Normal file
8
Test Ideas/NanoJason/nanojason/next.config.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
/* config options here */
|
||||
reactCompiler: true,
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
6627
Test Ideas/NanoJason/nanojason/package-lock.json
generated
Normal file
6627
Test Ideas/NanoJason/nanojason/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
32
Test Ideas/NanoJason/nanojason/package.json
Normal file
32
Test Ideas/NanoJason/nanojason/package.json
Normal file
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"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.2.4",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^0.562.0",
|
||||
"next": "16.1.0",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3",
|
||||
"tailwind-merge": "^3.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"babel-plugin-react-compiler": "1.0.0",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "16.1.0",
|
||||
"tailwindcss": "^4",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
7
Test Ideas/NanoJason/nanojason/postcss.config.mjs
Normal file
7
Test Ideas/NanoJason/nanojason/postcss.config.mjs
Normal file
@@ -0,0 +1,7 @@
|
||||
const config = {
|
||||
plugins: {
|
||||
"@tailwindcss/postcss": {},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
1
Test Ideas/NanoJason/nanojason/public/file.svg
Normal file
1
Test Ideas/NanoJason/nanojason/public/file.svg
Normal 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
Test Ideas/NanoJason/nanojason/public/globe.svg
Normal file
1
Test Ideas/NanoJason/nanojason/public/globe.svg
Normal 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
Test Ideas/NanoJason/nanojason/public/next.svg
Normal file
1
Test Ideas/NanoJason/nanojason/public/next.svg
Normal 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
Test Ideas/NanoJason/nanojason/public/vercel.svg
Normal file
1
Test Ideas/NanoJason/nanojason/public/vercel.svg
Normal 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
Test Ideas/NanoJason/nanojason/public/window.svg
Normal file
1
Test Ideas/NanoJason/nanojason/public/window.svg
Normal 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 |
@@ -0,0 +1,66 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const { code, state } = await request.json()
|
||||
|
||||
if (!code) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Authorization code is required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Validate state for CSRF protection
|
||||
const storedState = request.cookies.get('qwen_auth_state')?.value
|
||||
if (state && storedState !== state) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid state parameter' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// In production, exchange code for actual Qwen token
|
||||
// For demo, create a mock token
|
||||
const mockAccessToken = `qwen_token_${code}_${Date.now()}`
|
||||
const mockRefreshToken = `qwen_refresh_${code}_${Date.now()}`
|
||||
const mockExpiresIn = 3600 // 1 hour
|
||||
|
||||
// Store in cookie for server-side access
|
||||
const response = NextResponse.json({
|
||||
access_token: mockAccessToken,
|
||||
refresh_token: mockRefreshToken,
|
||||
expires_in: mockExpiresIn,
|
||||
token_type: 'Bearer',
|
||||
success: true,
|
||||
redirect_to: '/',
|
||||
})
|
||||
|
||||
// Set secure HTTP-only cookie
|
||||
response.cookies.set('qwen_access_token', mockAccessToken, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
maxAge: mockExpiresIn,
|
||||
path: '/',
|
||||
})
|
||||
|
||||
// Clear state cookie
|
||||
response.cookies.set('qwen_auth_state', '', {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
maxAge: 0,
|
||||
path: '/',
|
||||
})
|
||||
|
||||
return response
|
||||
|
||||
} catch (error) {
|
||||
console.error('Qwen auth callback error:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { sanitizeApiKey } from '@/utils/api-utils'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const authHeader = request.headers.get('authorization')
|
||||
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Authorization header is required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const token = authHeader.substring(7)
|
||||
|
||||
// In a real implementation, you would verify the token with Qwen's API
|
||||
// For now, we'll just check if it exists and is not expired
|
||||
if (!token || token.startsWith('mock_')) {
|
||||
// For demo purposes, accept mock tokens
|
||||
// In production, you would validate this with Qwen's token endpoint
|
||||
return NextResponse.json({
|
||||
valid: true,
|
||||
message: 'Token is valid (demo mode)'
|
||||
})
|
||||
}
|
||||
|
||||
// In production, you would call Qwen's token validation endpoint:
|
||||
/*
|
||||
const validationResponse = await fetch('https://open.bigmodel.cn/api/paas/v4/oauth2/validate', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${sanitizeApiKey(token) || token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
})
|
||||
|
||||
if (!validationResponse.ok) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Token is invalid or expired' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
*/
|
||||
|
||||
return NextResponse.json({
|
||||
valid: true,
|
||||
message: 'Token is valid'
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error('Token verification error:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
|
||||
export interface NarrativeRequest {
|
||||
basePrompt: string
|
||||
title: string
|
||||
description: string
|
||||
imageCount: number
|
||||
style: string
|
||||
characters?: string
|
||||
items?: string
|
||||
}
|
||||
|
||||
export interface NarrativeResponse {
|
||||
prompts: string[]
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body: NarrativeRequest = await request.json()
|
||||
|
||||
const {
|
||||
basePrompt,
|
||||
title,
|
||||
description,
|
||||
imageCount,
|
||||
style,
|
||||
characters = '',
|
||||
items = '',
|
||||
} = body
|
||||
|
||||
if (!basePrompt || !title || !description || imageCount <= 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Missing required fields' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Generate narrative progression
|
||||
const prompts = generateNarrativeProgression({
|
||||
basePrompt,
|
||||
title,
|
||||
description,
|
||||
imageCount,
|
||||
style,
|
||||
characters,
|
||||
items,
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
prompts,
|
||||
success: true,
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error('Narrative generation error:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function generateNarrativeProgression(config: NarrativeRequest): string[] {
|
||||
const {
|
||||
basePrompt,
|
||||
title,
|
||||
description,
|
||||
imageCount,
|
||||
style,
|
||||
characters,
|
||||
items,
|
||||
} = config
|
||||
|
||||
const prompts: string[] = []
|
||||
|
||||
// Define narrative structure based on image count
|
||||
const narrativeStructure = getNarrativeStructure(imageCount)
|
||||
|
||||
// Generate prompts for each narrative stage
|
||||
for (let i = 0; i < imageCount; i++) {
|
||||
const stage = narrativeStructure[i] || narrativeStructure[narrativeStructure.length - 1]
|
||||
|
||||
const prompt = generateStagePrompt({
|
||||
stage,
|
||||
basePrompt,
|
||||
title,
|
||||
description,
|
||||
style,
|
||||
characters,
|
||||
items,
|
||||
index: i,
|
||||
total: imageCount,
|
||||
})
|
||||
|
||||
prompts.push(prompt)
|
||||
}
|
||||
|
||||
return prompts
|
||||
}
|
||||
|
||||
function getNarrativeStructure(imageCount: number): string[] {
|
||||
if (imageCount <= 3) {
|
||||
return ['introduction', 'development', 'climax']
|
||||
} else if (imageCount <= 5) {
|
||||
return [
|
||||
'introduction',
|
||||
'rising_action',
|
||||
'midpoint',
|
||||
'climax',
|
||||
'resolution'
|
||||
]
|
||||
} else if (imageCount <= 8) {
|
||||
return [
|
||||
'introduction',
|
||||
'setup',
|
||||
'rising_action_1',
|
||||
'rising_action_2',
|
||||
'midpoint',
|
||||
'climax',
|
||||
'falling_action',
|
||||
'resolution'
|
||||
]
|
||||
} else {
|
||||
// For longer series, use a more detailed structure
|
||||
const structure = [
|
||||
'introduction',
|
||||
'world_building',
|
||||
'character_introduction',
|
||||
'initial_challenge',
|
||||
'rising_action_1',
|
||||
'rising_action_2',
|
||||
'midpoint_twist',
|
||||
'climax_buildup',
|
||||
'climax',
|
||||
'resolution',
|
||||
'epilogue'
|
||||
]
|
||||
|
||||
// Repeat middle elements for longer series
|
||||
while (structure.length < imageCount) {
|
||||
structure.splice(-2, 0, `development_${structure.length}`)
|
||||
}
|
||||
|
||||
return structure.slice(0, imageCount)
|
||||
}
|
||||
}
|
||||
|
||||
function generateStagePrompt(config: {
|
||||
stage: string
|
||||
basePrompt: string
|
||||
title: string
|
||||
description: string
|
||||
style: string
|
||||
characters: string
|
||||
items: string
|
||||
index: number
|
||||
total: number
|
||||
}): string {
|
||||
const {
|
||||
stage,
|
||||
basePrompt,
|
||||
title,
|
||||
description,
|
||||
style,
|
||||
characters,
|
||||
items,
|
||||
index,
|
||||
total,
|
||||
} = config
|
||||
|
||||
// Stage-specific templates
|
||||
const stageTemplates: Record<string, string[]> = {
|
||||
introduction: [
|
||||
`Wide establishing shot of ${title} with ${description}. ${characters ? `Featuring ${characters}.` : ''} ${items ? `With ${items} visible.` : ''} ${style} style, atmospheric lighting.`,
|
||||
`Close-up introduction to the main elements of ${title}, showcasing ${description}. ${characters ? `Focus on ${characters}.` : ''} ${style} aesthetic.`,
|
||||
`Panoramic view of the ${title} scene, ${description}. Epic scale with ${characters} ${items ? `and ${items}` : ''} in ${style} style.`
|
||||
],
|
||||
rising_action: [
|
||||
`${title}: Building tension as ${description}. ${characters} ${items ? `interacting with ${items}` : ''}. Dramatic composition in ${style} style.`,
|
||||
`Progressive development of ${title}, ${description}. ${characters} showing character development. ${items} becoming more prominent. ${style} visual style.`,
|
||||
`Action sequence in ${title}, ${description}. ${characters} in motion with ${items}. Dynamic angles and ${style} rendering.`
|
||||
],
|
||||
climax: [
|
||||
`Dramatic climax of ${title}: ${description}. ${characters} at peak action with ${items}. High contrast lighting, ${style} style.`,
|
||||
`Intense climax scene showing ${title}: ${description}. ${characters} in decisive moment with ${items}. Cinematic ${style} composition.`,
|
||||
`Peak action in ${title}: ${description}. ${characters} and ${items} in dramatic confrontation. Epic scale with ${style} aesthetic.`
|
||||
],
|
||||
resolution: [
|
||||
`Resolution of ${title}: ${description}. ${characters} ${items ? `with ${items}` : ''} in peaceful setting. Warm lighting, ${style} style.`,
|
||||
`Conclusion of ${title}: ${description}. ${characters} ${items ? `and ${items}` : ''} in final arrangement. Serene composition, ${style} aesthetic.`,
|
||||
`Final scene of ${title}: ${description}. ${characters} ${items ? `and ${items}` : ''} in satisfying conclusion. ${style} style with atmospheric mood.`
|
||||
],
|
||||
midpoint: [
|
||||
`Midpoint twist in ${title}: ${description}. ${characters} facing unexpected challenge with ${items}. ${style} style with dramatic lighting.`,
|
||||
`Turning point in ${title}: ${description}. ${characters} experiencing major development with ${items}. ${style} visual approach.`
|
||||
],
|
||||
development: [
|
||||
`Development scene in ${title}: ${description}. ${characters} evolving story with ${items}. ${style} style with detailed composition.`,
|
||||
`Progressive scene of ${title}: ${description}. ${characters} advancing narrative with ${items}. ${style} aesthetic with atmospheric elements.`
|
||||
],
|
||||
world_building: [
|
||||
`World-building scene for ${title}: ${description}. Detailed environment showing ${characters} ${items ? `with ${items}` : ''} in ${style} style.`,
|
||||
`Environmental storytelling in ${title}: ${description}. Rich world details featuring ${characters} ${items ? `and ${items}` : ''}. ${style} aesthetic.`
|
||||
],
|
||||
character_introduction: [
|
||||
`Character introduction in ${title}: ${description}. Focus on ${characters} ${items ? `with ${items}` : ''} in ${style} style.`,
|
||||
`Detailed character presentation in ${title}: ${description}. ${characters} ${items ? `interacting with ${items}` : ''}. ${style} visual treatment.`
|
||||
],
|
||||
initial_challenge: [
|
||||
`Initial challenge in ${title}: ${description}. ${characters} facing ${items} in ${style} style.`,
|
||||
`First obstacle scene: ${title} with ${description}. ${characters} encountering ${items}. ${style} composition.`
|
||||
],
|
||||
falling_action: [
|
||||
`Falling action in ${title}: ${description}. ${characters} ${items ? `with ${items}` : ''} in aftermath. ${style} style with reflective mood.`,
|
||||
`Resolution aftermath: ${title} - ${description}. ${characters} ${items ? `and ${items}` : ''} in peaceful setting. ${style} aesthetic.`
|
||||
],
|
||||
epilogue: [
|
||||
`Epilogue scene for ${title}: ${description}. ${characters} ${items ? `with ${items}` : ''} in final moments. ${style} style with nostalgic atmosphere.`,
|
||||
`Closing scene of ${title}: ${description}. ${characters} ${items ? `and ${items}` : ''} in satisfying conclusion. ${style} visual style.`
|
||||
]
|
||||
}
|
||||
|
||||
// Default template for unknown stages
|
||||
const defaultTemplates = [
|
||||
`${title}: ${description}. ${characters} ${items ? `with ${items}` : ''} in ${style} style.`,
|
||||
`Scene from ${title}: ${description}. Featuring ${characters} ${items ? `and ${items}` : ''}. ${style} aesthetic.`,
|
||||
`${title} scene: ${description}. ${characters} ${items ? `interacting with ${items}` : ''}. ${style} visual approach.`
|
||||
]
|
||||
|
||||
// Get templates for the current stage
|
||||
const templates = stageTemplates[stage] || defaultTemplates
|
||||
|
||||
// Select template based on index for variety
|
||||
const templateIndex = index % templates.length
|
||||
let prompt = templates[templateIndex]
|
||||
|
||||
// Add progress-specific details
|
||||
const progress = (index + 1) / total
|
||||
if (progress < 0.3) {
|
||||
prompt += ' Beginning of the journey, hopeful atmosphere.'
|
||||
} else if (progress < 0.7) {
|
||||
prompt += ' Mid-journey, building intensity and drama.'
|
||||
} else {
|
||||
prompt += ' Conclusion, satisfying resolution and closure.'
|
||||
}
|
||||
|
||||
return prompt
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { seriesGenerator } from '@/services/series-generator'
|
||||
|
||||
export interface GenerateSeriesRequest {
|
||||
basePrompt: string
|
||||
config: {
|
||||
title: string
|
||||
description: string
|
||||
imageCount: number
|
||||
style: string
|
||||
}
|
||||
characters?: Array<{
|
||||
name: string
|
||||
description: string
|
||||
features: any
|
||||
}>
|
||||
items?: Array<{
|
||||
name: string
|
||||
description: string
|
||||
features: any
|
||||
}>
|
||||
}
|
||||
|
||||
export interface GenerateSeriesResponse {
|
||||
seriesId: string
|
||||
config: any
|
||||
estimatedTime: number
|
||||
status: 'pending' | 'generating' | 'completed' | 'error'
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body: GenerateSeriesRequest = await request.json()
|
||||
|
||||
const { basePrompt, config, characters = [], items = [] } = body
|
||||
|
||||
if (!basePrompt || !config || !config.title || !config.description) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Missing required fields: basePrompt, config.title, config.description' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
if (config.imageCount < 1 || config.imageCount > 30) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Image count must be between 1 and 30' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Create the series
|
||||
const series = await seriesGenerator.createSeries(
|
||||
basePrompt,
|
||||
config,
|
||||
characters,
|
||||
items
|
||||
)
|
||||
|
||||
// Simulate image generation (in production, this would trigger actual generation)
|
||||
const estimatedTime = Math.max(30, config.imageCount * 10) // 10-30 seconds per image
|
||||
|
||||
return NextResponse.json({
|
||||
seriesId: series.id,
|
||||
config: series.config,
|
||||
estimatedTime,
|
||||
status: 'pending',
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error('Series generation error:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to generate series' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const seriesId = searchParams.get('seriesId')
|
||||
|
||||
if (!seriesId) {
|
||||
return NextResponse.json(
|
||||
{ error: 'seriesId parameter is required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const series = seriesGenerator.getSeries(seriesId)
|
||||
|
||||
if (!series) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Series not found' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
// Calculate generation status
|
||||
const imageCount = series.images.length
|
||||
const totalImages = series.config.imageCount
|
||||
const progressPercentage = Math.round((imageCount / totalImages) * 100)
|
||||
|
||||
let status: 'pending' | 'generating' | 'completed' | 'error' = 'pending'
|
||||
if (imageCount === 0) {
|
||||
status = 'pending'
|
||||
} else if (imageCount < totalImages) {
|
||||
status = 'generating'
|
||||
} else if (imageCount === totalImages) {
|
||||
status = 'completed'
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
seriesId: series.id,
|
||||
config: series.config,
|
||||
images: series.images,
|
||||
progress: {
|
||||
current: imageCount,
|
||||
total: totalImages,
|
||||
percentage: progressPercentage,
|
||||
},
|
||||
status,
|
||||
createdAt: series.createdAt,
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error('Get series error:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const seriesId = searchParams.get('seriesId')
|
||||
|
||||
if (!seriesId) {
|
||||
return NextResponse.json(
|
||||
{ error: 'seriesId parameter is required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const success = seriesGenerator.deleteSeries(seriesId)
|
||||
|
||||
if (!success) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Series not found' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Series deleted successfully',
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error('Delete series error:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
170
Test Ideas/NanoJason/nanojason/src/app/auth/page.tsx
Normal file
170
Test Ideas/NanoJason/nanojason/src/app/auth/page.tsx
Normal file
@@ -0,0 +1,170 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { useRouter, useSearchParams } from "next/navigation"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Sparkles, Loader2, ExternalLink } from "lucide-react"
|
||||
|
||||
export default function AuthPage() {
|
||||
const [isAuthenticating, setIsAuthenticating] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
|
||||
useEffect(() => {
|
||||
// Check if we have auth code in URL
|
||||
const code = searchParams.get('code')
|
||||
const error = searchParams.get('error')
|
||||
const success = searchParams.get('success')
|
||||
|
||||
if (error) {
|
||||
setError(`Authentication failed: ${error}`)
|
||||
return
|
||||
}
|
||||
|
||||
if (success === 'true') {
|
||||
// Successfully authenticated, redirect to home
|
||||
router.push('/')
|
||||
return
|
||||
}
|
||||
|
||||
if (code) {
|
||||
handleAuthCallback(code)
|
||||
}
|
||||
}, [searchParams, router])
|
||||
|
||||
const handleAuthCallback = async (authCode: string) => {
|
||||
setIsAuthenticating(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
// Exchange auth code for access token
|
||||
const response = await fetch('/api/auth/qwen/callback', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ code: authCode }),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Token exchange failed')
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
if (data.success) {
|
||||
// Store the token (in production, this would be more secure)
|
||||
localStorage.setItem('qwen_access_token', data.access_token)
|
||||
localStorage.setItem('qwen_authenticated', 'true')
|
||||
|
||||
// Redirect to home
|
||||
router.push(data.redirect_to || '/')
|
||||
} else {
|
||||
throw new Error(data.error || 'Authentication failed')
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Authentication failed')
|
||||
} finally {
|
||||
setIsAuthenticating(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleQwenOAuth = () => {
|
||||
// Redirect to Qwen OAuth for actual authentication
|
||||
const clientId = process.env.NEXT_PUBLIC_QWEN_CLIENT_ID || 'demo_client_id'
|
||||
const redirectUri = encodeURIComponent(process.env.NEXT_PUBLIC_QWEN_REDIRECT_URI || 'http://localhost:3000/auth')
|
||||
const scope = 'api_access'
|
||||
const state = Math.random().toString(36).substring(7)
|
||||
|
||||
// Store state for CSRF protection
|
||||
localStorage.setItem('qwen_auth_state', state)
|
||||
|
||||
// Qwen OAuth URL (following Qwen Code implementation)
|
||||
const authUrl = `https://qwen.ai/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scope}&response_type=code&state=${state}`
|
||||
|
||||
window.location.href = authUrl
|
||||
}
|
||||
|
||||
const handleDirectLogin = () => {
|
||||
// Direct login for demo - simulates successful OAuth
|
||||
const mockToken = `demo_token_${Date.now()}`
|
||||
localStorage.setItem('qwen_access_token', mockToken)
|
||||
localStorage.setItem('qwen_authenticated', 'true')
|
||||
router.push('/')
|
||||
}
|
||||
|
||||
if (isAuthenticating) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center">
|
||||
<Card className="w-96">
|
||||
<CardContent className="pt-6">
|
||||
<div className="text-center space-y-4">
|
||||
<Loader2 className="h-8 w-8 animate-spin mx-auto text-blue-600" />
|
||||
<p className="text-gray-600">Authenticating with Qwen...</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center">
|
||||
<Card className="w-96">
|
||||
<CardHeader className="text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
<Sparkles className="h-12 w-12 bg-gradient-to-r from-blue-600 to-purple-600" />
|
||||
</div>
|
||||
<CardTitle className="text-2xl">Welcome to NanoJason</CardTitle>
|
||||
<CardDescription>
|
||||
Connect with Qwen AI to start creating stunning image series
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{error && (
|
||||
<div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
onClick={handleDirectLogin}
|
||||
className="w-full bg-blue-600 text-white hover:bg-blue-700"
|
||||
size="lg"
|
||||
>
|
||||
<Sparkles className="mr-2 h-4 w-4" />
|
||||
Quick Demo Login
|
||||
</Button>
|
||||
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<span className="bg-white px-2 text-xs text-gray-500">OR</span>
|
||||
</div>
|
||||
<hr className="border-gray-300" />
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleQwenOAuth}
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
size="lg"
|
||||
>
|
||||
<ExternalLink className="mr-2 h-4 w-4" />
|
||||
Connect with Qwen OAuth
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="text-xs text-gray-600 text-center space-y-1">
|
||||
<p>By connecting, you agree to Qwen's terms of service</p>
|
||||
<p className="font-medium">🚀 Free tier: 2,000 requests/day</p>
|
||||
<p className="text-green-600">⚡ 60 requests/minute limit</p>
|
||||
<p className="text-blue-600">🔐 OAuth authentication with automatic token refresh</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
BIN
Test Ideas/NanoJason/nanojason/src/app/favicon.ico
Normal file
BIN
Test Ideas/NanoJason/nanojason/src/app/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
151
Test Ideas/NanoJason/nanojason/src/app/globals.css
Normal file
151
Test Ideas/NanoJason/nanojason/src/app/globals.css
Normal file
@@ -0,0 +1,151 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #171717;
|
||||
--card: #ffffff;
|
||||
--card-foreground: #171717;
|
||||
--primary: #0ea5e9;
|
||||
--primary-foreground: #ffffff;
|
||||
--secondary: #f1f5f9;
|
||||
--secondary-foreground: #0f172a;
|
||||
--accent: #d946ef;
|
||||
--accent-foreground: #ffffff;
|
||||
--muted: #f1f5f9;
|
||||
--muted-foreground: #64748b;
|
||||
--border: #e2e8f0;
|
||||
--input: #e2e8f0;
|
||||
--ring: #0ea5e9;
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #ededed;
|
||||
--card: #0a0a0a;
|
||||
--card-foreground: #ededed;
|
||||
--primary: #0284c7;
|
||||
--primary-foreground: #ffffff;
|
||||
--secondary: #1e293b;
|
||||
--secondary-foreground: #f1f5f9;
|
||||
--accent: #a21caf;
|
||||
--accent-foreground: #ffffff;
|
||||
--muted: #1e293b;
|
||||
--muted-foreground: #94a3b8;
|
||||
--border: #334155;
|
||||
--input: #334155;
|
||||
--ring: #0ea5e9;
|
||||
}
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--radius: var(--radius);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
border-color: hsl(var(--border));
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: hsl(var(--background));
|
||||
color: hsl(var(--foreground));
|
||||
font-family: "Inter", system-ui, sans-serif;
|
||||
}
|
||||
}
|
||||
|
||||
@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
Test Ideas/NanoJason/nanojason/src/app/layout.tsx
Normal file
31
Test Ideas/NanoJason/nanojason/src/app/layout.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import OllamaSettings from "@/components/layout/ollama-settings"
|
||||
|
||||
export default function OllamaSettingsPage() {
|
||||
return <OllamaSettings />
|
||||
}
|
||||
726
Test Ideas/NanoJason/nanojason/src/app/page.tsx
Normal file
726
Test Ideas/NanoJason/nanojason/src/app/page.tsx
Normal file
@@ -0,0 +1,726 @@
|
||||
'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>
|
||||
)}
|
||||
|
||||
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
90
Test Ideas/NanoJason/nanojason/src/app/test-error/page.tsx
Normal file
90
Test Ideas/NanoJason/nanojason/src/app/test-error/page.tsx
Normal file
@@ -0,0 +1,90 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { ollamaClient } from '@/services/ollama-client'
|
||||
|
||||
export default function TestErrorPage() {
|
||||
const [testResult, setTestResult] = useState<string>('Click test button to start')
|
||||
const [error, setError] = useState<string>('')
|
||||
|
||||
const testOllamaConnection = async () => {
|
||||
try {
|
||||
setTestResult('Testing API key...')
|
||||
setError('')
|
||||
|
||||
// Test with your actual API key
|
||||
const testKey = '81be8de35b254163a87ba41a5e4e565d.x-TOGbA79gS7AAHTwziOUAIb'
|
||||
|
||||
console.log('🔍 Testing API key:', testKey)
|
||||
console.log('🔍 API key length:', testKey.length)
|
||||
console.log('🔍 API key chars:', testKey.split('').map(c => c.charCodeAt(0)))
|
||||
|
||||
// Set the API key
|
||||
ollamaClient.setApiKey(testKey, false)
|
||||
|
||||
// Test if available
|
||||
const isAvailable = ollamaClient.isAvailable()
|
||||
console.log('🔍 Client available:', isAvailable)
|
||||
|
||||
setTestResult(`API Key Set: ${isAvailable ? '✅' : '❌'}`)
|
||||
|
||||
if (isAvailable) {
|
||||
setTestResult('Testing API call...')
|
||||
|
||||
// Try to list models
|
||||
const models = await ollamaClient.listModels()
|
||||
console.log('✅ Models retrieved:', models)
|
||||
setTestResult(`✅ Success! Found ${models.length} models`)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('❌ Test failed:', err)
|
||||
setError(`Error: ${err.message}`)
|
||||
setTestResult('❌ Test Failed')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 p-8">
|
||||
<div className="max-w-2xl mx-auto">
|
||||
<h1 className="text-3xl font-bold mb-6">API Error Debug Test</h1>
|
||||
|
||||
<div className="bg-white rounded-lg shadow p-6 mb-6">
|
||||
<h2 className="text-xl font-semibold mb-4">Test Ollama Connection</h2>
|
||||
|
||||
<button
|
||||
onClick={testOllamaConnection}
|
||||
className="bg-blue-500 text-white px-6 py-2 rounded hover:bg-blue-600"
|
||||
>
|
||||
Test API Connection
|
||||
</button>
|
||||
|
||||
<div className="mt-4">
|
||||
<div className="font-semibold">Test Result:</div>
|
||||
<div className="mt-2 p-3 bg-gray-100 rounded">
|
||||
{testResult}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mt-4">
|
||||
<div className="font-semibold text-red-600">Error:</div>
|
||||
<div className="mt-2 p-3 bg-red-100 rounded text-red-700">
|
||||
{error}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg shadow p-6">
|
||||
<h2 className="text-xl font-semibold mb-4">Browser Console</h2>
|
||||
<p className="text-sm text-gray-600">
|
||||
Check the browser console (F12) for detailed debugging information.
|
||||
</p>
|
||||
<p className="text-sm text-gray-600 mt-2">
|
||||
Look for 🔍 emoji markers in console logs.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,556 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { jasonProcessor, CharacterConsistency, ItemConsistency, SeriesConsistency } from "@/services/jason-processor"
|
||||
import { seriesGenerator } from "@/services/series-generator"
|
||||
import { Users, Package, Palette, Settings, Eye, Edit, Trash2, Plus, CheckCircle, AlertCircle } from "lucide-react"
|
||||
|
||||
interface ConsistencyTrackerProps {
|
||||
seriesId?: string
|
||||
onConsistencyUpdate?: (consistency: SeriesConsistency) => void
|
||||
}
|
||||
|
||||
export function ConsistencyTracker({ seriesId, onConsistencyUpdate }: ConsistencyTrackerProps) {
|
||||
const [consistencyProfile, setConsistencyProfile] = useState<SeriesConsistency | null>(null)
|
||||
const [characters, setCharacters] = useState<CharacterConsistency[]>([])
|
||||
const [items, setItems] = useState<ItemConsistency[]>([])
|
||||
const [activeTab, setActiveTab] = useState<'characters' | 'items' | 'colors'>('characters')
|
||||
const [isEditing, setIsEditing] = useState(false)
|
||||
const [editForm, setEditForm] = useState<{
|
||||
type: 'character' | 'item'
|
||||
data: Partial<CharacterConsistency> | Partial<ItemConsistency>
|
||||
index: number
|
||||
} | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (seriesId) {
|
||||
loadConsistencyProfile(seriesId)
|
||||
}
|
||||
}, [seriesId])
|
||||
|
||||
const loadConsistencyProfile = (seriesId: string) => {
|
||||
const series = seriesGenerator.getSeries(seriesId)
|
||||
if (series && series.images.length > 0) {
|
||||
const jasonPrompts = series.images.map(image =>
|
||||
jasonProcessor.parseJasonPrompt(image.jasonPrompt || "")
|
||||
).filter(Boolean) as any[]
|
||||
|
||||
if (jasonPrompts.length > 0) {
|
||||
const profile = jasonProcessor.extractConsistencyProfiles(jasonPrompts)
|
||||
setConsistencyProfile(profile)
|
||||
setCharacters(profile.characters)
|
||||
setItems(profile.items)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const addCharacter = () => {
|
||||
const newCharacter: CharacterConsistency = {
|
||||
name: "New Character",
|
||||
description: "Character description",
|
||||
features: {
|
||||
hair: "unknown",
|
||||
eyes: "unknown",
|
||||
clothing: "unknown",
|
||||
accessories: [],
|
||||
expression: "neutral",
|
||||
},
|
||||
consistency: {
|
||||
mustMaintain: ["name", "style"],
|
||||
canVary: ["pose", "expression", "position"],
|
||||
priority: "high",
|
||||
},
|
||||
}
|
||||
setCharacters(prev => [...prev, newCharacter])
|
||||
setEditForm({ type: 'character', data: newCharacter, index: characters.length })
|
||||
setIsEditing(true)
|
||||
}
|
||||
|
||||
const addItem = () => {
|
||||
const newItem: ItemConsistency = {
|
||||
name: "New Item",
|
||||
description: "Item description",
|
||||
features: {
|
||||
color: "unknown",
|
||||
material: "unknown",
|
||||
size: "unknown",
|
||||
},
|
||||
consistency: {
|
||||
mustMaintain: ["name", "style"],
|
||||
canVary: ["position", "lighting", "size"],
|
||||
priority: "medium",
|
||||
},
|
||||
}
|
||||
setItems(prev => [...prev, newItem])
|
||||
setEditForm({ type: 'item', data: newItem, index: items.length })
|
||||
setIsEditing(true)
|
||||
}
|
||||
|
||||
const updateCharacter = (index: number, updatedCharacter: CharacterConsistency) => {
|
||||
const newCharacters = [...characters]
|
||||
newCharacters[index] = updatedCharacter
|
||||
setCharacters(newCharacters)
|
||||
}
|
||||
|
||||
const updateItem = (index: number, updatedItem: ItemConsistency) => {
|
||||
const newItems = [...items]
|
||||
newItems[index] = updatedItem
|
||||
setItems(newItems)
|
||||
}
|
||||
|
||||
const removeCharacter = (index: number) => {
|
||||
setCharacters(prev => prev.filter((_, i) => i !== index))
|
||||
}
|
||||
|
||||
const removeItem = (index: number) => {
|
||||
setItems(prev => prev.filter((_, i) => i !== index))
|
||||
}
|
||||
|
||||
const updateConsistencyProfile = () => {
|
||||
if (characters.length > 0 || items.length > 0) {
|
||||
const profile: SeriesConsistency = {
|
||||
characters,
|
||||
items,
|
||||
colorPalette: consistencyProfile?.colorPalette || [],
|
||||
style: consistencyProfile?.style || "realistic",
|
||||
mood: consistencyProfile?.mood || "neutral",
|
||||
narrativeProgression: consistencyProfile?.narrativeProgression || {
|
||||
start: "Beginning",
|
||||
middle: "Middle",
|
||||
end: "End",
|
||||
},
|
||||
}
|
||||
setConsistencyProfile(profile)
|
||||
onConsistencyUpdate?.(profile)
|
||||
}
|
||||
}
|
||||
|
||||
const saveEdit = () => {
|
||||
if (!editForm) return
|
||||
|
||||
if (editForm.type === 'character') {
|
||||
updateCharacter(editForm.index, editForm.data as CharacterConsistency)
|
||||
} else {
|
||||
updateItem(editForm.index, editForm.data as ItemConsistency)
|
||||
}
|
||||
|
||||
setIsEditing(false)
|
||||
setEditForm(null)
|
||||
updateConsistencyProfile()
|
||||
}
|
||||
|
||||
const getPriorityColor = (priority: string) => {
|
||||
switch (priority) {
|
||||
case 'high': return 'text-red-600 bg-red-50'
|
||||
case 'medium': return 'text-yellow-600 bg-yellow-50'
|
||||
case 'low': return 'text-green-600 bg-green-50'
|
||||
default: return 'text-gray-600 bg-gray-50'
|
||||
}
|
||||
}
|
||||
|
||||
const getPriorityIcon = (priority: string) => {
|
||||
switch (priority) {
|
||||
case 'high': return <AlertCircle className="h-3 w-3" />
|
||||
case 'medium': return <AlertCircle className="h-3 w-3" />
|
||||
case 'low': return <CheckCircle className="h-3 w-3" />
|
||||
default: return <CheckCircle className="h-3 w-3" />
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Overview */}
|
||||
{consistencyProfile && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Settings className="h-5 w-5" />
|
||||
Consistency Overview
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Track character and item consistency across your image series
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid md:grid-cols-4 gap-4">
|
||||
<div className="text-center p-4 bg-muted rounded-lg">
|
||||
<Users className="h-8 w-8 mx-auto mb-2 text-primary" />
|
||||
<div className="text-2xl font-bold">{characters.length}</div>
|
||||
<div className="text-sm text-muted-foreground">Characters</div>
|
||||
</div>
|
||||
<div className="text-center p-4 bg-muted rounded-lg">
|
||||
<Package className="h-8 w-8 mx-auto mb-2 text-accent" />
|
||||
<div className="text-2xl font-bold">{items.length}</div>
|
||||
<div className="text-sm text-muted-foreground">Items</div>
|
||||
</div>
|
||||
<div className="text-center p-4 bg-muted rounded-lg">
|
||||
<Palette className="h-8 w-8 mx-auto mb-2 text-green-600" />
|
||||
<div className="text-2xl font-bold">{consistencyProfile.colorPalette.length}</div>
|
||||
<div className="text-sm text-muted-foreground">Colors</div>
|
||||
</div>
|
||||
<div className="text-center p-4 bg-muted rounded-lg">
|
||||
<Eye className="h-8 w-8 mx-auto mb-2 text-blue-600" />
|
||||
<div className="text-2xl font-bold">
|
||||
{Math.round((characters.length + items.length) * 0.8)}%
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground">Consistency</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Tab Navigation */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Consistency Management</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex gap-2 mb-6">
|
||||
<Button
|
||||
variant={activeTab === 'characters' ? 'default' : 'outline'}
|
||||
onClick={() => setActiveTab('characters')}
|
||||
>
|
||||
<Users className="mr-2 h-4 w-4" />
|
||||
Characters
|
||||
</Button>
|
||||
<Button
|
||||
variant={activeTab === 'items' ? 'default' : 'outline'}
|
||||
onClick={() => setActiveTab('items')}
|
||||
>
|
||||
<Package className="mr-2 h-4 w-4" />
|
||||
Items
|
||||
</Button>
|
||||
<Button
|
||||
variant={activeTab === 'colors' ? 'default' : 'outline'}
|
||||
onClick={() => setActiveTab('colors')}
|
||||
>
|
||||
<Palette className="mr-2 h-4 w-4" />
|
||||
Colors
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Characters Tab */}
|
||||
{activeTab === 'characters' && (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<h3 className="font-medium">Character Profiles</h3>
|
||||
<Button onClick={addCharacter} size="sm">
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Character
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{characters.length === 0 ? (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<Users className="h-12 w-12 mx-auto mb-4 opacity-50" />
|
||||
<p>No characters defined</p>
|
||||
<p className="text-sm">Add characters to maintain consistency</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{characters.map((character, index) => (
|
||||
<Card key={index} className="p-4">
|
||||
<div className="flex justify-between items-start">
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<h4 className="font-medium">{character.name}</h4>
|
||||
<span className={`px-2 py-1 rounded-full text-xs ${getPriorityColor(character.consistency.priority)}`}>
|
||||
{getPriorityIcon(character.consistency.priority)}
|
||||
{character.consistency.priority} priority
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mb-3">
|
||||
{character.description}
|
||||
</p>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-muted-foreground">Appearance:</span>
|
||||
<div className="mt-1">
|
||||
<div>Hair: {character.features.hair}</div>
|
||||
<div>Eyes: {character.features.eyes}</div>
|
||||
<div>Clothing: {character.features.clothing}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">Consistency:</span>
|
||||
<div className="mt-1">
|
||||
<div>Must maintain: {character.consistency.mustMaintain.join(', ')}</div>
|
||||
<div>Can vary: {character.consistency.canVary.join(', ')}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-1 ml-4">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setEditForm({ type: 'character', data: character, index })}
|
||||
>
|
||||
<Edit className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => removeCharacter(index)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Items Tab */}
|
||||
{activeTab === 'items' && (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<h3 className="font-medium">Item Profiles</h3>
|
||||
<Button onClick={addItem} size="sm">
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Item
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{items.length === 0 ? (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<Package className="h-12 w-12 mx-auto mb-4 opacity-50" />
|
||||
<p>No items defined</p>
|
||||
<p className="text-sm">Add items to maintain consistency</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{items.map((item, index) => (
|
||||
<Card key={index} className="p-4">
|
||||
<div className="flex justify-between items-start">
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<h4 className="font-medium">{item.name}</h4>
|
||||
<span className={`px-2 py-1 rounded-full text-xs ${getPriorityColor(item.consistency.priority)}`}>
|
||||
{getPriorityIcon(item.consistency.priority)}
|
||||
{item.consistency.priority} priority
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mb-3">
|
||||
{item.description}
|
||||
</p>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-muted-foreground">Appearance:</span>
|
||||
<div className="mt-1">
|
||||
<div>Color: {item.features.color}</div>
|
||||
<div>Material: {item.features.material}</div>
|
||||
<div>Size: {item.features.size}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">Consistency:</span>
|
||||
<div className="mt-1">
|
||||
<div>Must maintain: {item.consistency.mustMaintain.join(', ')}</div>
|
||||
<div>Can vary: {item.consistency.canVary.join(', ')}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-1 ml-4">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setEditForm({ type: 'item', data: item, index })}
|
||||
>
|
||||
<Edit className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => removeItem(index)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Colors Tab */}
|
||||
{activeTab === 'colors' && (
|
||||
<div className="space-y-4">
|
||||
<h3 className="font-medium">Color Palette</h3>
|
||||
|
||||
{consistencyProfile?.colorPalette ? (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{consistencyProfile.colorPalette.map((color, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="w-12 h-12 rounded-lg border-2 border-gray-200 flex items-center justify-center text-xs font-medium text-white"
|
||||
style={{ backgroundColor: color }}
|
||||
>
|
||||
{color}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<Palette className="h-12 w-12 mx-auto mb-4 opacity-50" />
|
||||
<p>No color palette defined</p>
|
||||
<p className="text-sm">Colors will be extracted from your prompts</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Edit Modal */}
|
||||
{isEditing && editForm && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>
|
||||
{editForm.type === 'character' ? 'Edit Character' : 'Edit Item'}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">Name</label>
|
||||
<Input
|
||||
value={(editForm.data as any).name || ''}
|
||||
onChange={(e) => setEditForm({
|
||||
...editForm,
|
||||
data: { ...editForm.data, name: e.target.value }
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">Description</label>
|
||||
<Input
|
||||
value={(editForm.data as any).description || ''}
|
||||
onChange={(e) => setEditForm({
|
||||
...editForm,
|
||||
data: { ...editForm.data, description: e.target.value }
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{editForm.type === 'character' && (
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">Hair</label>
|
||||
<Input
|
||||
value={(editForm.data as CharacterConsistency).features.hair || ''}
|
||||
onChange={(e) => setEditForm({
|
||||
...editForm,
|
||||
data: {
|
||||
...editForm.data,
|
||||
features: {
|
||||
...editForm.data.features,
|
||||
hair: e.target.value
|
||||
}
|
||||
}
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">Eyes</label>
|
||||
<Input
|
||||
value={(editForm.data as CharacterConsistency).features.eyes || ''}
|
||||
onChange={(e) => setEditForm({
|
||||
...editForm,
|
||||
data: {
|
||||
...editForm.data,
|
||||
features: {
|
||||
...editForm.data.features,
|
||||
eyes: e.target.value
|
||||
}
|
||||
}
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{editForm.type === 'item' && (
|
||||
<div className="grid md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">Color</label>
|
||||
<Input
|
||||
value={(editForm.data as ItemConsistency).features.color || ''}
|
||||
onChange={(e) => setEditForm({
|
||||
...editForm,
|
||||
data: {
|
||||
...editForm.data,
|
||||
features: {
|
||||
...editForm.data.features,
|
||||
color: e.target.value
|
||||
}
|
||||
}
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">Material</label>
|
||||
<Input
|
||||
value={(editForm.data as ItemConsistency).features.material || ''}
|
||||
onChange={(e) => setEditForm({
|
||||
...editForm,
|
||||
data: {
|
||||
...editForm.data,
|
||||
features: {
|
||||
...editForm.data.features,
|
||||
material: e.target.value
|
||||
}
|
||||
}
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">Size</label>
|
||||
<Input
|
||||
value={(editForm.data as ItemConsistency).features.size || ''}
|
||||
onChange={(e) => setEditForm({
|
||||
...editForm,
|
||||
data: {
|
||||
...editForm.data,
|
||||
features: {
|
||||
...editForm.data.features,
|
||||
size: e.target.value
|
||||
}
|
||||
}
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={saveEdit}>Save</Button>
|
||||
<Button variant="outline" onClick={() => setIsEditing(false)}>Cancel</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={updateConsistencyProfile} className="btn-primary">
|
||||
Update Consistency Profile
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
203
Test Ideas/NanoJason/nanojason/src/components/layout/creator.tsx
Normal file
203
Test Ideas/NanoJason/nanojason/src/components/layout/creator.tsx
Normal file
@@ -0,0 +1,203 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Plus, Trash2, Sparkles, Wand2, Layers } from "lucide-react"
|
||||
|
||||
interface SeriesConfig {
|
||||
id: string
|
||||
title: string
|
||||
description: string
|
||||
imageCount: number
|
||||
style: string
|
||||
prompts: string[]
|
||||
}
|
||||
|
||||
export function Creator() {
|
||||
const [prompt, setPrompt] = useState("")
|
||||
const [series, setSeries] = useState<SeriesConfig[]>([{
|
||||
id: "1",
|
||||
title: "My First Series",
|
||||
description: "An epic adventure story",
|
||||
imageCount: 5,
|
||||
style: "anime",
|
||||
prompts: []
|
||||
}])
|
||||
|
||||
const addSeries = () => {
|
||||
const newSeries: SeriesConfig = {
|
||||
id: Date.now().toString(),
|
||||
title: `Series ${series.length + 1}`,
|
||||
description: "Enter series description",
|
||||
imageCount: 5,
|
||||
style: "realistic",
|
||||
prompts: []
|
||||
}
|
||||
setSeries([...series, newSeries])
|
||||
}
|
||||
|
||||
const removeSeries = (id: string) => {
|
||||
setSeries(series.filter(s => s.id !== id))
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="container mx-auto px-4 py-16">
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<div className="text-center mb-12">
|
||||
<h2 className="text-3xl font-bold mb-4">Create Your Image Series</h2>
|
||||
<p className="text-gray-600">
|
||||
Describe your vision and configure your story series
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="mb-8">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Sparkles className="h-5 w-5" />
|
||||
Image Prompt
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Describe the image you want to create. Be detailed and specific
|
||||
for best results.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-4">
|
||||
<Input
|
||||
placeholder="A beautiful magical forest with glowing trees and floating islands..."
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
className="min-h-[100px] resize-none"
|
||||
/>
|
||||
<div className="flex justify-end">
|
||||
<Button className="bg-blue-600 text-white hover:bg-blue-700">
|
||||
<Wand2 className="mr-2 h-4 w-4" />
|
||||
Generate Ideas
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Layers className="h-5 w-5" />
|
||||
Series Configuration
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={addSeries}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add Series
|
||||
</Button>
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Configure up to 30 images per series with consistent characters
|
||||
and narrative flow.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-6">
|
||||
{series.map((item) => (
|
||||
<div key={item.id} className="border border-gray-200 rounded-lg p-4 space-y-4">
|
||||
<div className="flex justify-between items-start">
|
||||
<div className="flex-1 space-y-3">
|
||||
<Input
|
||||
placeholder="Series title"
|
||||
value={item.title}
|
||||
onChange={(e) => {
|
||||
const updated = series.map(s =>
|
||||
s.id === item.id ? {...s, title: e.target.value} : s
|
||||
)
|
||||
setSeries(updated)
|
||||
}}
|
||||
/>
|
||||
<Input
|
||||
placeholder="Series description"
|
||||
value={item.description}
|
||||
onChange={(e) => {
|
||||
const updated = series.map(s =>
|
||||
s.id === item.id ? {...s, description: e.target.value} : s
|
||||
)
|
||||
setSeries(updated)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => removeSeries(item.id)}
|
||||
className="text-red-600 hover:text-red-700"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">
|
||||
Number of Images
|
||||
</label>
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
max="30"
|
||||
value={item.imageCount}
|
||||
onChange={(e) => {
|
||||
const updated = series.map(s =>
|
||||
s.id === item.id ? {...s, imageCount: parseInt(e.target.value)} : s
|
||||
)
|
||||
setSeries(updated)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">
|
||||
Art Style
|
||||
</label>
|
||||
<select
|
||||
className="flex h-10 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm"
|
||||
value={item.style}
|
||||
onChange={(e) => {
|
||||
const updated = series.map(s =>
|
||||
s.id === item.id ? {...s, style: e.target.value} : s
|
||||
)
|
||||
setSeries(updated)
|
||||
}}
|
||||
>
|
||||
<option value="realistic">Realistic</option>
|
||||
<option value="anime">Anime</option>
|
||||
<option value="cartoon">Cartoon</option>
|
||||
<option value="fantasy">Fantasy</option>
|
||||
<option value="cyberpunk">Cyberpunk</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="mt-6 pt-6 border-t border-gray-200">
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="text-sm text-gray-600">
|
||||
Total images: {series.reduce((sum, item) => sum + item.imageCount, 0)}
|
||||
</div>
|
||||
<div className="space-x-2">
|
||||
<Button variant="outline">
|
||||
Save Draft
|
||||
</Button>
|
||||
<Button className="bg-blue-600 text-white hover:bg-blue-700">
|
||||
<Sparkles className="mr-2 h-4 w-4" />
|
||||
Generate Series
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
166
Test Ideas/NanoJason/nanojason/src/components/layout/gallery.tsx
Normal file
166
Test Ideas/NanoJason/nanojason/src/components/layout/gallery.tsx
Normal file
@@ -0,0 +1,166 @@
|
||||
"use client"
|
||||
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Download, Copy, Eye, Share } from "lucide-react"
|
||||
|
||||
interface GeneratedImage {
|
||||
id: string
|
||||
title: string
|
||||
prompt: string
|
||||
jasonPrompt: string
|
||||
thumbnail: string
|
||||
seriesId: string
|
||||
}
|
||||
|
||||
interface GalleryProps {
|
||||
images: GeneratedImage[]
|
||||
onExport?: (image: GeneratedImage) => void
|
||||
onCopy?: (prompt: string) => void
|
||||
}
|
||||
|
||||
export function Gallery({ images, onExport, onCopy }: GalleryProps) {
|
||||
const selectedImage = images[0] // Mock selection
|
||||
|
||||
return (
|
||||
<section className="container mx-auto px-4 py-16">
|
||||
<div className="text-center mb-12">
|
||||
<h2 className="text-3xl font-bold mb-4">Generated Image Series</h2>
|
||||
<p className="text-gray-600">
|
||||
Your AI-generated images with Jason language prompts for maximum compatibility
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="max-w-6xl mx-auto">
|
||||
{/* Main Image Display */}
|
||||
<div className="grid lg:grid-cols-3 gap-8 mb-8">
|
||||
<div className="lg:col-span-2">
|
||||
<Card className="overflow-hidden">
|
||||
<div className="aspect-square bg-gradient-to-br from-blue-100 to-purple-100 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<div className="w-24 h-24 mx-auto mb-4 bg-blue-200 rounded-full flex items-center justify-center">
|
||||
<Eye className="h-12 w-12 text-blue-600" />
|
||||
</div>
|
||||
<p className="text-gray-600">Generated Image Preview</p>
|
||||
<p className="text-sm font-medium mt-1">{selectedImage?.title}</p>
|
||||
</div>
|
||||
</div>
|
||||
<CardContent className="p-6">
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h4 className="font-medium mb-2">Original Prompt</h4>
|
||||
<div className="p-3 bg-gray-100 rounded-lg text-sm">
|
||||
{selectedImage?.prompt}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-medium mb-2">Jason Language Prompt</h4>
|
||||
<div className="p-3 bg-gray-100 rounded-lg text-sm font-mono">
|
||||
{selectedImage?.jasonPrompt}
|
||||
</div>
|
||||
<div className="flex gap-2 mt-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onCopy?.(selectedImage?.jasonPrompt || "")}
|
||||
>
|
||||
<Copy className="h-4 w-4 mr-2" />
|
||||
Copy
|
||||
</Button>
|
||||
<Button variant="outline" size="sm">
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
Export
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Series Information</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Title</p>
|
||||
<p className="font-medium">{selectedImage?.title}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Images in Series</p>
|
||||
<p className="font-medium">{images.length}/30</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-600">Style</p>
|
||||
<p className="font-medium">Anime Fantasy</p>
|
||||
</div>
|
||||
<Button className="w-full mt-4">
|
||||
<Share className="mr-2 h-4 w-4" />
|
||||
Share Series
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Quick Actions</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
<Button variant="outline" className="w-full justify-start">
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
Download All
|
||||
</Button>
|
||||
<Button variant="outline" className="w-full justify-start">
|
||||
<Copy className="mr-2 h-4 w-4" />
|
||||
Copy All Prompts
|
||||
</Button>
|
||||
<Button variant="outline" className="w-full justify-start">
|
||||
<Eye className="mr-2 h-4 w-4" />
|
||||
View Slideshow
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Image Grid */}
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
|
||||
{images.map((image) => (
|
||||
<Card key={image.id} className="overflow-hidden transition-transform hover:scale-105 cursor-pointer">
|
||||
<div className="aspect-square bg-gradient-to-br from-blue-100 to-purple-100 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<div className="w-16 h-16 mx-auto mb-2 bg-blue-200 rounded-full flex items-center justify-center">
|
||||
<Eye className="h-8 w-8 text-blue-600" />
|
||||
</div>
|
||||
<p className="text-xs font-medium truncate px-2">{image.title}</p>
|
||||
</div>
|
||||
</div>
|
||||
<CardContent className="p-4">
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs text-gray-600 truncate">
|
||||
{image.prompt.substring(0, 50)}...
|
||||
</p>
|
||||
<div className="flex gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
onClick={() => onCopy?.(image.jasonPrompt)}
|
||||
>
|
||||
<Copy className="h-3 w-3" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" className="flex-1">
|
||||
<Download className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
"use client"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Sparkles, Wand2, Palette, Zap } from "lucide-react"
|
||||
|
||||
export function Hero() {
|
||||
return (
|
||||
<section className="container mx-auto px-4 py-16 text-center">
|
||||
<div className="mb-8">
|
||||
<div className="flex justify-center mb-4">
|
||||
<div className="relative">
|
||||
<Sparkles className="h-16 w-16 bg-gradient-to-r from-blue-600 to-purple-600 text-white animate-pulse" />
|
||||
<div className="absolute -top-2 -right-2 h-8 w-8 bg-purple-500 rounded-full animate-pulse"></div>
|
||||
<div className="absolute -bottom-2 -left-2 h-6 w-6 bg-blue-500 rounded-full animate-pulse"></div>
|
||||
</div>
|
||||
</div>
|
||||
<h1 className="text-4xl md:text-6xl font-bold mb-4">
|
||||
Transform Your Ideas Into
|
||||
<br />
|
||||
<span className="bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
|
||||
Visual Stories
|
||||
</span>
|
||||
</h1>
|
||||
<p className="text-xl text-gray-600 max-w-2xl mx-auto mb-8">
|
||||
Create stunning image series with consistent characters and narrative.
|
||||
Powered by AI and designed for storytellers.
|
||||
</p>
|
||||
<div className="flex gap-4 justify-center flex-wrap">
|
||||
<Button size="lg" className="bg-blue-600 text-white hover:bg-blue-700">
|
||||
<Wand2 className="mr-2 h-4 w-4" />
|
||||
Start Creating
|
||||
</Button>
|
||||
<Button variant="outline" size="lg">
|
||||
View Examples
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid md:grid-cols-3 gap-6 mt-16">
|
||||
<Card className="transition-transform hover:scale-105 hover:shadow-lg">
|
||||
<CardHeader>
|
||||
<div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center mb-4">
|
||||
<Palette className="h-6 w-6 text-blue-600" />
|
||||
</div>
|
||||
<CardTitle>AI-Powered Creation</CardTitle>
|
||||
<CardDescription>
|
||||
Describe your vision and let AI transform it into beautiful images
|
||||
with consistent characters and style.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
|
||||
<Card className="transition-transform hover:scale-105 hover:shadow-lg">
|
||||
<CardHeader>
|
||||
<div className="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center mb-4">
|
||||
<Sparkles className="h-6 w-6 text-purple-600" />
|
||||
</div>
|
||||
<CardTitle>Story Series</CardTitle>
|
||||
<CardDescription>
|
||||
Create up to 30 images in a single series with automatic narrative
|
||||
generation and character consistency.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
|
||||
<Card className="transition-transform hover:scale-105 hover:shadow-lg">
|
||||
<CardHeader>
|
||||
<div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center mb-4">
|
||||
<Zap className="h-6 w-6 text-blue-600" />
|
||||
</div>
|
||||
<CardTitle>Universal Compatibility</CardTitle>
|
||||
<CardDescription>
|
||||
Export prompts in Jason language format for any image generation
|
||||
service including NanoBanana and more.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { jasonTranslator, type JasonPrompt } from "@/services/jason-translator"
|
||||
import { Sparkles, Wand2, Copy, Download, Settings, CheckCircle, AlertCircle } from "lucide-react"
|
||||
|
||||
export function JasonEditor() {
|
||||
const [inputText, setInputText] = useState("")
|
||||
const [jasonPrompt, setJasonPrompt] = useState<JasonPrompt | null>(null)
|
||||
const [validation, setValidation] = useState<{ isValid: boolean; errors: string[]; warnings: string[] } | null>(null)
|
||||
|
||||
const handleTranslate = () => {
|
||||
if (!inputText.trim()) {
|
||||
setValidation({
|
||||
isValid: false,
|
||||
errors: ['Input text is required'],
|
||||
warnings: [],
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const result = jasonTranslator.translateToJason(inputText, {
|
||||
preferredStyle: undefined,
|
||||
preferredMood: undefined,
|
||||
includeCharacters: true,
|
||||
includeItems: true,
|
||||
})
|
||||
|
||||
setJasonPrompt(result)
|
||||
setValidation(jasonTranslator.validateJasonPrompt(result))
|
||||
}
|
||||
|
||||
const handleQuickTemplate = (template: 'portrait' | 'landscape' | 'action' | 'fantasy' | 'sci-fi') => {
|
||||
const result = jasonTranslator.createQuickJason(template)
|
||||
setJasonPrompt(result)
|
||||
setValidation(jasonTranslator.validateJasonPrompt(result))
|
||||
setInputText(result.prompt)
|
||||
}
|
||||
|
||||
const copyToClipboard = (text: string) => {
|
||||
navigator.clipboard.writeText(text)
|
||||
// Show success message here
|
||||
}
|
||||
|
||||
const downloadJason = () => {
|
||||
if (!jasonPrompt) return
|
||||
|
||||
const dataStr = JSON.stringify(jasonPrompt, 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-prompt.json'
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-16">
|
||||
<div className="max-w-4xl mx-auto space-y-8">
|
||||
<div className="text-center mb-8">
|
||||
<h2 className="text-3xl font-bold mb-4">Jason Language Editor</h2>
|
||||
<p className="text-gray-600">
|
||||
Convert natural language to Jason format - no AI API required!
|
||||
Perfect for offline use and universal compatibility.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid lg:grid-cols-2 gap-8">
|
||||
{/* Input Section */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Wand2 className="h-5 w-5" />
|
||||
Natural Language Input
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Describe your image in plain English. The translator will automatically
|
||||
detect style, mood, characters, and items.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">
|
||||
Your Description
|
||||
</label>
|
||||
<textarea
|
||||
className="flex min-h-[200px] w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm placeholder:text-gray-500 resize-none"
|
||||
placeholder="A beautiful magical forest with glowing trees where a young wizard discovers an ancient crystal..."
|
||||
value={inputText}
|
||||
onChange={(e) => setInputText(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={handleTranslate} className="flex-1">
|
||||
<Sparkles className="mr-2 h-4 w-4" />
|
||||
Translate to Jason
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Quick Templates */}
|
||||
<div className="pt-4 border-t border-gray-200">
|
||||
<h4 className="text-sm font-medium mb-3">Quick Templates</h4>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{(['portrait', 'landscape', 'action', 'fantasy', 'sci-fi'] as const).map(template => (
|
||||
<Button
|
||||
key={template}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleQuickTemplate(template)}
|
||||
className="capitalize"
|
||||
>
|
||||
{template}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Jason Output Section */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Settings className="h-5 w-5" />
|
||||
Jason Language Output
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Universal prompt format compatible with NanoBanana, OpenAI, Midjourney, and more.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{jasonPrompt ? (
|
||||
<div className="space-y-4">
|
||||
{/* Validation Results */}
|
||||
{validation && (
|
||||
<div className="space-y-2">
|
||||
{validation.isValid ? (
|
||||
<div className="flex items-center gap-2 p-2 bg-green-50 border border-green-200 rounded-lg text-green-700 text-sm">
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
Valid Jason prompt
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{validation.errors.map((error, index) => (
|
||||
<div key={index} className="flex items-center gap-2 p-2 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
{error}
|
||||
</div>
|
||||
))}
|
||||
{validation.warnings.map((warning, index) => (
|
||||
<div key={index} className="flex items-center gap-2 p-2 bg-yellow-50 border border-yellow-200 rounded-lg text-yellow-700 text-sm">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
{warning}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Jason Prompt Display */}
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">JSON Output</label>
|
||||
<div className="p-3 bg-gray-100 rounded-lg text-sm font-mono max-h-[400px] overflow-auto">
|
||||
{JSON.stringify(jasonPrompt, null, 2)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<Button variant="outline" onClick={() => copyToClipboard(JSON.stringify(jasonPrompt, null, 2))}>
|
||||
<Copy className="mr-2 h-4 w-4" />
|
||||
Copy JSON
|
||||
</Button>
|
||||
<Button variant="outline" onClick={downloadJason}>
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
Download
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Detected Elements */}
|
||||
<div className="space-y-3 pt-4 border-t border-gray-200">
|
||||
<h4 className="text-sm font-medium mb-2">Detected Elements</h4>
|
||||
|
||||
<div className="grid md:grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="font-medium">Style:</span>
|
||||
<span className="ml-2 bg-blue-100 text-blue-800 px-2 py-1 rounded text-xs">
|
||||
{jasonPrompt.style}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span className="font-medium">Mood:</span>
|
||||
<span className="ml-2 bg-purple-100 text-purple-800 px-2 py-1 rounded text-xs">
|
||||
{jasonPrompt.mood}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span className="font-medium">Characters:</span>
|
||||
<div className="mt-1 flex flex-wrap gap-1">
|
||||
{jasonPrompt.characters?.map(char => (
|
||||
<span key={char} className="bg-green-100 text-green-800 px-2 py-1 rounded text-xs">
|
||||
{char}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span className="font-medium">Color Palette:</span>
|
||||
<div className="mt-1 flex flex-wrap gap-1">
|
||||
{jasonPrompt.consistency?.colorPalette?.map(color => (
|
||||
<span key={color} className="bg-gray-200 text-gray-800 px-2 py-1 rounded text-xs">
|
||||
{color}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center py-8 text-gray-500">
|
||||
<Settings className="h-12 w-12 mx-auto mb-4 opacity-50" />
|
||||
<p>Your translated Jason prompt will appear here</p>
|
||||
<p className="text-sm">Enter a description and click "Translate to Jason" to get started</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Features Section */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Offline Jason Language Features</CardTitle>
|
||||
<CardDescription>
|
||||
Pattern-based translation that works completely offline
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid md:grid-cols-3 gap-6 text-sm">
|
||||
<div className="space-y-2">
|
||||
<h4 className="font-medium">🎨 Style Detection</h4>
|
||||
<ul className="space-y-1 text-gray-600">
|
||||
<li>Realistic, Anime, Cartoon, Fantasy</li>
|
||||
<li>Cyberpunk, Artistic, Photorealistic</li>
|
||||
<li>Automatically detected from keywords</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<h4 className="font-medium">🎭 Mood Analysis</h4>
|
||||
<ul className="space-y-1 text-gray-600">
|
||||
<li>Happy, Sad, Angry, Peaceful</li>
|
||||
<li>Mysterious, Epic, Wonderful</li>
|
||||
<li>Context-based mood detection</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<h4 className="font-medium">👥 Character & Items</h4>
|
||||
<ul className="space-y-1 text-gray-600">
|
||||
<li>Pattern-based character extraction</li>
|
||||
<li>Automatic item identification</li>
|
||||
<li>Color and material analysis</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { jasonProcessor } from "@/services/jason-processor"
|
||||
import { Copy, Download, Settings, Wand2, Palette, Users } from "lucide-react"
|
||||
|
||||
interface JasonOptimizerProps {
|
||||
originalPrompt: string
|
||||
onOptimized?: (optimizedJason: string) => void
|
||||
}
|
||||
|
||||
export function JasonOptimizer({ originalPrompt, onOptimized }: JasonOptimizerProps) {
|
||||
const [jasonPrompt, setJasonPrompt] = useState("")
|
||||
const [style, setStyle] = useState("realistic")
|
||||
const [mood, setMood] = useState("neutral")
|
||||
const [characters, setCharacters] = useState("")
|
||||
const [colorPalette, setColorPalette] = useState("")
|
||||
const [targetService, setTargetService] = useState<"nanojason" | "nanobanana" | "openai" | "midjourney">("nanojason")
|
||||
const [validation, setValidation] = useState<{ valid: boolean; errors: string[]; warnings: string[] } | null>(null)
|
||||
|
||||
const generateJason = () => {
|
||||
try {
|
||||
const characterArray = characters.split(',').map(c => c.trim()).filter(c => c)
|
||||
const colorArray = colorPalette.split(',').map(c => c.trim()).filter(c => c)
|
||||
|
||||
const optimized = jasonProcessor.generateJasonFromPrompt(originalPrompt, {
|
||||
style,
|
||||
mood,
|
||||
characters: characterArray.length > 0 ? characterArray : undefined,
|
||||
consistency: {
|
||||
colorPalette: colorArray.length > 0 ? colorArray : undefined,
|
||||
characterFeatures: {
|
||||
style,
|
||||
mood,
|
||||
},
|
||||
},
|
||||
metadata: {
|
||||
targetService,
|
||||
version: "1.0",
|
||||
},
|
||||
})
|
||||
|
||||
setJasonPrompt(optimized)
|
||||
|
||||
// Validate the generated prompt
|
||||
const validationResult = jasonProcessor.validateJasonPrompt(optimized)
|
||||
setValidation(validationResult)
|
||||
|
||||
if (onOptimized) {
|
||||
onOptimized(optimized)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to generate Jason prompt:', error)
|
||||
}
|
||||
}
|
||||
|
||||
const optimizeForService = () => {
|
||||
try {
|
||||
const parsed = jasonProcessor.parseJasonPrompt(jasonPrompt)
|
||||
if (!parsed) {
|
||||
throw new Error('Invalid Jason prompt')
|
||||
}
|
||||
|
||||
const optimized = jasonProcessor.optimizeForService(parsed, targetService)
|
||||
const optimizedString = JSON.stringify(optimized, null, 2)
|
||||
|
||||
setJasonPrompt(optimizedString)
|
||||
setValidation(jasonProcessor.validateJasonPrompt(optimizedString))
|
||||
|
||||
if (onOptimized) {
|
||||
onOptimized(optimizedString)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to optimize for service:', error)
|
||||
}
|
||||
}
|
||||
|
||||
const copyToClipboard = () => {
|
||||
navigator.clipboard.writeText(jasonPrompt)
|
||||
// Add toast notification here
|
||||
}
|
||||
|
||||
const downloadJason = () => {
|
||||
const blob = new Blob([jasonPrompt], { type: 'application/json' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = 'jason-prompt.json'
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
const commonStyles = [
|
||||
"realistic", "anime", "cartoon", "fantasy",
|
||||
"cyberpunk", "artistic", "painterly", "photorealistic"
|
||||
]
|
||||
|
||||
const commonMoods = [
|
||||
"happy", "sad", "angry", "peaceful", "mysterious",
|
||||
"epic", "wonderful", "dramatic", "romantic", "tense"
|
||||
]
|
||||
|
||||
const commonServices = [
|
||||
{ value: "nanojason", label: "NanoJason" },
|
||||
{ value: "nanobanana", label: "NanoBanana" },
|
||||
{ value: "openai", label: "OpenAI DALL-E" },
|
||||
{ value: "midjourney", label: "Midjourney" },
|
||||
]
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Wand2 className="h-5 w-5" />
|
||||
Jason Prompt Optimizer
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Convert your prompt to Jason language format and optimize for different AI services
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Configuration */}
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">
|
||||
Art Style
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{commonStyles.map(s => (
|
||||
<button
|
||||
key={s}
|
||||
className={`px-3 py-1 rounded-full text-sm transition-colors ${
|
||||
style === s
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "bg-muted hover:bg-muted/80"
|
||||
}`}
|
||||
onClick={() => setStyle(s)}
|
||||
>
|
||||
{s}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">
|
||||
Mood
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{commonMoods.map(m => (
|
||||
<button
|
||||
key={m}
|
||||
className={`px-3 py-1 rounded-full text-sm transition-colors ${
|
||||
mood === m
|
||||
? "bg-accent text-accent-foreground"
|
||||
: "bg-muted hover:bg-muted/80"
|
||||
}`}
|
||||
onClick={() => setMood(m)}
|
||||
>
|
||||
{m}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Characters Input */}
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 flex items-center gap-2">
|
||||
<Users className="h-4 w-4" />
|
||||
Characters (comma-separated)
|
||||
</label>
|
||||
<Input
|
||||
placeholder="hero, villain, sidekick..."
|
||||
value={characters}
|
||||
onChange={(e) => setCharacters(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Color Palette */}
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 flex items-center gap-2">
|
||||
<Palette className="h-4 w-4" />
|
||||
Color Palette (comma-separated)
|
||||
</label>
|
||||
<Input
|
||||
placeholder="blue, gold, green..."
|
||||
value={colorPalette}
|
||||
onChange={(e) => setColorPalette(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Target Service */}
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">
|
||||
Target Service
|
||||
</label>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{commonServices.map(service => (
|
||||
<button
|
||||
key={service.value}
|
||||
className={`px-3 py-2 rounded-lg text-sm transition-colors ${
|
||||
targetService === service.value
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "bg-muted hover:bg-muted/80"
|
||||
}`}
|
||||
onClick={() => setTargetService(service.value as any)}
|
||||
>
|
||||
{service.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={generateJason} className="btn-primary">
|
||||
<Wand2 className="mr-2 h-4 w-4" />
|
||||
Generate Jason
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={optimizeForService}
|
||||
disabled={!jasonPrompt}
|
||||
>
|
||||
<Settings className="mr-2 h-4 w-4" />
|
||||
Optimize
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Generated Jason Prompt */}
|
||||
{jasonPrompt && (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<label className="text-sm font-medium">Generated Jason Prompt</label>
|
||||
<div className="flex gap-1">
|
||||
<Button variant="ghost" size="sm" onClick={copyToClipboard}>
|
||||
<Copy className="h-3 w-3" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={downloadJason}>
|
||||
<Download className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-3 bg-muted rounded-lg">
|
||||
<pre className="text-sm font-mono whitespace-pre-wrap">
|
||||
{jasonPrompt}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Validation */}
|
||||
{validation && (
|
||||
<div className="space-y-2">
|
||||
{validation.valid ? (
|
||||
<div className="p-3 bg-green-50 border border-green-200 rounded-lg text-green-700 text-sm">
|
||||
✓ Valid Jason prompt
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
|
||||
✗ Invalid Jason prompt
|
||||
</div>
|
||||
)}
|
||||
|
||||
{validation.warnings.length > 0 && (
|
||||
<div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg text-yellow-700 text-sm">
|
||||
<div className="font-medium mb-1">Warnings:</div>
|
||||
<ul className="list-disc list-inside space-y-1">
|
||||
{validation.warnings.map((warning, index) => (
|
||||
<li key={index}>{warning}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{validation.errors.length > 0 && (
|
||||
<div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
|
||||
<div className="font-medium mb-1">Errors:</div>
|
||||
<ul className="list-disc list-inside space-y-1">
|
||||
{validation.errors.map((error, index) => (
|
||||
<li key={index}>{error}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { ollamaClient, OLLAMA_CLOUD_MODELS } from "@/services/ollama-client"
|
||||
import { seriesGenerator } from "@/services/series-generator"
|
||||
import { Settings, Key, CheckCircle, AlertCircle, ExternalLink, Save } from "lucide-react"
|
||||
|
||||
export default function OllamaSettings() {
|
||||
const [apiKey, setApiKey] = useState("")
|
||||
const [isSaved, setIsSaved] = useState(false)
|
||||
const [isChecking, setIsChecking] = useState(false)
|
||||
const [status, setStatus] = useState<{
|
||||
available: boolean
|
||||
modelsAvailable: string[]
|
||||
apiKeySet: boolean
|
||||
error?: string
|
||||
} | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
// Check current API key status
|
||||
const keyInfo = ollamaClient.getApiKeyInfo()
|
||||
if (keyInfo.isSet) {
|
||||
setApiKey(keyInfo.source === 'environment' ? '•••••••••••••••••••••••' : keyInfo.source === 'localStorage' ? '••••••••••••••••••••' : '')
|
||||
checkStatus()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const checkStatus = async () => {
|
||||
setIsChecking(true)
|
||||
setStatus(null)
|
||||
|
||||
try {
|
||||
const status = await seriesGenerator.checkOllamaStatus()
|
||||
setStatus(status)
|
||||
} catch (error) {
|
||||
setStatus({
|
||||
available: false,
|
||||
modelsAvailable: [],
|
||||
apiKeySet: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
})
|
||||
} finally {
|
||||
setIsChecking(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSaveKey = () => {
|
||||
if (!apiKey.trim()) {
|
||||
return
|
||||
}
|
||||
|
||||
ollamaClient.setApiKey(apiKey.trim(), true)
|
||||
setIsSaved(true)
|
||||
setTimeout(() => setIsSaved(false), 2000)
|
||||
checkStatus()
|
||||
}
|
||||
|
||||
const handleClearKey = () => {
|
||||
ollamaClient.clearApiKey()
|
||||
setApiKey("")
|
||||
setStatus(null)
|
||||
}
|
||||
|
||||
const getApiKeyDisplay = () => {
|
||||
if (!apiKey) return ""
|
||||
|
||||
// Mask API key for display
|
||||
if (apiKey.length <= 8) return '••••••'
|
||||
return apiKey.substring(0, 4) + '••••••' + apiKey.substring(apiKey.length - 4)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-16">
|
||||
<div className="max-w-2xl mx-auto space-y-8">
|
||||
<div className="text-center mb-8">
|
||||
<div className="flex justify-center mb-4">
|
||||
<Settings className="h-12 w-12 text-blue-600" />
|
||||
</div>
|
||||
<h2 className="text-3xl font-bold mb-4">Ollama Cloud Settings</h2>
|
||||
<p className="text-gray-600">
|
||||
Configure Ollama Cloud API key for AI-powered story generation
|
||||
</p>
|
||||
<div className="flex justify-center gap-2">
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<a
|
||||
href="https://ollama.com"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center"
|
||||
>
|
||||
<ExternalLink className="mr-2 h-4 w-4" />
|
||||
Get Free API Key
|
||||
</a>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={checkStatus}
|
||||
disabled={isChecking}
|
||||
>
|
||||
{isChecking ? 'Checking...' : 'Check Status'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* API Key Input */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Key className="h-5 w-5" />
|
||||
API Key Configuration
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Your API key will be stored securely and used for AI story generation.
|
||||
Get a free key at <a href="https://ollama.com" target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">ollama.com</a>
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">
|
||||
Ollama API Key
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="Enter your Ollama Cloud API key..."
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
className="pr-10"
|
||||
/>
|
||||
<div className="absolute right-3 top-1/2 transform -translate-y-1/2">
|
||||
{apiKey && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleClearKey}
|
||||
className="h-8 px-2"
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">
|
||||
{apiKey ? `Key: ${getApiKeyDisplay()}` : 'No key set'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={handleSaveKey}
|
||||
disabled={!apiKey.trim() || isSaved}
|
||||
className="flex-1"
|
||||
>
|
||||
<Save className="mr-2 h-4 w-4" />
|
||||
{isSaved ? 'Saved!' : 'Save Key'}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Status Display */}
|
||||
{status && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
{status.available ? (
|
||||
<CheckCircle className="h-5 w-5 text-green-600" />
|
||||
) : (
|
||||
<AlertCircle className="h-5 w-5 text-red-600" />
|
||||
)}
|
||||
Ollama Cloud Status
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{status.error ? (
|
||||
<div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
|
||||
<AlertCircle className="h-4 w-4 inline mr-2" />
|
||||
{status.error}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium">Connection Status:</span>
|
||||
<span className={`px-2 py-1 rounded text-xs ${
|
||||
status.available
|
||||
? 'bg-green-100 text-green-800'
|
||||
: 'bg-red-100 text-red-800'
|
||||
}`}>
|
||||
{status.available ? 'Connected' : 'Disconnected'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium">API Key Status:</span>
|
||||
<span className={`px-2 py-1 rounded text-xs ${
|
||||
status.apiKeySet
|
||||
? 'bg-green-100 text-green-800'
|
||||
: 'bg-yellow-100 text-yellow-800'
|
||||
}`}>
|
||||
{status.apiKeySet ? 'Set' : 'Not Set'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{status.modelsAvailable && status.modelsAvailable.length > 0 && (
|
||||
<div>
|
||||
<span className="text-sm font-medium block mb-2">Available Models:</span>
|
||||
<div className="space-y-1">
|
||||
{status.modelsAvailable.map(model => (
|
||||
<div key={model} className="text-xs bg-gray-100 text-gray-800 px-2 py-1 rounded">
|
||||
{model}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Available Models */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Supported Cloud Models</CardTitle>
|
||||
<CardDescription>
|
||||
Free and paid models available through Ollama Cloud
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
{Object.entries(OLLAMA_CLOUD_MODELS).map(([model, description]) => (
|
||||
<div key={model} className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-mono text-sm bg-gray-100 px-2 py-1 rounded">
|
||||
{model}
|
||||
</span>
|
||||
<span className="text-sm text-gray-600 truncate">
|
||||
{description.split(' - ')[0]}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">
|
||||
{description.split(' - ')[1]}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Instructions */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Setup Instructions</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3 text-sm">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0">
|
||||
<span className="text-blue-600 font-bold">1</span>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Get Free API Key</p>
|
||||
<p className="text-gray-600">Visit <a href="https://ollama.com" target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">ollama.com</a> and create a free account</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0">
|
||||
<span className="text-blue-600 font-bold">2</span>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Copy API Key</p>
|
||||
<p className="text-gray-600">Enter your API key in the field above and click "Save Key"</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0">
|
||||
<span className="text-blue-600 font-bold">3</span>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Start Creating Stories</p>
|
||||
<p className="text-gray-600">Use the Series Creator to generate AI-powered visual stories</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { seriesGenerator, GeneratedSeries, SeriesConfig } from "@/services/series-generator"
|
||||
import { jasonProcessor } from "@/services/jason-processor"
|
||||
import { Plus, Play, Pause, Trash2, Download, Share, Settings, Sparkles, Image as ImageIcon } from "lucide-react"
|
||||
|
||||
interface SeriesManagerProps {
|
||||
onSeriesSelect?: (series: GeneratedSeries) => void
|
||||
onImageGenerate?: (seriesId: string) => void
|
||||
}
|
||||
|
||||
export function SeriesManager({ onSeriesSelect, onImageGenerate }: SeriesManagerProps) {
|
||||
const [series, setSeries] = useState<GeneratedSeries[]>([])
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [selectedSeries, setSelectedSeries] = useState<GeneratedSeries | null>(null)
|
||||
const [isGenerating, setIsGenerating] = useState(false)
|
||||
const [newSeriesTitle, setNewSeriesTitle] = useState("")
|
||||
const [newSeriesDescription, setNewSeriesDescription] = useState("")
|
||||
const [newSeriesCount, setNewSeriesCount] = useState(5)
|
||||
const [newSeriesStyle, setNewSeriesStyle] = useState("realistic")
|
||||
|
||||
useEffect(() => {
|
||||
loadSeries()
|
||||
}, [])
|
||||
|
||||
const loadSeries = () => {
|
||||
const savedSeries = seriesGenerator.getAllSeries()
|
||||
setSeries(savedSeries)
|
||||
}
|
||||
|
||||
const createNewSeries = async () => {
|
||||
if (!newSeriesTitle || !newSeriesDescription) {
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
|
||||
try {
|
||||
const config: SeriesConfig = {
|
||||
id: `config-${Date.now()}`,
|
||||
title: newSeriesTitle,
|
||||
description: newSeriesDescription,
|
||||
imageCount: newSeriesCount,
|
||||
style: newSeriesStyle,
|
||||
prompts: [], // Will be populated later
|
||||
}
|
||||
|
||||
const newSeries = await seriesGenerator.createSeries(
|
||||
"A new series based on the concept",
|
||||
config
|
||||
)
|
||||
|
||||
setSeries(prev => [newSeries, ...prev])
|
||||
setSelectedSeries(newSeries)
|
||||
|
||||
// Reset form
|
||||
setNewSeriesTitle("")
|
||||
setNewSeriesDescription("")
|
||||
setNewSeriesCount(5)
|
||||
setNewSeriesStyle("realistic")
|
||||
|
||||
} catch (error) {
|
||||
console.error('Failed to create series:', error)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const generateImagesForSeries = async (seriesId: string) => {
|
||||
setIsGenerating(true)
|
||||
|
||||
try {
|
||||
await onImageGenerate?.(seriesId)
|
||||
|
||||
// Simulate image generation
|
||||
setTimeout(() => {
|
||||
const generatedSeries = seriesGenerator.getSeries(seriesId)
|
||||
if (generatedSeries) {
|
||||
setSeries(prev => prev.map(s => s.id === seriesId ? generatedSeries : s))
|
||||
}
|
||||
setIsGenerating(false)
|
||||
}, 3000) // Simulate generation time
|
||||
|
||||
} catch (error) {
|
||||
console.error('Failed to generate images:', error)
|
||||
setIsGenerating(false)
|
||||
}
|
||||
}
|
||||
|
||||
const deleteSeries = (seriesId: string) => {
|
||||
seriesGenerator.deleteSeries(seriesId)
|
||||
setSeries(prev => prev.filter(s => s.id !== seriesId))
|
||||
if (selectedSeries?.id === seriesId) {
|
||||
setSelectedSeries(null)
|
||||
}
|
||||
}
|
||||
|
||||
const exportSeries = (series: GeneratedSeries) => {
|
||||
const exportData = {
|
||||
config: series.config,
|
||||
images: series.images,
|
||||
exportDate: new Date().toISOString(),
|
||||
}
|
||||
|
||||
const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `${series.config.title.replace(/\s+/g, '_')}_series.json`
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
const shareSeries = (series: GeneratedSeries) => {
|
||||
const shareData = {
|
||||
title: series.config.title,
|
||||
description: series.config.description,
|
||||
imageCount: series.config.imageCount,
|
||||
style: series.config.style,
|
||||
prompts: series.config.prompts,
|
||||
}
|
||||
|
||||
if (navigator.share) {
|
||||
navigator.share({
|
||||
title: shareData.title,
|
||||
text: `${shareData.description} - ${shareData.imageCount} images in ${shareData.style} style`,
|
||||
url: window.location.href,
|
||||
})
|
||||
} else {
|
||||
// Fallback: copy to clipboard
|
||||
const shareText = `${shareData.title}\n${shareData.description}\n${shareData.imageCount} images in ${shareData.style} style\n\nPrompts:\n${shareData.prompts.join('\n')}`
|
||||
navigator.clipboard.writeText(shareText)
|
||||
}
|
||||
}
|
||||
|
||||
const commonStyles = [
|
||||
"realistic", "anime", "cartoon", "fantasy",
|
||||
"cyberpunk", "artistic", "painterly", "photorealistic"
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Create New Series */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Plus className="h-5 w-5" />
|
||||
Create New Series
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Configure your image series with up to 30 images
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">
|
||||
Series Title
|
||||
</label>
|
||||
<Input
|
||||
placeholder="Enter series title..."
|
||||
value={newSeriesTitle}
|
||||
onChange={(e) => setNewSeriesTitle(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">
|
||||
Image Count
|
||||
</label>
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
max="30"
|
||||
value={newSeriesCount}
|
||||
onChange={(e) => setNewSeriesCount(parseInt(e.target.value))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">
|
||||
Description
|
||||
</label>
|
||||
<Input
|
||||
placeholder="Describe your series concept..."
|
||||
value={newSeriesDescription}
|
||||
onChange={(e) => setNewSeriesDescription(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">
|
||||
Art Style
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{commonStyles.map(s => (
|
||||
<button
|
||||
key={s}
|
||||
className={`px-3 py-1 rounded-full text-sm transition-colors ${
|
||||
newSeriesStyle === s
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "bg-muted hover:bg-muted/80"
|
||||
}`}
|
||||
onClick={() => setNewSeriesStyle(s)}
|
||||
>
|
||||
{s}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={createNewSeries}
|
||||
className="btn-primary"
|
||||
disabled={isLoading || !newSeriesTitle || !newSeriesDescription}
|
||||
>
|
||||
<Sparkles className="mr-2 h-4 w-4" />
|
||||
{isLoading ? "Creating..." : "Create Series"}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Series List */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<ImageIcon className="h-5 w-5" />
|
||||
My Series
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Manage your image series projects
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{series.length === 0 ? (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<ImageIcon className="h-12 w-12 mx-auto mb-4 opacity-50" />
|
||||
<p>No series created yet</p>
|
||||
<p className="text-sm">Create your first series to get started</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid md:grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
{series.map((s) => (
|
||||
<Card
|
||||
key={s.id}
|
||||
className={`cursor-pointer transition-all hover:shadow-lg ${
|
||||
selectedSeries?.id === s.id ? 'ring-2 ring-primary' : ''
|
||||
}`}
|
||||
onClick={() => setSelectedSeries(s)}
|
||||
>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex justify-between items-start mb-3">
|
||||
<div>
|
||||
<h3 className="font-medium">{s.config.title}</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{s.config.imageCount} images • {s.config.style} style
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
deleteSeries(s.id)
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<p className="text-sm mb-3 line-clamp-2">
|
||||
{s.config.description}
|
||||
</p>
|
||||
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{s.images.length > 0
|
||||
? `${s.images.length}/${s.config.imageCount} images generated`
|
||||
: 'Not generated'
|
||||
}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-1">
|
||||
{s.images.length === 0 && (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
generateImagesForSeries(s.id)
|
||||
}}
|
||||
disabled={isGenerating}
|
||||
>
|
||||
{isGenerating ? (
|
||||
<div className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />
|
||||
) : (
|
||||
<Play className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
exportSeries(s)
|
||||
}}
|
||||
>
|
||||
<Download className="h-3 w-3" />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
shareSeries(s)
|
||||
}}
|
||||
>
|
||||
<Share className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Selected Series Details */}
|
||||
{selectedSeries && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center justify-between">
|
||||
<span>{selectedSeries.config.title}</span>
|
||||
<Button variant="outline" size="sm">
|
||||
<Settings className="h-4 w-4" />
|
||||
</Button>
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{selectedSeries.config.description}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid md:grid-cols-3 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-muted-foreground">Images:</span>
|
||||
<span className="ml-2 font-medium">
|
||||
{selectedSeries.images.length}/{selectedSeries.config.imageCount}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">Style:</span>
|
||||
<span className="ml-2 font-medium">{selectedSeries.config.style}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">Created:</span>
|
||||
<span className="ml-2 font-medium">
|
||||
{new Date(selectedSeries.createdAt).toLocaleDateString()}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Progress */}
|
||||
<div>
|
||||
<div className="flex justify-between text-sm mb-2">
|
||||
<span>Generation Progress</span>
|
||||
<span>{Math.round((selectedSeries.images.length / selectedSeries.config.imageCount) * 100)}%</span>
|
||||
</div>
|
||||
<div className="w-full bg-muted rounded-full h-2">
|
||||
<div
|
||||
className="bg-primary h-2 rounded-full transition-all duration-300"
|
||||
style={{
|
||||
width: `${(selectedSeries.images.length / selectedSeries.config.imageCount) * 100}%`
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="flex gap-2">
|
||||
{selectedSeries.images.length < selectedSeries.config.imageCount && (
|
||||
<Button
|
||||
onClick={() => generateImagesForSeries(selectedSeries.id)}
|
||||
disabled={isGenerating}
|
||||
className="btn-primary"
|
||||
>
|
||||
{isGenerating ? (
|
||||
<>
|
||||
<div className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent mr-2" />
|
||||
Generating...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Play className="mr-2 h-4 w-4" />
|
||||
Continue Generation
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Button variant="outline" onClick={() => onSeriesSelect?.(selectedSeries)}>
|
||||
View Details
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
56
Test Ideas/NanoJason/nanojason/src/components/ui/button.tsx
Normal file
56
Test Ideas/NanoJason/nanojason/src/components/ui/button.tsx
Normal 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 }
|
||||
79
Test Ideas/NanoJason/nanojason/src/components/ui/card.tsx
Normal file
79
Test Ideas/NanoJason/nanojason/src/components/ui/card.tsx
Normal 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 }
|
||||
25
Test Ideas/NanoJason/nanojason/src/components/ui/input.tsx
Normal file
25
Test Ideas/NanoJason/nanojason/src/components/ui/input.tsx
Normal 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 }
|
||||
121
Test Ideas/NanoJason/nanojason/src/hooks/use-qwen-auth.ts
Normal file
121
Test Ideas/NanoJason/nanojason/src/hooks/use-qwen-auth.ts
Normal file
@@ -0,0 +1,121 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, createContext, useContext, ReactNode } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { createAuthHeader } from '@/utils/api-utils'
|
||||
|
||||
interface QwenAuthContextType {
|
||||
isAuthenticated: boolean
|
||||
isLoading: boolean
|
||||
login: () => void
|
||||
logout: () => void
|
||||
accessToken: string | null
|
||||
error: string | null
|
||||
clearError: () => void
|
||||
}
|
||||
|
||||
const QwenAuthContext = createContext<QwenAuthContextType | undefined>(undefined)
|
||||
|
||||
interface QwenAuthProviderProps {
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
export function QwenAuthProvider({ children }: QwenAuthProviderProps) {
|
||||
const [isAuthenticated, setIsAuthenticated] = useState(false)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [accessToken, setAccessToken] = useState<string | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const router = useRouter()
|
||||
|
||||
useEffect(() => {
|
||||
checkAuthStatus()
|
||||
}, [])
|
||||
|
||||
const checkAuthStatus = async () => {
|
||||
setIsLoading(true)
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem('qwen_access_token')
|
||||
|
||||
if (token) {
|
||||
// Verify the token is still valid
|
||||
const response = await fetch('/api/auth/verify', {
|
||||
headers: {
|
||||
'Authorization': createAuthHeader(token),
|
||||
},
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
setIsAuthenticated(true)
|
||||
setAccessToken(token)
|
||||
} else {
|
||||
// Token is invalid, remove it
|
||||
localStorage.removeItem('qwen_access_token')
|
||||
setAccessToken(null)
|
||||
setIsAuthenticated(false)
|
||||
}
|
||||
} else {
|
||||
setIsAuthenticated(false)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Auth check failed:', err)
|
||||
setIsAuthenticated(false)
|
||||
setAccessToken(null)
|
||||
localStorage.removeItem('qwen_access_token')
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const login = () => {
|
||||
const clientId = process.env.NEXT_PUBLIC_QWEN_CLIENT_ID
|
||||
const redirectUri = encodeURIComponent(process.env.NEXT_PUBLIC_QWEN_REDIRECT_URI || `${window.location.origin}/auth`)
|
||||
const scope = 'image_generation chat'
|
||||
const state = Math.random().toString(36).substring(7)
|
||||
|
||||
localStorage.setItem('qwen_auth_state', state)
|
||||
|
||||
const authUrl = `https://open.bigmodel.cn/oauth2/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scope}&response_type=code&state=${state}`
|
||||
|
||||
window.location.href = authUrl
|
||||
}
|
||||
|
||||
const logout = () => {
|
||||
localStorage.removeItem('qwen_access_token')
|
||||
localStorage.removeItem('qwen_auth_state')
|
||||
setIsAuthenticated(false)
|
||||
setAccessToken(null)
|
||||
setError(null)
|
||||
router.push('/')
|
||||
}
|
||||
|
||||
const clearError = () => {
|
||||
setError(null)
|
||||
}
|
||||
|
||||
const value: QwenAuthContextType = {
|
||||
isAuthenticated,
|
||||
isLoading,
|
||||
login,
|
||||
logout,
|
||||
accessToken,
|
||||
error,
|
||||
clearError,
|
||||
}
|
||||
|
||||
return (
|
||||
<QwenAuthContext.Provider value={value}>
|
||||
{children}
|
||||
</QwenAuthContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useQwenAuth() {
|
||||
const context = useContext(QwenAuthContext)
|
||||
|
||||
if (context === undefined) {
|
||||
throw new Error('useQwenAuth must be used within a QwenAuthProvider')
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
14
Test Ideas/NanoJason/nanojason/src/lib/qwen-api.ts
Normal file
14
Test Ideas/NanoJason/nanojason/src/lib/qwen-api.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
// Export the new Qwen API client
|
||||
export { QwenAPIClient, QWEN_MODELS, QWEN_LIMITS } from '../services/qwen-api-client'
|
||||
|
||||
// Legacy compatibility exports
|
||||
export type { QwenAuthConfig, QwenTokenResponse, QwenChatRequest, QwenChatResponse, QwenImageRequest, QwenImageResponse } from '../services/qwen-api-client'
|
||||
|
||||
// Create default instance
|
||||
export const qwenAPI = new QwenAPIClient({
|
||||
clientId: process.env.NEXT_PUBLIC_QWEN_CLIENT_ID || 'demo_client_id',
|
||||
clientSecret: process.env.QWEN_CLIENT_SECRET || 'demo_client_secret',
|
||||
redirectUri: process.env.NEXT_PUBLIC_QWEN_REDIRECT_URI || 'http://localhost:3000/auth',
|
||||
})
|
||||
|
||||
export default QwenAPIClient
|
||||
6
Test Ideas/NanoJason/nanojason/src/lib/utils.ts
Normal file
6
Test Ideas/NanoJason/nanojason/src/lib/utils.ts
Normal 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))
|
||||
}
|
||||
529
Test Ideas/NanoJason/nanojason/src/services/jason-processor.ts
Normal file
529
Test Ideas/NanoJason/nanojason/src/services/jason-processor.ts
Normal file
@@ -0,0 +1,529 @@
|
||||
export interface JasonPrompt {
|
||||
prompt: string
|
||||
style: string
|
||||
characters?: string[]
|
||||
mood?: string
|
||||
consistency?: {
|
||||
characterFeatures?: Record<string, any>
|
||||
itemFeatures?: Record<string, any>
|
||||
colorPalette?: string[]
|
||||
style?: string
|
||||
}
|
||||
metadata?: {
|
||||
version?: string
|
||||
timestamp?: string
|
||||
engine?: string
|
||||
seriesId?: string
|
||||
imageIndex?: number
|
||||
}
|
||||
}
|
||||
|
||||
export interface CharacterConsistency {
|
||||
name: string
|
||||
description: string
|
||||
features: {
|
||||
hair: string
|
||||
eyes: string
|
||||
clothing: string
|
||||
accessories: string[]
|
||||
expression: string
|
||||
pose?: string
|
||||
colorPalette?: string[]
|
||||
}
|
||||
consistency: {
|
||||
mustMaintain: string[]
|
||||
canVary: string[]
|
||||
priority: 'high' | 'medium' | 'low'
|
||||
}
|
||||
}
|
||||
|
||||
export interface ItemConsistency {
|
||||
name: string
|
||||
description: string
|
||||
features: {
|
||||
color: string
|
||||
material: string
|
||||
size: string
|
||||
position?: string
|
||||
lighting?: string
|
||||
}
|
||||
consistency: {
|
||||
mustMaintain: string[]
|
||||
canVary: string[]
|
||||
priority: 'high' | 'medium' | 'low'
|
||||
}
|
||||
}
|
||||
|
||||
export interface SeriesConsistency {
|
||||
characters: CharacterConsistency[]
|
||||
items: ItemConsistency[]
|
||||
colorPalette: string[]
|
||||
style: string
|
||||
mood: string
|
||||
narrativeProgression: {
|
||||
start: string
|
||||
middle: string
|
||||
end: string
|
||||
}
|
||||
}
|
||||
|
||||
export class JasonProcessor {
|
||||
private jasonPatterns = {
|
||||
basic: /^{[\s\S]*}$/,
|
||||
prompt: /"prompt"\s*:\s*"([^"]+)"/,
|
||||
style: /"style"\s*:\s*"([^"]+)"/,
|
||||
characters: /"characters"\s*:\s*(\[.*?\])/,
|
||||
mood: /"mood"\s*:\s*"([^"]+)"/,
|
||||
consistency: /"consistency"\s*:\s*{[\s\S]*?}/,
|
||||
}
|
||||
|
||||
parseJasonPrompt(jasonString: string): JasonPrompt | null {
|
||||
try {
|
||||
// Clean the input
|
||||
const cleaned = jasonString.trim()
|
||||
|
||||
if (!cleaned.startsWith('{') || !cleaned.endsWith('}')) {
|
||||
throw new Error('Invalid Jason format: must be a JSON object')
|
||||
}
|
||||
|
||||
// Parse JSON
|
||||
const parsed = JSON.parse(cleaned)
|
||||
|
||||
// Validate required fields
|
||||
if (!parsed.prompt || typeof parsed.prompt !== 'string') {
|
||||
throw new Error('Invalid Jason format: prompt is required')
|
||||
}
|
||||
|
||||
return {
|
||||
prompt: parsed.prompt,
|
||||
style: parsed.style || 'realistic',
|
||||
characters: parsed.characters || [],
|
||||
mood: parsed.mood || 'neutral',
|
||||
consistency: parsed.consistency || {},
|
||||
metadata: parsed.metadata || {},
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Failed to parse Jason prompt:', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
generateJasonFromPrompt(
|
||||
prompt: string,
|
||||
options: {
|
||||
style?: string
|
||||
characters?: string[]
|
||||
mood?: string
|
||||
consistency?: Partial<JasonPrompt['consistency']>
|
||||
metadata?: Partial<JasonPrompt['metadata']>
|
||||
} = {}
|
||||
): string {
|
||||
const {
|
||||
style = 'realistic',
|
||||
characters = [],
|
||||
mood = 'neutral',
|
||||
consistency = {},
|
||||
metadata = {},
|
||||
} = options
|
||||
|
||||
const jasonPrompt: JasonPrompt = {
|
||||
prompt,
|
||||
style,
|
||||
characters,
|
||||
mood,
|
||||
consistency: {
|
||||
characterFeatures: {
|
||||
style,
|
||||
mood,
|
||||
...consistency.characterFeatures,
|
||||
},
|
||||
itemFeatures: {
|
||||
style,
|
||||
quality: 'high',
|
||||
...consistency.itemFeatures,
|
||||
},
|
||||
...consistency,
|
||||
},
|
||||
metadata: {
|
||||
version: '1.0',
|
||||
timestamp: new Date().toISOString(),
|
||||
engine: 'nanojason',
|
||||
...metadata,
|
||||
},
|
||||
}
|
||||
|
||||
return JSON.stringify(jasonPrompt, null, 2)
|
||||
}
|
||||
|
||||
extractConsistencyProfiles(
|
||||
prompts: JasonPrompt[]
|
||||
): SeriesConsistency {
|
||||
const characters: CharacterConsistency[] = []
|
||||
const items: ItemConsistency[] = []
|
||||
const colorPalette = new Set<string>()
|
||||
const styleSet = new Set<string>()
|
||||
const moodSet = new Set<string>()
|
||||
|
||||
prompts.forEach((prompt, index) => {
|
||||
// Extract style
|
||||
if (prompt.style) {
|
||||
styleSet.add(prompt.style)
|
||||
}
|
||||
|
||||
// Extract mood
|
||||
if (prompt.mood) {
|
||||
moodSet.add(prompt.mood)
|
||||
}
|
||||
|
||||
// Extract color palette from consistency
|
||||
if (prompt.consistency?.colorPalette) {
|
||||
prompt.consistency.colorPalette.forEach(color => colorPalette.add(color))
|
||||
}
|
||||
|
||||
// Extract characters
|
||||
if (prompt.characters) {
|
||||
prompt.characters.forEach(characterName => {
|
||||
const existingCharacter = characters.find(c => c.name === characterName)
|
||||
|
||||
if (!existingCharacter) {
|
||||
characters.push({
|
||||
name: characterName,
|
||||
description: `Character from prompt ${index + 1}`,
|
||||
features: this.extractCharacterFeatures(prompt),
|
||||
consistency: {
|
||||
mustMaintain: ['name', 'style'],
|
||||
canVary: ['pose', 'expression', 'position'],
|
||||
priority: 'high',
|
||||
},
|
||||
})
|
||||
} else {
|
||||
// Merge features for existing character
|
||||
existingCharacter.features = this.mergeCharacterFeatures(
|
||||
existingCharacter.features,
|
||||
this.extractCharacterFeatures(prompt)
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Extract items from prompt
|
||||
const itemsInPrompt = this.extractItemsFromPrompt(prompt.prompt)
|
||||
itemsInPrompt.forEach(itemName => {
|
||||
const existingItem = items.find(i => i.name === itemName)
|
||||
|
||||
if (!existingItem) {
|
||||
items.push({
|
||||
name: itemName,
|
||||
description: `Item from prompt ${index + 1}`,
|
||||
features: this.extractItemFeatures(prompt, itemName),
|
||||
consistency: {
|
||||
mustMaintain: ['name', 'style'],
|
||||
canVary: ['position', 'lighting', 'size'],
|
||||
priority: 'medium',
|
||||
},
|
||||
})
|
||||
} else {
|
||||
// Merge features for existing item
|
||||
existingItem.features = this.mergeItemFeatures(
|
||||
existingItem.features,
|
||||
this.extractItemFeatures(prompt, itemName)
|
||||
)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
return {
|
||||
characters,
|
||||
items,
|
||||
colorPalette: Array.from(colorPalette),
|
||||
style: Array.from(styleSet)[0] || 'realistic',
|
||||
mood: Array.from(moodSet)[0] || 'neutral',
|
||||
narrativeProgression: this.extractNarrativeProgression(prompts),
|
||||
}
|
||||
}
|
||||
|
||||
private extractCharacterFeatures(prompt: JasonPrompt): CharacterConsistency['features'] {
|
||||
// Simple feature extraction - in production, this would use NLP
|
||||
const features: CharacterConsistency['features'] = {
|
||||
hair: 'unknown',
|
||||
eyes: 'unknown',
|
||||
clothing: 'unknown',
|
||||
accessories: [],
|
||||
expression: 'neutral',
|
||||
}
|
||||
|
||||
// Extract from prompt text
|
||||
const promptText = prompt.prompt.toLowerCase()
|
||||
|
||||
if (promptText.includes('long hair')) features.hair = 'long'
|
||||
if (promptText.includes('short hair')) features.hair = 'short'
|
||||
if (promptText.includes('blue eyes')) features.eyes = 'blue'
|
||||
if (promptText.includes('brown eyes')) features.eyes = 'brown'
|
||||
if (promptText.includes('green eyes')) features.eyes = 'green'
|
||||
|
||||
if (promptText.includes('wearing')) {
|
||||
const clothingMatch = promptText.match(/wearing\s+([a-z\s]+)/)
|
||||
if (clothingMatch) {
|
||||
features.clothing = clothingMatch[1]
|
||||
}
|
||||
}
|
||||
|
||||
if (promptText.includes('smiling')) features.expression = 'smiling'
|
||||
if (promptText.includes('sad')) features.expression = 'sad'
|
||||
if (promptText.includes('angry')) features.expression = 'angry'
|
||||
|
||||
return features
|
||||
}
|
||||
|
||||
private extractItemFeatures(prompt: JasonPrompt, itemName: string): ItemConsistency['features'] {
|
||||
const features: ItemConsistency['features'] = {
|
||||
color: 'unknown',
|
||||
material: 'unknown',
|
||||
size: 'unknown',
|
||||
}
|
||||
|
||||
const promptText = prompt.prompt.toLowerCase()
|
||||
|
||||
// Extract color
|
||||
const colorPatterns = ['red', 'blue', 'green', 'yellow', 'black', 'white', 'gold', 'silver']
|
||||
const foundColor = colorPatterns.find(color => promptText.includes(color))
|
||||
if (foundColor) {
|
||||
features.color = foundColor
|
||||
}
|
||||
|
||||
// Extract material
|
||||
const materialPatterns = ['wooden', 'metal', 'crystal', 'glass', 'stone', 'fabric']
|
||||
const foundMaterial = materialPatterns.find(material => promptText.includes(material))
|
||||
if (foundMaterial) {
|
||||
features.material = foundMaterial
|
||||
}
|
||||
|
||||
// Extract size
|
||||
if (promptText.includes('large')) features.size = 'large'
|
||||
if (promptText.includes('small')) features.size = 'small'
|
||||
if (promptText.includes('tiny')) features.size = 'tiny'
|
||||
|
||||
return features
|
||||
}
|
||||
|
||||
private mergeCharacterFeatures(
|
||||
existing: CharacterConsistency['features'],
|
||||
newFeatures: CharacterConsistency['features']
|
||||
): CharacterConsistency['features'] {
|
||||
return {
|
||||
hair: newFeatures.hair !== 'unknown' ? newFeatures.hair : existing.hair,
|
||||
eyes: newFeatures.eyes !== 'unknown' ? newFeatures.eyes : existing.eyes,
|
||||
clothing: newFeatures.clothing !== 'unknown' ? newFeatures.clothing : existing.clothing,
|
||||
accessories: [...existing.accessories, ...newFeatures.accessories],
|
||||
expression: newFeatures.expression !== 'neutral' ? newFeatures.expression : existing.expression,
|
||||
colorPalette: existing.colorPalette || newFeatures.colorPalette,
|
||||
}
|
||||
}
|
||||
|
||||
private mergeItemFeatures(
|
||||
existing: ItemConsistency['features'],
|
||||
newFeatures: ItemConsistency['features']
|
||||
): ItemConsistency['features'] {
|
||||
return {
|
||||
color: newFeatures.color !== 'unknown' ? newFeatures.color : existing.color,
|
||||
material: newFeatures.material !== 'unknown' ? newFeatures.material : existing.material,
|
||||
size: newFeatures.size !== 'unknown' ? newFeatures.size : existing.size,
|
||||
position: newFeatures.position || existing.position,
|
||||
lighting: newFeatures.lighting || existing.lighting,
|
||||
}
|
||||
}
|
||||
|
||||
private extractItemsFromPrompt(promptText: string): string[] {
|
||||
const items: string[] = []
|
||||
|
||||
// Common item patterns
|
||||
const itemPatterns = [
|
||||
/\b(sword|knife|blade)\b/gi,
|
||||
/\b(staff|wand|rod)\b/gi,
|
||||
/\b(book|scroll|tome)\b/gi,
|
||||
/\b(crown|tiara|diadem)\b/gi,
|
||||
/\b(crystal|gem|stone)\b/gi,
|
||||
/\b(key|lock|chest)\b/gi,
|
||||
/\b(map|compass|treasure)\b/gi,
|
||||
/\b(armor|shield|helmet)\b/gi,
|
||||
/\b(flower|plant|tree)\b/gi,
|
||||
/\b(building|house|castle)\b/gi,
|
||||
]
|
||||
|
||||
itemPatterns.forEach(pattern => {
|
||||
const matches = promptText.match(pattern)
|
||||
if (matches) {
|
||||
matches.forEach(match => {
|
||||
const cleanMatch = match.toLowerCase()
|
||||
if (!items.includes(cleanMatch)) {
|
||||
items.push(cleanMatch)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
return items
|
||||
}
|
||||
|
||||
private extractNarrativeProgression(prompts: JasonPrompt[]): SeriesConsistency['narrativeProgression'] {
|
||||
const total = prompts.length
|
||||
|
||||
return {
|
||||
start: prompts[0]?.prompt || 'Beginning of story',
|
||||
middle: prompts[Math.floor(total / 2)]?.prompt || 'Middle of story',
|
||||
end: prompts[total - 1]?.prompt || 'End of story',
|
||||
}
|
||||
}
|
||||
|
||||
generateConsistencyEnhancedPrompt(
|
||||
originalPrompt: string,
|
||||
consistencyProfile: SeriesConsistency,
|
||||
imageIndex: number,
|
||||
totalImages: number
|
||||
): JasonPrompt {
|
||||
// Apply consistency rules to enhance the prompt
|
||||
let enhancedPrompt = originalPrompt
|
||||
|
||||
// Add character consistency
|
||||
if (consistencyProfile.characters.length > 0) {
|
||||
const characterDescriptions = consistencyProfile.characters.map(char =>
|
||||
`${char.name} with ${char.features.hair} hair and ${char.features.eyes} eyes`
|
||||
).join(', ')
|
||||
|
||||
enhancedPrompt += ` featuring ${characterDescriptions}`
|
||||
}
|
||||
|
||||
// Add item consistency
|
||||
if (consistencyProfile.items.length > 0) {
|
||||
const itemDescriptions = consistencyProfile.items.map(item =>
|
||||
`${item.name} made of ${item.features.material}`
|
||||
).join(', ')
|
||||
|
||||
enhancedPrompt += ` with ${itemDescriptions}`
|
||||
}
|
||||
|
||||
// Add style and mood consistency
|
||||
enhancedPrompt += ` in ${consistencyProfile.style} style with ${consistencyProfile.mood} atmosphere`
|
||||
|
||||
// Add color palette if available
|
||||
if (consistencyProfile.colorPalette.length > 0) {
|
||||
enhancedPrompt += `, color palette: ${consistencyProfile.colorPalette.join(', ')}`
|
||||
}
|
||||
|
||||
return {
|
||||
prompt: enhancedPrompt,
|
||||
style: consistencyProfile.style,
|
||||
characters: consistencyProfile.characters.map(c => c.name),
|
||||
mood: consistencyProfile.mood,
|
||||
consistency: {
|
||||
characterFeatures: {
|
||||
style: consistencyProfile.style,
|
||||
mood: consistencyProfile.mood,
|
||||
},
|
||||
itemFeatures: {
|
||||
style: consistencyProfile.style,
|
||||
},
|
||||
colorPalette: consistencyProfile.colorPalette,
|
||||
},
|
||||
metadata: {
|
||||
version: '1.0',
|
||||
timestamp: new Date().toISOString(),
|
||||
engine: 'nanojason-enhanced',
|
||||
seriesId: 'consistency-enhanced',
|
||||
imageIndex,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
validateJasonPrompt(jasonString: string): {
|
||||
valid: boolean
|
||||
errors: string[]
|
||||
warnings: string[]
|
||||
} {
|
||||
const errors: string[] = []
|
||||
const warnings: string[] = []
|
||||
|
||||
try {
|
||||
const prompt = this.parseJasonPrompt(jasonString)
|
||||
|
||||
if (!prompt) {
|
||||
errors.push('Invalid JSON format')
|
||||
return { valid: false, errors, warnings }
|
||||
}
|
||||
|
||||
// Validate required fields
|
||||
if (!prompt.prompt) {
|
||||
errors.push('Prompt field is required')
|
||||
}
|
||||
|
||||
// Validate style
|
||||
const validStyles = ['realistic', 'anime', 'cartoon', 'fantasy', 'cyberpunk', 'artistic']
|
||||
if (prompt.style && !validStyles.includes(prompt.style)) {
|
||||
warnings.push(`Style "${prompt.style}" is not standard. Recommended: ${validStyles.join(', ')}`)
|
||||
}
|
||||
|
||||
// Validate mood
|
||||
const validMoods = ['happy', 'sad', 'angry', 'peaceful', 'mysterious', 'epic', 'wonderful', 'neutral']
|
||||
if (prompt.mood && !validMoods.includes(prompt.mood)) {
|
||||
warnings.push(`Mood "${prompt.mood}" is not standard. Recommended: ${validMoods.join(', ')}`)
|
||||
}
|
||||
|
||||
// Check for consistency if multiple prompts
|
||||
if (Array.isArray(prompt.characters) && prompt.characters.length > 3) {
|
||||
warnings.push('More than 3 characters may reduce consistency across images')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
errors.push(`Validation error: ${error instanceof Error ? error.message : 'Unknown error'}`)
|
||||
}
|
||||
|
||||
return {
|
||||
valid: errors.length === 0,
|
||||
errors,
|
||||
warnings,
|
||||
}
|
||||
}
|
||||
|
||||
optimizeForService(jasonPrompt: JasonPrompt, targetService: 'nanojason' | 'nanobanana' | 'openai' | 'midjourney'): JasonPrompt {
|
||||
const optimized = { ...jasonPrompt }
|
||||
|
||||
// Service-specific optimizations
|
||||
switch (targetService) {
|
||||
case 'nanobanana':
|
||||
// NanoBanana-specific optimizations
|
||||
optimized.consistency = {
|
||||
...optimized.consistency,
|
||||
characterFeatures: {
|
||||
...optimized.consistency?.characterFeatures,
|
||||
style: 'consistent',
|
||||
quality: 'high',
|
||||
},
|
||||
}
|
||||
break
|
||||
|
||||
case 'openai':
|
||||
// OpenAI DALL-E specific optimizations
|
||||
if (optimized.characters && optimized.characters.length > 1) {
|
||||
optimized.prompt += `, consistent character design across all images`
|
||||
}
|
||||
break
|
||||
|
||||
case 'midjourney':
|
||||
// Midjourney specific optimizations
|
||||
optimized.consistency = {
|
||||
...optimized.consistency,
|
||||
colorPalette: optimized.consistency?.colorPalette || ['vibrant', 'saturated'],
|
||||
}
|
||||
break
|
||||
|
||||
default:
|
||||
// NanoJason optimizations
|
||||
break
|
||||
}
|
||||
|
||||
return optimized
|
||||
}
|
||||
}
|
||||
|
||||
export const jasonProcessor = new JasonProcessor()
|
||||
262
Test Ideas/NanoJason/nanojason/src/services/jason-translator.ts
Normal file
262
Test Ideas/NanoJason/nanojason/src/services/jason-translator.ts
Normal 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
Test Ideas/NanoJason/nanojason/src/services/nano-coder.ts
Normal file
315
Test Ideas/NanoJason/nanojason/src/services/nano-coder.ts
Normal 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, codeContext)
|
||||
|
||||
// Step 6: Calculate accuracy score
|
||||
const accuracyScore = this.calculateTechnicalAccuracy(technical_specifications)
|
||||
|
||||
// Step 7: Generate performance tips
|
||||
const performanceTips = this.generateTechnicalTips(technical_specifications, domain)
|
||||
|
||||
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
Test Ideas/NanoJason/nanojason/src/services/nano-prompt.ts
Normal file
374
Test Ideas/NanoJason/nanojason/src/services/nano-prompt.ts
Normal 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()
|
||||
@@ -0,0 +1,161 @@
|
||||
// Debug version of Ollama Client to isolate fetch issues
|
||||
|
||||
export class OllamaClientDebug {
|
||||
private apiKey: string | null = null
|
||||
private baseURL: string
|
||||
|
||||
constructor(apiKey?: string) {
|
||||
console.log('🔍 Debug: Initializing OllamaClient with key:', apiKey ? 'provided' : 'none')
|
||||
this.apiKey = apiKey || process.env.OLLAMA_API_KEY || null
|
||||
this.baseURL = 'https://ollama.com'
|
||||
|
||||
if (this.apiKey) {
|
||||
console.log('✅ Debug: API key initialized, length:', this.apiKey.length)
|
||||
console.log('🔍 Debug: API key chars:', this.apiKey.split('').map(c => c.charCodeAt(0)))
|
||||
}
|
||||
}
|
||||
|
||||
isAvailable(): boolean {
|
||||
console.log('🔍 Debug: Checking availability, key exists:', !!this.apiKey)
|
||||
return !!this.apiKey
|
||||
}
|
||||
|
||||
// Get API key info
|
||||
getApiKeyInfo(): { isSet: boolean; source: string } {
|
||||
if (this.apiKey) {
|
||||
return {
|
||||
isSet: true,
|
||||
source: 'constructor'
|
||||
}
|
||||
}
|
||||
|
||||
// Check localStorage
|
||||
const storedKey = typeof window !== 'undefined' ? localStorage.getItem('ollama_api_key') : null
|
||||
if (storedKey) {
|
||||
return {
|
||||
isSet: true,
|
||||
source: 'localStorage'
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isSet: false,
|
||||
source: 'none'
|
||||
}
|
||||
}
|
||||
|
||||
async listModels() {
|
||||
console.log('🔍 Debug: Attempting to list models...')
|
||||
|
||||
if (!this.isAvailable()) {
|
||||
console.error('❌ Debug: API key not available')
|
||||
throw new Error('Ollama API key not available')
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('🔍 Debug: Making request to:', `${this.baseURL}/api/tags`)
|
||||
|
||||
// Create headers object first
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
// Add Authorization header if key exists
|
||||
if (this.apiKey) {
|
||||
headers['Authorization'] = `Bearer ${this.apiKey?.replace(/[^\x20-\x7E]/g, '').trim() || ''}`
|
||||
console.log('✅ Debug: Authorization header set, length:', headers['Authorization'].length)
|
||||
}
|
||||
|
||||
console.log('🔍 Debug: Headers object:', headers)
|
||||
|
||||
const response = await fetch(`${this.baseURL}/api/tags`, {
|
||||
method: 'GET',
|
||||
headers: headers,
|
||||
})
|
||||
|
||||
console.log('🔍 Debug: Response status:', response.status)
|
||||
console.log('🔍 Debug: Response ok:', response.ok)
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('❌ Debug: Failed to list models:', response.statusText, response.status)
|
||||
throw new Error(`Failed to list models: ${response.statusText}`)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
console.log('✅ Debug: Models retrieved:', data.models?.length || 0)
|
||||
return data.models
|
||||
} catch (error) {
|
||||
console.error('❌ Debug: Error in listModels:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async chat(request: { model?: string; messages: any[]; stream?: boolean; options?: any }) {
|
||||
console.log('🔍 Debug: Starting chat with model:', request.model || 'default')
|
||||
|
||||
if (!this.isAvailable()) {
|
||||
console.error('❌ Debug: API key not available for chat')
|
||||
throw new Error('Ollama API key not available')
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('🔍 Debug: Making chat request to:', `${this.baseURL}/api/chat`)
|
||||
|
||||
// Create headers object first
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
// Add Authorization header if key exists
|
||||
if (this.apiKey) {
|
||||
headers['Authorization'] = `Bearer ${this.apiKey?.replace(/[^\x20-\x7E]/g, '').trim() || ''}`
|
||||
console.log('✅ Debug: Chat Authorization header set')
|
||||
}
|
||||
|
||||
console.log('🔍 Debug: Chat headers:', headers)
|
||||
|
||||
const response = await fetch(`${this.baseURL}/api/chat`, {
|
||||
method: 'POST',
|
||||
headers: headers,
|
||||
body: JSON.stringify({
|
||||
model: request.model || 'gpt-oss:120b-cloud',
|
||||
messages: request.messages,
|
||||
stream: false,
|
||||
options: {
|
||||
temperature: 0.7,
|
||||
top_p: 0.9,
|
||||
max_tokens: 1500,
|
||||
...request.options,
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
console.log('🔍 Debug: Chat response status:', response.status)
|
||||
console.log('🔍 Debug: Chat response ok:', response.ok)
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('❌ Debug: Chat failed:', response.statusText)
|
||||
throw new Error(`Ollama chat failed: ${response.statusText}`)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
console.log('✅ Debug: Chat response received')
|
||||
return data.message?.content || 'No content received'
|
||||
} catch (error) {
|
||||
console.error('❌ Debug: Error in chat:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const ollamaClientDebug = new OllamaClientDebug()
|
||||
|
||||
// Available cloud models
|
||||
export const OLLAMA_CLOUD_MODELS = {
|
||||
'gpt-oss:120b-cloud': 'GPT-OSS 120B Cloud',
|
||||
'llama3.1:70b': 'Llama 3.1 70B',
|
||||
'llama3.1:8b': 'Llama 3.1 8B',
|
||||
'mixtral:8x7b': 'Mixtral 8x7B',
|
||||
'codellama:70b': 'CodeLlama 70B',
|
||||
'qwen2.5:72b': 'Qwen2.5 72B',
|
||||
}
|
||||
351
Test Ideas/NanoJason/nanojason/src/services/ollama-client.ts
Normal file
351
Test Ideas/NanoJason/nanojason/src/services/ollama-client.ts
Normal file
@@ -0,0 +1,351 @@
|
||||
// Ollama Cloud API Client - For AI-powered story generation
|
||||
// https://docs.ollama.com/cloud
|
||||
import { sanitizeApiKey } from '@/utils/api-utils'
|
||||
|
||||
export interface OllamaChatRequest {
|
||||
model: string
|
||||
messages: Array<{
|
||||
role: 'system' | 'user' | 'assistant'
|
||||
content: string
|
||||
}>
|
||||
stream?: boolean
|
||||
options?: {
|
||||
temperature?: number
|
||||
top_p?: number
|
||||
max_tokens?: number
|
||||
}
|
||||
}
|
||||
|
||||
export interface OllamaChatResponse {
|
||||
model: string
|
||||
created_at: string
|
||||
message: {
|
||||
role: string
|
||||
content: string
|
||||
}
|
||||
done: boolean
|
||||
total_duration?: number
|
||||
load_duration?: number
|
||||
prompt_eval_count?: number
|
||||
prompt_eval_duration?: number
|
||||
eval_count?: number
|
||||
eval_duration?: number
|
||||
}
|
||||
|
||||
export interface OllamaModel {
|
||||
name: string
|
||||
size: string
|
||||
digest: string
|
||||
modified_at: string
|
||||
}
|
||||
|
||||
export interface OllamaListResponse {
|
||||
models: OllamaModel[]
|
||||
}
|
||||
|
||||
export class OllamaClient {
|
||||
private apiKey: string | null = null
|
||||
private baseURL: string
|
||||
private defaultModel = 'gpt-oss:120b-cloud' // Free cloud model
|
||||
|
||||
constructor(apiKey?: string) {
|
||||
this.apiKey = sanitizeApiKey(apiKey) || process.env.OLLAMA_API_KEY || null
|
||||
this.baseURL = 'https://ollama.com'
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Check if API key is available
|
||||
isAvailable(): boolean {
|
||||
return !!this.apiKey
|
||||
}
|
||||
|
||||
// List available models
|
||||
async listModels(): Promise<OllamaModel[]> {
|
||||
if (!this.isAvailable()) {
|
||||
throw new Error('Ollama API key not available')
|
||||
}
|
||||
|
||||
const response = await fetch(`${this.baseURL}/api/tags`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${this.apiKey || ''}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to list models: ${response.statusText}`)
|
||||
}
|
||||
|
||||
const data: OllamaListResponse = await response.json()
|
||||
return data.models
|
||||
}
|
||||
|
||||
// Generate chat completion
|
||||
async chat(request: OllamaChatRequest): Promise<string> {
|
||||
if (!this.isAvailable()) {
|
||||
throw new Error('Ollama API key not available')
|
||||
}
|
||||
|
||||
const response = await fetch(`${this.baseURL}/api/chat`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${this.apiKey || ''}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: request.model || this.defaultModel,
|
||||
messages: request.messages,
|
||||
stream: false, // We'll handle streaming later
|
||||
options: {
|
||||
temperature: request.options?.temperature || 0.7,
|
||||
top_p: request.options?.top_p || 0.9,
|
||||
max_tokens: request.options?.max_tokens || 1500,
|
||||
...request.options,
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Ollama chat failed: ${response.statusText}`)
|
||||
}
|
||||
|
||||
if (request.stream) {
|
||||
// Handle streaming response
|
||||
return this.handleStreamResponse(response)
|
||||
} else {
|
||||
// Handle non-streaming response
|
||||
const data: OllamaChatResponse = await response.json()
|
||||
return data.message.content
|
||||
}
|
||||
}
|
||||
|
||||
// Generate story series with narrative progression
|
||||
async generateStorySeries(
|
||||
basePrompt: string,
|
||||
options: {
|
||||
imageCount?: number
|
||||
style?: string
|
||||
mood?: string
|
||||
includeCharacters?: boolean
|
||||
includeItems?: boolean
|
||||
} = {}
|
||||
): Promise<{
|
||||
title: string
|
||||
description: string
|
||||
prompts: string[]
|
||||
narrativeProgression: string[]
|
||||
characters: string[]
|
||||
items: string[]
|
||||
style: string
|
||||
mood: string
|
||||
}> {
|
||||
const imageCount = Math.min(options.imageCount || 5, 30) // Max 30 images
|
||||
|
||||
const systemPrompt = `Generate ${imageCount} creative and diverse series ideas for visual storytelling based on the user's interest: "${basePrompt}"
|
||||
|
||||
Each idea should be:
|
||||
1. Engaging and visually rich
|
||||
2. Suitable for image series (5-30 images)
|
||||
3. Different genres and styles
|
||||
4. Have strong narrative potential
|
||||
5. Appeal to creators and storytellers
|
||||
|
||||
Return as a JSON array of strings:
|
||||
["Idea 1 title and brief description", "Idea 2 title and brief description", ...]
|
||||
|
||||
Focus on variety: fantasy, sci-fi, slice of life, adventure, mystery, etc.`
|
||||
|
||||
try {
|
||||
const response = await this.chat({
|
||||
model: this.defaultModel,
|
||||
messages: [
|
||||
{
|
||||
role: 'system',
|
||||
content: systemPrompt
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: `Generate ${imageCount} series ideas about ${basePrompt}`
|
||||
}
|
||||
],
|
||||
options: {
|
||||
temperature: 0.8, // Higher creativity for stories
|
||||
max_tokens: 2000,
|
||||
},
|
||||
})
|
||||
|
||||
// Parse JSON response
|
||||
const storyData = JSON.parse(response)
|
||||
|
||||
return {
|
||||
title: storyData.title || 'Untitled Story',
|
||||
description: storyData.description || basePrompt,
|
||||
prompts: Array.isArray(storyData.prompts) ? storyData.prompts : [basePrompt],
|
||||
narrativeProgression: Array.isArray(storyData.narrativeProgression) ? storyData.narrativeProgression : ['Beginning', 'Middle', 'End'],
|
||||
characters: Array.isArray(storyData.characters) ? storyData.characters : [],
|
||||
items: Array.isArray(storyData.items) ? storyData.items : [],
|
||||
style: storyData.style || options.style || 'fantasy',
|
||||
mood: storyData.mood || options.mood || 'wonderful',
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to generate story with Ollama:', error)
|
||||
|
||||
// Fallback to basic structure if AI fails
|
||||
return this.generateFallbackStory(basePrompt, options, imageCount)
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback story generation without AI
|
||||
private generateFallbackStory(basePrompt: string, options: any, imageCount: number) {
|
||||
const stages = this.generateBasicProgression(imageCount)
|
||||
|
||||
return {
|
||||
title: `${options.style || 'Fantasy'} Adventure`,
|
||||
description: basePrompt,
|
||||
prompts: stages.map((stage, index) =>
|
||||
`${basePrompt} - ${stage} (Scene ${index + 1} of ${imageCount})`
|
||||
),
|
||||
narrativeProgression: stages,
|
||||
characters: options.includeCharacters !== false ? ['hero', 'guide', 'mystical being'] : [],
|
||||
items: options.includeItems !== false ? ['magical artifact', 'ancient map', 'enchanted weapon'] : [],
|
||||
style: options.style || 'fantasy',
|
||||
mood: options.mood || 'wonderful',
|
||||
}
|
||||
}
|
||||
|
||||
private generateBasicProgression(imageCount: number): string[] {
|
||||
if (imageCount <= 3) {
|
||||
return [
|
||||
'Introduction and setting the scene',
|
||||
'Discovery and rising action',
|
||||
'Climax and resolution'
|
||||
]
|
||||
} else if (imageCount <= 5) {
|
||||
return [
|
||||
'Introduction',
|
||||
'Rising action',
|
||||
'Midpoint',
|
||||
'Climax',
|
||||
'Resolution and aftermath'
|
||||
]
|
||||
} else if (imageCount <= 8) {
|
||||
return [
|
||||
'Introduction',
|
||||
'Setup',
|
||||
'Rising action 1',
|
||||
'Rising action 2',
|
||||
'Midpoint',
|
||||
'Climax',
|
||||
'Falling action',
|
||||
'Conclusion'
|
||||
]
|
||||
} else {
|
||||
// For longer series, generate more detailed progression
|
||||
const stages = ['Introduction', 'Setup']
|
||||
for (let i = 2; i <= imageCount; i++) {
|
||||
stages.push(`Development ${i-1}`)
|
||||
}
|
||||
return stages.slice(0, imageCount)
|
||||
}
|
||||
}
|
||||
|
||||
// Handle streaming response
|
||||
private async handleStreamResponse(response: Response): Promise<string> {
|
||||
const reader = response.body?.getReader()
|
||||
if (!reader) {
|
||||
throw new Error('Streaming not supported')
|
||||
}
|
||||
|
||||
const decoder = new TextDecoder()
|
||||
let fullContent = ''
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
|
||||
const chunk = decoder.decode(value, { stream: true })
|
||||
const lines = chunk.split('\n').filter(line => line.trim())
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('data: ')) {
|
||||
try {
|
||||
const data = JSON.parse(line.slice(6))
|
||||
if (data.message?.content) {
|
||||
fullContent += data.message.content
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore malformed JSON chunks
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock()
|
||||
}
|
||||
|
||||
return fullContent
|
||||
}
|
||||
|
||||
// Get API key info
|
||||
getApiKeyInfo(): { isSet: boolean; source: string } {
|
||||
if (this.apiKey) {
|
||||
return {
|
||||
isSet: true,
|
||||
source: 'constructor'
|
||||
}
|
||||
}
|
||||
|
||||
// Check localStorage
|
||||
const storedKey = typeof window !== 'undefined' ? localStorage.getItem('ollama_api_key') : null
|
||||
if (storedKey) {
|
||||
return {
|
||||
isSet: true,
|
||||
source: 'localStorage'
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isSet: false,
|
||||
source: 'none'
|
||||
}
|
||||
}
|
||||
|
||||
// Set API key with sanitization
|
||||
setApiKey(apiKey: string, persist: boolean = false): void {
|
||||
const sanitizedKey = sanitizeApiKey(apiKey)
|
||||
if (!sanitizedKey) {
|
||||
console.error('Invalid API key format')
|
||||
return
|
||||
}
|
||||
|
||||
this.apiKey = sanitizedKey
|
||||
|
||||
if (persist && typeof window !== 'undefined') {
|
||||
localStorage.setItem('ollama_api_key', sanitizedKey)
|
||||
}
|
||||
}
|
||||
|
||||
// Clear API key
|
||||
clearApiKey(): void {
|
||||
this.apiKey = null
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.removeItem('ollama_api_key')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create default instance
|
||||
export const ollamaClient = new OllamaClient()
|
||||
|
||||
// Available cloud models
|
||||
export const OLLAMA_CLOUD_MODELS = {
|
||||
'gpt-oss:120b-cloud': 'GPT-4 Turbo (120B) - Good balance of speed and quality',
|
||||
'gpt-oss:137b-cloud': 'GPT-4 Large (137B) - Higher quality, slower',
|
||||
'gpt-oss:78b-cloud': 'GPT-3.5 Turbo (78B) - Fastest responses',
|
||||
'gpt-oss:34b-cloud': 'GPT-3.5 (34B) - Most economical',
|
||||
'llama3:70b-cloud': 'Llama 3 (70B) - Open source alternative',
|
||||
'llama3:8b-cloud': 'Llama 3 (8B) - Fast and efficient',
|
||||
} as const
|
||||
368
Test Ideas/NanoJason/nanojason/src/services/qwen-api-client.ts
Normal file
368
Test Ideas/NanoJason/nanojason/src/services/qwen-api-client.ts
Normal file
@@ -0,0 +1,368 @@
|
||||
// Qwen API Client - Based on Qwen Code implementation
|
||||
import { createAuthHeader } from '@/utils/api-utils'
|
||||
// Provides 2,000 free daily requests with 60 requests/minute rate limit
|
||||
|
||||
export interface QwenAuthConfig {
|
||||
clientId: string
|
||||
clientSecret: string
|
||||
redirectUri: string
|
||||
}
|
||||
|
||||
export interface QwenTokenResponse {
|
||||
access_token: string
|
||||
refresh_token: string
|
||||
expires_in: number
|
||||
token_type: string
|
||||
scope: string
|
||||
}
|
||||
|
||||
export interface QwenChatRequest {
|
||||
model: string
|
||||
messages: Array<{
|
||||
role: 'system' | 'user' | 'assistant'
|
||||
content: string
|
||||
}>
|
||||
max_tokens?: number
|
||||
temperature?: number
|
||||
top_p?: number
|
||||
}
|
||||
|
||||
export interface QwenChatResponse {
|
||||
id: string
|
||||
object: string
|
||||
created: number
|
||||
model: string
|
||||
choices: Array<{
|
||||
index: number
|
||||
message: {
|
||||
role: string
|
||||
content: string
|
||||
}
|
||||
finish_reason: string
|
||||
}>
|
||||
usage: {
|
||||
prompt_tokens: number
|
||||
completion_tokens: number
|
||||
total_tokens: number
|
||||
}
|
||||
}
|
||||
|
||||
export interface QwenImageRequest {
|
||||
model: string
|
||||
prompt: string
|
||||
n?: number
|
||||
size?: string
|
||||
quality?: string
|
||||
style?: string
|
||||
}
|
||||
|
||||
export interface QwenImageResponse {
|
||||
created: number
|
||||
data: Array<{
|
||||
url: string
|
||||
revised_prompt?: string
|
||||
}>
|
||||
}
|
||||
|
||||
export class QwenAPIClient {
|
||||
private accessToken: string | null = null
|
||||
private refreshToken: string | null = null
|
||||
private tokenExpiry: number = 0
|
||||
private baseURL = 'https://dashscope.aliyuncs.com/api/v1'
|
||||
|
||||
constructor(private config: QwenAuthConfig) {}
|
||||
|
||||
// OAuth Flow
|
||||
async authenticate(): Promise<string> {
|
||||
// Generate PKCE parameters for security
|
||||
const codeVerifier = this.generateCodeVerifier()
|
||||
const codeChallenge = await this.generateCodeChallenge(codeVerifier)
|
||||
const state = this.generateState()
|
||||
|
||||
// Store PKCE parameters for callback verification
|
||||
sessionStorage.setItem('qwen_code_verifier', codeVerifier)
|
||||
sessionStorage.setItem('qwen_oauth_state', state)
|
||||
|
||||
// Build OAuth URL
|
||||
const params = new URLSearchParams({
|
||||
client_id: this.config.clientId,
|
||||
redirect_uri: this.config.redirectUri,
|
||||
response_type: 'code',
|
||||
scope: 'api_access',
|
||||
state: state,
|
||||
code_challenge: codeChallenge,
|
||||
code_challenge_method: 'S256'
|
||||
})
|
||||
|
||||
const oauthUrl = `https://qwen.ai/oauth/authorize?${params.toString()}`
|
||||
|
||||
// Redirect to OAuth provider
|
||||
window.location.href = oauthUrl
|
||||
|
||||
return new Promise((resolve) => {
|
||||
// This will be resolved in the callback handling
|
||||
window.addEventListener('message', (event) => {
|
||||
if (event.data.type === 'qwen_auth_success') {
|
||||
resolve(event.data.token)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Exchange authorization code for access token
|
||||
async exchangeCodeForToken(code: string, codeVerifier: string): Promise<QwenTokenResponse> {
|
||||
const response = await fetch(`${this.baseURL}/oauth/token`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Accept': 'application/json',
|
||||
},
|
||||
body: new URLSearchParams({
|
||||
grant_type: 'authorization_code',
|
||||
client_id: this.config.clientId,
|
||||
client_secret: this.config.clientSecret,
|
||||
code: code,
|
||||
code_verifier: codeVerifier,
|
||||
redirect_uri: this.config.redirectUri,
|
||||
}),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Token exchange failed: ${response.statusText}`)
|
||||
}
|
||||
|
||||
const tokenData: QwenTokenResponse = await response.json()
|
||||
|
||||
// Store token information
|
||||
this.accessToken = tokenData.access_token
|
||||
this.refreshToken = tokenData.refresh_token
|
||||
this.tokenExpiry = Date.now() + (tokenData.expires_in * 1000)
|
||||
|
||||
// Store in localStorage for persistence
|
||||
localStorage.setItem('qwen_access_token', tokenData.access_token)
|
||||
localStorage.setItem('qwen_refresh_token', tokenData.refresh_token)
|
||||
localStorage.setItem('qwen_token_expiry', this.tokenExpiry.toString())
|
||||
|
||||
return tokenData
|
||||
}
|
||||
|
||||
// Refresh access token
|
||||
async refreshAccessToken(): Promise<QwenTokenResponse> {
|
||||
if (!this.refreshToken) {
|
||||
throw new Error('No refresh token available')
|
||||
}
|
||||
|
||||
const response = await fetch(`${this.baseURL}/oauth/token`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Accept': 'application/json',
|
||||
},
|
||||
body: new URLSearchParams({
|
||||
grant_type: 'refresh_token',
|
||||
client_id: this.config.clientId,
|
||||
client_secret: this.config.clientSecret,
|
||||
refresh_token: this.refreshToken,
|
||||
}),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Token refresh failed: ${response.statusText}`)
|
||||
}
|
||||
|
||||
const tokenData: QwenTokenResponse = await response.json()
|
||||
|
||||
// Update stored token information
|
||||
this.accessToken = tokenData.access_token
|
||||
this.refreshToken = tokenData.refresh_token
|
||||
this.tokenExpiry = Date.now() + (tokenData.expires_in * 1000)
|
||||
|
||||
localStorage.setItem('qwen_access_token', tokenData.access_token)
|
||||
localStorage.setItem('qwen_refresh_token', tokenData.refresh_token)
|
||||
localStorage.setItem('qwen_token_expiry', this.tokenExpiry.toString())
|
||||
|
||||
return tokenData
|
||||
}
|
||||
|
||||
// Get valid access token
|
||||
async getAccessToken(): Promise<string> {
|
||||
// Check if token exists and is not expired
|
||||
if (!this.accessToken || Date.now() >= this.tokenExpiry) {
|
||||
// Try to refresh token
|
||||
await this.refreshAccessToken()
|
||||
}
|
||||
|
||||
if (!this.accessToken) {
|
||||
throw new Error('Unable to obtain access token')
|
||||
}
|
||||
|
||||
return this.accessToken
|
||||
}
|
||||
|
||||
// Chat completion API
|
||||
async chatCompletion(request: QwenChatRequest): Promise<QwenChatResponse> {
|
||||
const token = await this.getAccessToken()
|
||||
|
||||
const response = await fetch(`${this.baseURL}/services/aigc/text-generation/generation`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': createAuthHeader(token),
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: request.model,
|
||||
input: {
|
||||
messages: request.messages,
|
||||
},
|
||||
parameters: {
|
||||
max_tokens: request.max_tokens || 1500,
|
||||
temperature: request.temperature || 0.7,
|
||||
top_p: request.top_p || 0.8,
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Chat completion failed: ${response.statusText}`)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
return {
|
||||
id: data.request_id,
|
||||
object: 'chat.completion',
|
||||
created: Date.now() / 1000,
|
||||
model: request.model,
|
||||
choices: data.output?.choices || [],
|
||||
usage: {
|
||||
prompt_tokens: data.usage?.input_tokens || 0,
|
||||
completion_tokens: data.usage?.output_tokens || 0,
|
||||
total_tokens: data.usage?.total_tokens || 0,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Image generation API
|
||||
async generateImages(request: QwenImageRequest): Promise<QwenImageResponse> {
|
||||
const token = await this.getAccessToken()
|
||||
|
||||
const response = await fetch(`${this.baseURL}/services/aigc/text2image/image-synthesis`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': createAuthHeader(token),
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: request.model || 'qwen-vl-plus',
|
||||
input: {
|
||||
prompt: request.prompt,
|
||||
},
|
||||
parameters: {
|
||||
n: request.n || 1,
|
||||
size: request.size || '1024x1024',
|
||||
quality: request.quality || 'standard',
|
||||
style: request.style || 'vivid',
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Image generation failed: ${response.statusText}`)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
return {
|
||||
created: Date.now() / 1000,
|
||||
data: data.output?.results?.map((result: any) => ({
|
||||
url: result.url,
|
||||
revised_prompt: result.prompt,
|
||||
})) || [],
|
||||
}
|
||||
}
|
||||
|
||||
// Rate limit checking
|
||||
async checkRateLimit(): Promise<{ remaining: number; resetTime: number }> {
|
||||
try {
|
||||
const token = await this.getAccessToken()
|
||||
|
||||
// This would normally be parsed from response headers
|
||||
// For demo, we'll simulate the 2,000 daily limit
|
||||
const dailyLimit = 2000
|
||||
const usedToday = Math.floor(Math.random() * dailyLimit)
|
||||
const remaining = dailyLimit - usedToday
|
||||
const resetTime = Math.floor(Date.now() / 1000) + (24 * 3600) // Next midnight
|
||||
|
||||
return {
|
||||
remaining,
|
||||
resetTime,
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Rate limit check failed:', error)
|
||||
return {
|
||||
remaining: 2000,
|
||||
resetTime: Math.floor(Date.now() / 1000) + (24 * 3600),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
private generateCodeVerifier(): string {
|
||||
const array = new Uint8Array(32)
|
||||
crypto.getRandomValues(array)
|
||||
return btoa(String.fromCharCode(...array))
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=/g, '')
|
||||
}
|
||||
|
||||
private async generateCodeChallenge(verifier: string): Promise<string> {
|
||||
const encoder = new TextEncoder()
|
||||
const data = encoder.encode(verifier)
|
||||
const digest = await crypto.subtle.digest('SHA-256', data)
|
||||
return btoa(String.fromCharCode(...new Uint8Array(digest)))
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=/g, '')
|
||||
}
|
||||
|
||||
private generateState(): string {
|
||||
return Math.random().toString(36).substring(2, 15)
|
||||
}
|
||||
|
||||
// Initialize from stored tokens
|
||||
initializeFromStorage(): void {
|
||||
this.accessToken = localStorage.getItem('qwen_access_token')
|
||||
this.refreshToken = localStorage.getItem('qwen_refresh_token')
|
||||
const expiry = localStorage.getItem('qwen_token_expiry')
|
||||
this.tokenExpiry = expiry ? parseInt(expiry) : 0
|
||||
}
|
||||
|
||||
// Logout
|
||||
logout(): void {
|
||||
this.accessToken = null
|
||||
this.refreshToken = null
|
||||
this.tokenExpiry = 0
|
||||
|
||||
localStorage.removeItem('qwen_access_token')
|
||||
localStorage.removeItem('qwen_refresh_token')
|
||||
localStorage.removeItem('qwen_token_expiry')
|
||||
localStorage.removeItem('qwen_authenticated')
|
||||
}
|
||||
}
|
||||
|
||||
// Default models available
|
||||
export const QWEN_MODELS = {
|
||||
TEXT: 'qwen-turbo',
|
||||
CHAT: 'qwen-plus',
|
||||
VISION: 'qwen-vl-plus',
|
||||
IMAGE: 'qwen-vl-plus',
|
||||
} as const
|
||||
|
||||
// Rate limits
|
||||
export const QWEN_LIMITS = {
|
||||
FREE_DAILY: 2000,
|
||||
FREE_MINUTE: 60,
|
||||
PRO_DAILY: 50000,
|
||||
PRO_MINUTE: 500,
|
||||
} as const
|
||||
357
Test Ideas/NanoJason/nanojason/src/services/series-generator.ts
Normal file
357
Test Ideas/NanoJason/nanojason/src/services/series-generator.ts
Normal file
@@ -0,0 +1,357 @@
|
||||
import { ollamaClient } from './ollama-client'
|
||||
import { jasonProcessor } from './jason-processor'
|
||||
|
||||
export interface SeriesConfig {
|
||||
id: string
|
||||
title: string
|
||||
description: string
|
||||
imageCount: number
|
||||
style: string
|
||||
prompts: string[]
|
||||
}
|
||||
|
||||
export interface GeneratedSeries {
|
||||
id: string
|
||||
config: SeriesConfig
|
||||
images: GeneratedImage[]
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface GeneratedImage {
|
||||
id: string
|
||||
title: string
|
||||
prompt: string
|
||||
jasonPrompt?: string
|
||||
thumbnail?: string
|
||||
seriesId: string
|
||||
characterConsistency?: any
|
||||
itemConsistency?: any
|
||||
}
|
||||
|
||||
export interface CharacterProfile {
|
||||
name: string
|
||||
description: string
|
||||
features: {
|
||||
appearance: string
|
||||
personality: string
|
||||
backstory: string
|
||||
}
|
||||
importance: 'main' | 'supporting' | 'background'
|
||||
}
|
||||
|
||||
export interface ItemProfile {
|
||||
name: string
|
||||
description: string
|
||||
features: {
|
||||
appearance: string
|
||||
purpose: string
|
||||
origin: string
|
||||
}
|
||||
importance: 'critical' | 'important' | 'background'
|
||||
}
|
||||
|
||||
export class SeriesGenerator {
|
||||
private storage: Storage
|
||||
|
||||
constructor() {
|
||||
this.storage = typeof window !== 'undefined' ? localStorage : new Map()
|
||||
}
|
||||
|
||||
// Generate series using AI (Ollama Cloud)
|
||||
async createSeries(
|
||||
basePrompt: string,
|
||||
config: SeriesConfig,
|
||||
characters?: CharacterProfile[],
|
||||
items?: ItemProfile[]
|
||||
): Promise<GeneratedSeries> {
|
||||
try {
|
||||
console.log('Generating series with Ollama Cloud...')
|
||||
|
||||
// Use Ollama for AI-powered story generation
|
||||
const storyData = await ollamaClient.generateStorySeries(basePrompt, {
|
||||
imageCount: config.imageCount,
|
||||
style: config.style,
|
||||
mood: 'wonderful', // Default mood
|
||||
includeCharacters: characters && characters.length > 0,
|
||||
includeItems: items && items.length > 0,
|
||||
})
|
||||
|
||||
// Generate Jason prompts for each scene
|
||||
const jasonPrompts = storyData.prompts.map((prompt, index) =>
|
||||
jasonProcessor.generateConsistencyEnhancedPrompt(
|
||||
prompt,
|
||||
{
|
||||
characters: characters?.map(c => c.name) || [],
|
||||
items: items?.map(i => i.name) || [],
|
||||
colorPalette: ['blue', 'purple', 'gold'], // Story-appropriate colors
|
||||
style: config.style,
|
||||
mood: storyData.mood,
|
||||
},
|
||||
index + 1,
|
||||
storyData.prompts.length
|
||||
)
|
||||
)
|
||||
|
||||
// Create generated images with Jason prompts
|
||||
const images: GeneratedImage[] = jasonPrompts.map((jasonPrompt, index) => ({
|
||||
id: `${config.id}_${index}`,
|
||||
title: `${storyData.title} - Scene ${index + 1}`,
|
||||
prompt: storyData.prompts[index],
|
||||
jasonPrompt: JSON.stringify(jasonPrompt, null, 2),
|
||||
seriesId: config.id,
|
||||
}))
|
||||
|
||||
const series: GeneratedSeries = {
|
||||
id: config.id,
|
||||
config: {
|
||||
...config,
|
||||
prompts: storyData.prompts,
|
||||
},
|
||||
images,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
|
||||
// Store series
|
||||
this.saveSeries(series)
|
||||
|
||||
console.log(`Generated series: ${series.config.title} with ${images.length} scenes`)
|
||||
return series
|
||||
|
||||
} catch (error) {
|
||||
console.error('Failed to create series:', error)
|
||||
|
||||
// Fallback to offline generation
|
||||
return this.createOfflineSeries(basePrompt, config, characters, items)
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback offline series generation
|
||||
private createOfflineSeries(
|
||||
basePrompt: string,
|
||||
config: SeriesConfig,
|
||||
characters?: CharacterProfile[],
|
||||
items?: ItemProfile[]
|
||||
): GeneratedSeries {
|
||||
console.log('Using offline series generation (fallback mode)')
|
||||
|
||||
// Basic progression without AI
|
||||
const progression = this.generateBasicProgression(config.imageCount)
|
||||
const images: GeneratedImage[] = progression.map((stage, index) => ({
|
||||
id: `${config.id}_${index}`,
|
||||
title: `${config.title} - ${stage}`,
|
||||
prompt: `${basePrompt} - ${stage}`,
|
||||
jasonPrompt: JSON.stringify({
|
||||
prompt: `${basePrompt} - ${stage}`,
|
||||
style: config.style,
|
||||
characters: characters?.map(c => c.name) || [],
|
||||
mood: 'neutral',
|
||||
}, null, 2),
|
||||
seriesId: config.id,
|
||||
}))
|
||||
|
||||
const series: GeneratedSeries = {
|
||||
id: config.id,
|
||||
config,
|
||||
images,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
|
||||
this.saveSeries(series)
|
||||
return series
|
||||
}
|
||||
|
||||
private generateBasicProgression(imageCount: number): string[] {
|
||||
if (imageCount <= 3) {
|
||||
return ['Introduction', 'Development', 'Conclusion']
|
||||
} else if (imageCount <= 5) {
|
||||
return ['Introduction', 'Rising Action', 'Climax', 'Falling Action', 'Conclusion']
|
||||
} else if (imageCount <= 8) {
|
||||
return [
|
||||
'Introduction', 'Setup', 'Rising Action 1', 'Rising Action 2',
|
||||
'Midpoint', 'Climax', 'Falling Action', 'Conclusion'
|
||||
]
|
||||
} else {
|
||||
// For longer series
|
||||
const stages = ['Introduction', 'Setup']
|
||||
for (let i = 2; i <= imageCount; i++) {
|
||||
stages.push(`Development ${i-1}`)
|
||||
}
|
||||
return stages.slice(0, imageCount)
|
||||
}
|
||||
}
|
||||
|
||||
// Generate series ideas using AI
|
||||
async generateSeriesIdeas(userInterest: string, count: number = 5): Promise<string[]> {
|
||||
try {
|
||||
if (!ollamaClient.isAvailable()) {
|
||||
console.log('Ollama not available, generating offline ideas')
|
||||
return this.generateOfflineIdeas(userInterest, count)
|
||||
}
|
||||
|
||||
const systemPrompt = `Generate ${count} creative and diverse series ideas for visual storytelling based on the user's interest: "${userInterest}"
|
||||
|
||||
Each idea should be:
|
||||
1. Engaging and visually rich
|
||||
2. Suitable for image series (5-30 images)
|
||||
3. Different genres and styles
|
||||
4. Have strong narrative potential
|
||||
5. Appeal to creators and storytellers
|
||||
|
||||
Return as a JSON array of strings:
|
||||
["Idea 1 title and brief description", "Idea 2 title and brief description", ...]
|
||||
|
||||
Focus on variety: fantasy, sci-fi, slice of life, adventure, mystery, etc.`
|
||||
|
||||
const response = await ollamaClient.chat({
|
||||
model: 'gpt-oss:78b-cloud', // Use faster model for ideas
|
||||
messages: [
|
||||
{
|
||||
role: 'system',
|
||||
content: systemPrompt
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: `Generate ${count} series ideas about ${userInterest}`
|
||||
}
|
||||
],
|
||||
options: {
|
||||
temperature: 0.9, // High creativity for ideas
|
||||
max_tokens: 1000,
|
||||
},
|
||||
})
|
||||
|
||||
// Parse response
|
||||
const ideasMatch = response.match(/\[[\s\S]*?\]/)
|
||||
if (ideasMatch) {
|
||||
try {
|
||||
return JSON.parse(ideasMatch[0])
|
||||
} catch (e) {
|
||||
console.error('Failed to parse ideas:', e)
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to offline if parsing fails
|
||||
return this.generateOfflineIdeas(userInterest, count)
|
||||
|
||||
} catch (error) {
|
||||
console.error('Failed to generate ideas:', error)
|
||||
return this.generateOfflineIdeas(userInterest, count)
|
||||
}
|
||||
}
|
||||
|
||||
// Offline idea generation
|
||||
private generateOfflineIdeas(userInterest: string, count: number): string[] {
|
||||
const templates = [
|
||||
`Epic ${userInterest} Adventure Series`,
|
||||
`Mysterious ${userInterest} Mystery`,
|
||||
`Coming-of-Age ${userInterest} Story`,
|
||||
`Action-Packed ${userInterest} Saga`,
|
||||
`Heartwarming ${userInterest} Journey`,
|
||||
]
|
||||
|
||||
return templates.slice(0, count)
|
||||
}
|
||||
|
||||
// Storage methods
|
||||
private saveSeries(series: GeneratedSeries): void {
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.setItem(`series_${series.id}`, JSON.stringify(series))
|
||||
}
|
||||
}
|
||||
|
||||
getSeries(seriesId: string): GeneratedSeries | null {
|
||||
if (typeof window === 'undefined') return null
|
||||
|
||||
try {
|
||||
const stored = localStorage.getItem(`series_${seriesId}`)
|
||||
return stored ? JSON.parse(stored) : null
|
||||
} catch (error) {
|
||||
console.error('Failed to load series:', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
getAllSeries(): GeneratedSeries[] {
|
||||
if (typeof window === 'undefined') return []
|
||||
|
||||
const series: GeneratedSeries[] = []
|
||||
for (let i = 0; i < localStorage.length; i++) {
|
||||
const key = localStorage.key(i)
|
||||
if (key && key.startsWith('series_')) {
|
||||
try {
|
||||
const seriesData = JSON.parse(localStorage.getItem(key)!)
|
||||
series.push(seriesData)
|
||||
} catch (error) {
|
||||
console.error('Failed to parse series:', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
return series
|
||||
}
|
||||
|
||||
deleteSeries(seriesId: string): boolean {
|
||||
if (typeof window === 'undefined') return false
|
||||
|
||||
try {
|
||||
localStorage.removeItem(`series_${seriesId}`)
|
||||
return true
|
||||
} catch (error) {
|
||||
console.error('Failed to delete series:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
updateSeries(seriesId: string, updates: Partial<GeneratedSeries>): boolean {
|
||||
if (typeof window === 'undefined') return false
|
||||
|
||||
try {
|
||||
const existing = this.getSeries(seriesId)
|
||||
if (!existing) return false
|
||||
|
||||
const updated = { ...existing, ...updates, updatedAt: new Date().toISOString() }
|
||||
localStorage.setItem(`series_${seriesId}`, JSON.stringify(updated))
|
||||
return true
|
||||
} catch (error) {
|
||||
console.error('Failed to update series:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Check Ollama availability
|
||||
async checkOllamaStatus(): Promise<{
|
||||
available: boolean
|
||||
modelsAvailable: string[]
|
||||
apiKeySet: boolean
|
||||
error?: string
|
||||
}> {
|
||||
try {
|
||||
if (!ollamaClient.isAvailable()) {
|
||||
return {
|
||||
available: false,
|
||||
modelsAvailable: [],
|
||||
apiKeySet: false,
|
||||
error: 'Ollama API key not set. Get your free key at https://ollama.com'
|
||||
}
|
||||
}
|
||||
|
||||
const models = await ollamaClient.listModels()
|
||||
return {
|
||||
available: true,
|
||||
modelsAvailable: models.map(m => m.name),
|
||||
apiKeySet: true,
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
available: false,
|
||||
modelsAvailable: [],
|
||||
apiKeySet: ollamaClient.isAvailable(),
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const seriesGenerator = new SeriesGenerator()
|
||||
37
Test Ideas/NanoJason/nanojason/src/utils/api-utils.ts
Normal file
37
Test Ideas/NanoJason/nanojason/src/utils/api-utils.ts
Normal 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}`
|
||||
}
|
||||
65
Test Ideas/NanoJason/nanojason/tailwind.config.ts
Normal file
65
Test Ideas/NanoJason/nanojason/tailwind.config.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import type { Config } from "tailwindcss";
|
||||
|
||||
const config: Config = {
|
||||
content: [
|
||||
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
|
||||
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
|
||||
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
|
||||
],
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
background: "var(--background)",
|
||||
foreground: "var(--foreground)",
|
||||
primary: {
|
||||
50: "#f0f9ff",
|
||||
100: "#e0f2fe",
|
||||
200: "#7dd3fc",
|
||||
300: "#38bdf8",
|
||||
400: "#0ea5e9",
|
||||
500: "#0284c7",
|
||||
600: "#0369a1",
|
||||
700: "#075985",
|
||||
800: "#0c4a6e",
|
||||
900: "#082f49",
|
||||
},
|
||||
accent: {
|
||||
50: "#fdf4ff",
|
||||
100: "#fae8ff",
|
||||
200: "#f5d0fe",
|
||||
300: "#f0abfc",
|
||||
400: "#e879f9",
|
||||
500: "#d946ef",
|
||||
600: "#c026d3",
|
||||
700: "#a21caf",
|
||||
800: "#86198f",
|
||||
900: "#701a75",
|
||||
},
|
||||
},
|
||||
fontFamily: {
|
||||
sans: ["Inter", "system-ui", "sans-serif"],
|
||||
},
|
||||
animation: {
|
||||
"fade-in": "fadeIn 0.5s ease-in-out",
|
||||
"slide-up": "slideUp 0.3s ease-out",
|
||||
"float": "float 3s ease-in-out infinite",
|
||||
},
|
||||
keyframes: {
|
||||
fadeIn: {
|
||||
"0%": { opacity: "0" },
|
||||
"100%": { opacity: "1" },
|
||||
},
|
||||
slideUp: {
|
||||
"0%": { transform: "translateY(10px)", opacity: "0" },
|
||||
"100%": { transform: "translateY(0)", opacity: "1" },
|
||||
},
|
||||
float: {
|
||||
"0%, 100%": { transform: "translateY(0px)" },
|
||||
"50%": { transform: "translateY(-10px)" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [],
|
||||
};
|
||||
export default config;
|
||||
34
Test Ideas/NanoJason/nanojason/tsconfig.json
Normal file
34
Test Ideas/NanoJason/nanojason/tsconfig.json
Normal file
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"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": "react-jsx",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next/dev/types/**/*.ts",
|
||||
"**/*.mts"
|
||||
],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
Reference in New Issue
Block a user