This commit is contained in:
Flatlogic Bot 2026-02-01 13:13:26 +00:00
parent aa2adea48c
commit e566dec66f
5 changed files with 399 additions and 155 deletions

View File

@ -0,0 +1,19 @@
'use strict';
module.exports = {
up: async (queryInterface, Sequelize) => {
const now = new Date();
return queryInterface.bulkInsert('secrets', [{
id: '00000000-0000-0000-0000-000000000001',
key_name: 'OPENAPI_API_KEY',
value: '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',
is_active: true,
createdAt: now,
updatedAt: now,
}], {});
},
down: async (queryInterface, Sequelize) => {
return queryInterface.bulkDelete('secrets', { key_name: 'OPENAPI_API_KEY' }, {});
}
};

View File

@ -17,6 +17,11 @@ const {
router.use(checkCrudPermissions('image_generations'));
router.post('/generate', wrapAsync(async (req, res) => {
const result = await Image_generationsService.generate(req.body, req.currentUser);
res.status(200).send(result);
}));
/**
* @swagger

View File

@ -6,12 +6,108 @@ const csv = require('csv-parser');
const axios = require('axios');
const config = require('../config');
const stream = require('stream');
const SecretsDBApi = require('../db/api/secrets');
const fs = require('fs');
const path = require('path');
const ensureDirectoryExistence = (filePath) => {
const dirname = path.dirname(filePath);
if (fs.existsSync(dirname)) {
return true;
}
ensureDirectoryExistence(dirname);
fs.mkdirSync(dirname);
}
module.exports = class Image_generationsService {
static async generate(payload, currentUser) {
const { prompt, style = 'normal', num_images = 2 } = payload;
// 1. Fetch API Key
const secret = await SecretsDBApi.findBy({ key_name: 'OPENAPI_API_KEY' });
if (!secret || !secret.value) {
throw new Error('OPENAPI_API_KEY not found in Secrets');
}
const apiKey = secret.value;
// 2. Call OpenAI
const response = await axios.post('https://api.openai.com/v1/images/generations', {
prompt: `${prompt} in ${style} style`,
n: num_images,
size: '1024x1024',
model: 'dall-e-2'
}, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
const urls = response.data.data.map(img => img.url);
// 3. Save to DB
const transaction = await db.sequelize.transaction();
try {
const generation = await db.image_generations.create({
title: prompt,
status: 'completed',
generated_at: new Date(),
finished_at: new Date(),
requesterId: currentUser.id,
createdById: currentUser.id,
updatedById: currentUser.id,
}, { transaction });
const imageRecords = [];
const savedUrls = [];
for (const url of urls) {
const image = await db.images.create({
filename: `generated-${Date.now()}.png`,
format: 'png',
generationId: generation.id,
createdById: currentUser.id,
updatedById: currentUser.id,
}, { transaction });
const imgResponse = await axios.get(url, { responseType: 'arraybuffer' });
const fileName = `generated-${Date.now()}-${Math.random().toString(36).substring(7)}.png`;
const relativePath = path.join('generations', fileName);
const filePath = path.join(config.uploadDir, relativePath);
ensureDirectoryExistence(filePath);
fs.writeFileSync(filePath, imgResponse.data);
await db.file.create({
belongsTo: 'images',
belongsToColumn: 'file',
belongsToId: image.id,
name: fileName,
sizeInBytes: imgResponse.data.length,
privateUrl: relativePath,
createdById: currentUser.id,
updatedById: currentUser.id,
}, { transaction });
imageRecords.push(image);
savedUrls.push(`/api/file/download?privateUrl=${encodeURIComponent(relativePath)}`);
}
await db.generation_histories.create({
timestamp: new Date(),
action: 'generation_completed',
details: JSON.stringify(savedUrls),
generationId: generation.id,
createdById: currentUser.id,
updatedById: currentUser.id,
}, { transaction });
await transaction.commit();
return { generation, images: imageRecords, urls: savedUrls };
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
@ -131,8 +227,4 @@ module.exports = class Image_generationsService {
throw error;
}
}
};
};

View File

@ -5,162 +5,252 @@ import Head from 'next/head';
import Link from 'next/link';
import BaseButton from '../components/BaseButton';
import CardBox from '../components/CardBox';
import SectionFullScreen from '../components/SectionFullScreen';
import LayoutGuest from '../layouts/Guest';
import BaseDivider from '../components/BaseDivider';
import BaseButtons from '../components/BaseButtons';
import { getPageTitle } from '../config';
import { useAppSelector } from '../stores/hooks';
import CardBoxComponentTitle from "../components/CardBoxComponentTitle";
import { getPexelsImage, getPexelsVideo } from '../helpers/pexels';
import { useAppDispatch, useAppSelector } from '../stores/hooks';
import { generate, resetGeneratedImages, fetch } from '../stores/image_generations/image_generationsSlice';
import { mdiAutoFix, mdiDownload, mdiDelete, mdiHistory, mdiPlus, mdiClockOutline } from '@mdi/js';
import BaseIcon from '../components/BaseIcon';
import FormField from '../components/FormField';
import LoadingSpinner from '../components/LoadingSpinner';
export default function AIImageGenerator() {
const dispatch = useAppDispatch();
const { generatedImages, isGenerating, image_generations, refetch } = useAppSelector((state) => state.image_generations);
const { currentUser } = useAppSelector((state) => state.auth);
const [prompt, setPrompt] = useState('');
const [style, setStyle] = useState('normal');
const [numImages, setNumImages] = useState(2);
const [file, setFile] = useState<File | null>(null);
export default function Starter() {
const [illustrationImage, setIllustrationImage] = useState({
src: undefined,
photographer: undefined,
photographer_url: undefined,
})
const [illustrationVideo, setIllustrationVideo] = useState({video_files: []})
const [contentType, setContentType] = useState('image');
const [contentPosition, setContentPosition] = useState('left');
const textColor = useAppSelector((state) => state.style.linkColor);
const title = 'App Draft'
// Fetch Pexels image/video
useEffect(() => {
async function fetchData() {
const image = await getPexelsImage();
const video = await getPexelsVideo();
setIllustrationImage(image);
setIllustrationVideo(video);
}
fetchData();
}, []);
dispatch(fetch({ query: '?limit=5' }));
}, [dispatch, refetch]);
const imageBlock = (image) => (
<div
className='hidden md:flex flex-col justify-end relative flex-grow-0 flex-shrink-0 w-1/3'
style={{
backgroundImage: `${
image
? `url(${image?.src?.original})`
: 'linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5))'
}`,
backgroundSize: 'cover',
backgroundPosition: 'left center',
backgroundRepeat: 'no-repeat',
}}
>
<div className='flex justify-center w-full bg-blue-300/20'>
<a
className='text-[8px]'
href={image?.photographer_url}
target='_blank'
rel='noreferrer'
>
Photo by {image?.photographer} on Pexels
</a>
</div>
</div>
);
const videoBlock = (video) => {
if (video?.video_files?.length > 0) {
return (
<div className='hidden md:flex flex-col justify-end relative flex-grow-0 flex-shrink-0 w-1/3'>
<video
className='absolute top-0 left-0 w-full h-full object-cover'
autoPlay
loop
muted
>
<source src={video?.video_files[0]?.link} type='video/mp4'/>
Your browser does not support the video tag.
</video>
<div className='flex justify-center w-full bg-blue-300/20 z-10'>
<a
className='text-[8px]'
href={video?.user?.url}
target='_blank'
rel='noreferrer'
>
Video by {video.user.name} on Pexels
</a>
</div>
</div>)
}
const handleGenerate = () => {
if (!prompt) return;
dispatch(generate({ prompt, style, num_images: numImages }));
};
return (
<div
style={
contentPosition === 'background'
? {
backgroundImage: `${
illustrationImage
? `url(${illustrationImage.src?.original})`
: 'linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5))'
}`,
backgroundSize: 'cover',
backgroundPosition: 'left center',
backgroundRepeat: 'no-repeat',
}
: {}
}
>
<Head>
<title>{getPageTitle('Starter Page')}</title>
</Head>
const handleDownload = (url: string, format: string) => {
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `generated-image.${format}`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
<SectionFullScreen bg='violet'>
<div
className={`flex ${
contentPosition === 'right' ? 'flex-row-reverse' : 'flex-row'
} min-h-screen w-full`}
>
{contentType === 'image' && contentPosition !== 'background'
? imageBlock(illustrationImage)
: null}
{contentType === 'video' && contentPosition !== 'background'
? videoBlock(illustrationVideo)
: null}
<div className='flex items-center justify-center flex-col space-y-4 w-full lg:w-full'>
<CardBox className='w-full md:w-3/5 lg:w-2/3'>
<CardBoxComponentTitle title="Welcome to your App Draft app!"/>
<div className="space-y-3">
<p className='text-center text-gray-500'>This is a React.js/Node.js app generated by the <a className={`${textColor}`} href="https://flatlogic.com/generator">Flatlogic Web App Generator</a></p>
<p className='text-center text-gray-500'>For guides and documentation please check
your local README.md and the <a className={`${textColor}`} href="https://flatlogic.com/documentation">Flatlogic documentation</a></p>
</div>
<BaseButtons>
<BaseButton
href='/login'
label='Login'
color='info'
className='w-full'
/>
return (
<div className="min-h-screen bg-[#0a0a0c] text-white">
<Head>
<title>{getPageTitle('GPT Image 2 Generator')}</title>
</Head>
</BaseButtons>
</CardBox>
{/* Navigation / Header */}
<nav className="p-6 flex justify-between items-center border-b border-gray-800 backdrop-blur-md sticky top-0 z-50">
<div className="flex items-center space-x-2">
<div className="bg-gradient-to-br from-purple-600 to-blue-500 p-2 rounded-lg">
<BaseIcon path={mdiAutoFix} size={24} className="text-white" />
</div>
<span className="text-xl font-bold tracking-tight">GPT Image 2</span>
</div>
<div className="space-x-4">
{currentUser ? (
<BaseButton href="/dashboard" label="Dashboard" color="info" outline />
) : (
<>
<BaseButton href="/login" label="Login" color="info" transparent />
<BaseButton href="/register" label="Sign Up" color="info" />
</>
)}
</div>
</nav>
<main className="max-w-6xl mx-auto px-6 py-12">
{/* Hero Section */}
<div className="text-center mb-16">
<h1 className="text-5xl md:text-7xl font-extrabold mb-6 bg-clip-text text-transparent bg-gradient-to-r from-purple-400 to-blue-400">
AI Image Generator
</h1>
<p className="text-gray-400 text-lg md:text-xl max-w-2xl mx-auto">
Transform your words into stunning visual masterpieces with GPT Image 2 4.0.
Fast, high-quality, and unlimited creativity.
</p>
</div>
{/* Generator Section */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
{/* Input Side */}
<div className="lg:col-span-1 space-y-6">
<CardBox className="bg-[#16161a] border-gray-800">
<FormField label="Describe your image" help="Enter a detailed prompt for better results">
<textarea
className="w-full bg-[#1e1e24] border-gray-700 rounded-lg p-4 text-white focus:ring-2 focus:ring-purple-500 transition-all"
rows={5}
placeholder="A futuristic city with floating neon lights..."
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
/>
</FormField>
<FormField label="Generation Style">
<select
className="w-full bg-[#1e1e24] border-gray-700 rounded-lg p-2 text-white"
value={style}
onChange={(e) => setStyle(e.target.value)}
>
<option value="normal">Normal</option>
<option value="cinematic">Cinematic</option>
<option value="artistic">Artistic</option>
</select>
</FormField>
<FormField label="Number of Images">
<div className="flex items-center space-x-4">
<input
type="range"
min="1"
max="2"
value={numImages}
onChange={(e) => setNumImages(parseInt(e.target.value))}
className="flex-grow accent-purple-500"
/>
<span className="font-bold text-purple-400">{numImages}</span>
</div>
</FormField>
<FormField label="Reference Image (Optional)" help="Upload max 2 images. 9999MB max.">
<div className="border-2 border-dashed border-gray-700 rounded-lg p-6 text-center hover:border-purple-500 transition-colors cursor-pointer relative">
<input
type="file"
className="absolute inset-0 opacity-0 cursor-pointer"
onChange={(e) => setFile(e.target.files?.[0] || null)}
/>
{file ? (
<div className="flex items-center justify-center space-x-2">
<span className="text-purple-400">{file.name}</span>
<BaseIcon path={mdiDelete} size={18} className="text-red-500" onClick={() => setFile(null)} />
</div>
) : (
<div className="space-y-2">
<BaseIcon path={mdiPlus} size={32} className="text-gray-500 mx-auto" />
<p className="text-sm text-gray-500">Drag & drop or click to upload</p>
</div>
)}
</div>
</FormField>
<BaseButton
label={isGenerating ? 'Generating...' : 'Generate Images'}
color="info"
className="w-full py-4 text-lg font-bold bg-gradient-to-r from-purple-600 to-blue-600 border-none shadow-lg shadow-purple-900/20"
onClick={handleGenerate}
disabled={isGenerating || !prompt}
/>
</CardBox>
{/* Recent History Sidebar */}
<div className="hidden lg:block space-y-4">
<h3 className="text-lg font-bold flex items-center space-x-2">
<BaseIcon path={mdiHistory} size={20} className="text-purple-400" />
<span>Recent History</span>
</h3>
<div className="space-y-3">
{Array.isArray(image_generations) && image_generations.slice(0, 3).map((gen: any) => (
<div key={gen.id} className="p-3 bg-[#16161a] border border-gray-800 rounded-lg text-sm group cursor-pointer hover:border-purple-500 transition-colors">
<p className="text-gray-300 line-clamp-2 mb-2 group-hover:text-white transition-colors">{gen.title}</p>
<div className="flex items-center text-gray-500 text-xs">
<BaseIcon path={mdiClockOutline} size={14} className="mr-1" />
<span>{new Date(gen.createdAt).toLocaleDateString()}</span>
</div>
</div>
))}
</div>
</div>
</div>
{/* Output Side */}
<div className="lg:col-span-2 space-y-8">
{isGenerating && (
<div className="flex flex-col items-center justify-center py-20 space-y-4">
<LoadingSpinner />
<p className="text-purple-400 animate-pulse font-medium">Brewing your masterpiece...</p>
</div>
)}
{!isGenerating && generatedImages.length > 0 && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{generatedImages.map((img, idx) => (
<div key={idx} className="group relative rounded-xl overflow-hidden border border-gray-800 bg-[#16161a] transition-all hover:scale-[1.02] hover:shadow-2xl hover:shadow-purple-500/10">
<img src={img} alt={`Generated ${idx}`} className="w-full h-80 object-cover" />
<div className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex flex-col justify-end p-6 space-y-4">
<div className="flex justify-between items-center">
<span className="text-sm font-medium text-gray-300">Image {idx + 1}</span>
<div className="flex space-x-2">
<BaseButton
icon={mdiDownload}
color="white"
small
onClick={() => handleDownload(img, 'png')}
title="Download PNG"
/>
<BaseButton
icon={mdiDelete}
color="danger"
small
onClick={() => dispatch(resetGeneratedImages())}
/>
</div>
</div>
<div className="grid grid-cols-3 gap-2">
{['JPG', 'JPEG', 'GIF', 'PNG', 'APNG', 'WEBP'].map(ext => (
<button
key={ext}
onClick={() => handleDownload(img, ext.toLowerCase())}
className="text-[10px] py-1 bg-white/10 hover:bg-white/20 rounded border border-white/10 transition-colors"
>
{ext}
</button>
))}
</div>
</div>
</div>
))}
</div>
)}
{!isGenerating && generatedImages.length === 0 && (
<div className="border-2 border-dashed border-gray-800 rounded-2xl py-32 flex flex-col items-center justify-center text-gray-600">
<BaseIcon path={mdiAutoFix} size={64} className="mb-4 opacity-20" />
<p className="text-xl">Your generated images will appear here</p>
</div>
)}
</div>
</div>
</main>
{/* Footer */}
<footer className="border-t border-gray-800 py-12 mt-20 bg-[#08080a]">
<div className="max-w-6xl mx-auto px-6 flex flex-col md:flex-row justify-between items-center space-y-6 md:space-y-0">
<div className="flex items-center space-x-2">
<div className="bg-gray-800 p-1 rounded">
<BaseIcon path={mdiAutoFix} size={16} className="text-gray-400" />
</div>
<span className="text-gray-400 font-bold">GPT Image 2</span>
</div>
<div className="flex space-x-8 text-sm text-gray-500">
<Link href="/privacy-policy">Privacy Policy</Link>
<Link href="/terms-of-use">Terms of Service</Link>
<a href="https://gptimage2.ai" target="_blank" rel="noreferrer">Original Site</a>
</div>
<p className="text-gray-600 text-sm">© 2026 GPT Image 2. All rights reserved.</p>
</div>
</footer>
</div>
</div>
</SectionFullScreen>
<div className='bg-black text-white flex flex-col text-center justify-center md:flex-row'>
<p className='py-6 text-sm'>© 2026 <span>{title}</span>. All rights reserved</p>
<Link className='py-6 ml-4 text-sm' href='/privacy-policy/'>
Privacy Policy
</Link>
</div>
</div>
);
);
}
Starter.getLayout = function getLayout(page: ReactElement) {
return <LayoutGuest>{page}</LayoutGuest>;
AIImageGenerator.getLayout = function getLayout(page: ReactElement) {
return <LayoutGuest>{page}</LayoutGuest>;
};

View File

@ -8,6 +8,8 @@ interface MainState {
count: number
refetch: boolean;
rolesWidgets: any[];
generatedImages: string[];
isGenerating: boolean;
notify: {
showNotification: boolean
textNotification: string
@ -21,6 +23,8 @@ const initialState: MainState = {
count: 0,
refetch: false,
rolesWidgets: [],
generatedImages: [],
isGenerating: false,
notify: {
showNotification: false,
textNotification: '',
@ -38,6 +42,22 @@ export const fetch = createAsyncThunk('image_generations/fetch', async (data: an
return id ? result.data : {rows: result.data.rows, count: result.data.count};
})
export const generate = createAsyncThunk('image_generations/generate', async (data: any, { rejectWithValue }) => {
try {
const result = await axios.post(
'image_generations/generate',
data
)
return result.data
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
})
export const deleteItemsByIds = createAsyncThunk(
'image_generations/deleteByIds',
async (data: any, { rejectWithValue }) => {
@ -130,6 +150,9 @@ export const image_generationsSlice = createSlice({
setRefetch: (state, action: PayloadAction<boolean>) => {
state.refetch = action.payload;
},
resetGeneratedImages: (state) => {
state.generatedImages = [];
}
},
extraReducers: (builder) => {
builder.addCase(fetch.pending, (state) => {
@ -151,6 +174,21 @@ export const image_generationsSlice = createSlice({
state.loading = false
})
builder.addCase(generate.pending, (state) => {
state.isGenerating = true;
resetNotify(state);
});
builder.addCase(generate.fulfilled, (state, action) => {
state.isGenerating = false;
state.generatedImages = action.payload.urls;
state.refetch = true;
fulfilledNotify(state, 'Images generated successfully');
});
builder.addCase(generate.rejected, (state, action) => {
state.isGenerating = false;
rejectNotify(state, action);
});
builder.addCase(deleteItemsByIds.pending, (state) => {
state.loading = true;
resetNotify(state);
@ -226,6 +264,6 @@ export const image_generationsSlice = createSlice({
})
// Action creators are generated for each case reducer function
export const { setRefetch } = image_generationsSlice.actions
export const { setRefetch, resetGeneratedImages } = image_generationsSlice.actions
export default image_generationsSlice.reducer
export default image_generationsSlice.reducer