didigo commited on
Commit
7fab18f
·
verified ·
1 Parent(s): ab61245

Add files using upload-large-folder tool

Browse files
App.tsx ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState } from 'react';
2
+ import { Header } from './components/Header';
3
+ import { ImageUploader } from './components/ImageUploader';
4
+ import { OptionsPanel } from './components/OptionsPanel';
5
+ import { ResultViewer } from './components/ResultViewer';
6
+ import { generateHanfuTryOn } from './services/geminiService';
7
+ import { Dynasty, GenerationState } from './types';
8
+ import { CUSTOMIZATION_OPTIONS } from './constants';
9
+
10
+ const App: React.FC = () => {
11
+ const [selectedImage, setSelectedImage] = useState<string | null>(null);
12
+ const [selectedDynasty, setSelectedDynasty] = useState<Dynasty>(Dynasty.Tang);
13
+ const [selectedCustomizations, setSelectedCustomizations] = useState<string[]>([]);
14
+
15
+ const [generationState, setGenerationState] = useState<GenerationState>({
16
+ isLoading: false,
17
+ error: null,
18
+ resultImage: null
19
+ });
20
+
21
+ const handleCustomizationToggle = (id: string) => {
22
+ setSelectedCustomizations(prev =>
23
+ prev.includes(id) ? prev.filter(item => item !== id) : [...prev, id]
24
+ );
25
+ };
26
+
27
+ const handleGenerate = async () => {
28
+ if (!selectedImage) return;
29
+
30
+ setGenerationState({ isLoading: true, error: null, resultImage: null });
31
+
32
+ try {
33
+ // Get prompts from IDs
34
+ const customizationPrompts = selectedCustomizations
35
+ .map(id => CUSTOMIZATION_OPTIONS.find(opt => opt.id === id)?.promptAddon)
36
+ .filter((p): p is string => !!p);
37
+
38
+ const result = await generateHanfuTryOn(
39
+ selectedImage,
40
+ selectedDynasty,
41
+ customizationPrompts
42
+ );
43
+
44
+ setGenerationState({
45
+ isLoading: false,
46
+ error: null,
47
+ resultImage: result
48
+ });
49
+ } catch (error) {
50
+ setGenerationState({
51
+ isLoading: false,
52
+ error: "生成失败,请重试 (Generation failed, please try again).",
53
+ resultImage: null
54
+ });
55
+ }
56
+ };
57
+
58
+ return (
59
+ <div className="min-h-screen pb-12">
60
+ <Header />
61
+
62
+ <main className="max-w-5xl mx-auto pt-8 px-4">
63
+
64
+ {generationState.error && (
65
+ <div className="mb-6 p-4 bg-red-50 text-red-800 rounded-lg border border-red-200">
66
+ {generationState.error}
67
+ </div>
68
+ )}
69
+
70
+ <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 lg:gap-12">
71
+
72
+ {/* Left Column: Input */}
73
+ <div className="lg:col-span-5 space-y-8">
74
+ <section className="bg-white p-6 rounded-2xl shadow-sm border border-stone-100">
75
+ <h2 className="text-xl font-bold text-stone-800 mb-4">1. 上传照片 (Upload)</h2>
76
+ <ImageUploader
77
+ onImageSelect={setSelectedImage}
78
+ selectedImage={selectedImage}
79
+ />
80
+ </section>
81
+
82
+ <section className="bg-white p-6 rounded-2xl shadow-sm border border-stone-100">
83
+ <h2 className="text-xl font-bold text-stone-800 mb-6">2. 定制款式 (Customize)</h2>
84
+ <OptionsPanel
85
+ selectedDynasty={selectedDynasty}
86
+ onSelectDynasty={setSelectedDynasty}
87
+ selectedCustomizations={selectedCustomizations}
88
+ onToggleCustomization={handleCustomizationToggle}
89
+ isGenerating={generationState.isLoading}
90
+ onGenerate={handleGenerate}
91
+ hasImage={!!selectedImage}
92
+ />
93
+ </section>
94
+ </div>
95
+
96
+ {/* Right Column: Output */}
97
+ <div className="lg:col-span-7">
98
+ <section className="bg-white p-6 rounded-2xl shadow-sm border border-stone-100 h-full min-h-[500px] flex flex-col">
99
+ <h2 className="text-xl font-bold text-stone-800 mb-4">3. 试穿效果 (Result)</h2>
100
+ <div className="flex-1">
101
+ {selectedImage ? (
102
+ <ResultViewer
103
+ originalImage={selectedImage}
104
+ resultImage={generationState.resultImage}
105
+ isLoading={generationState.isLoading}
106
+ />
107
+ ) : (
108
+ <div className="h-full flex flex-col items-center justify-center text-stone-400 border-2 border-dashed border-stone-200 rounded-2xl bg-stone-50">
109
+ <p>效果图将展示在这里</p>
110
+ <p className="text-sm">(Result will appear here)</p>
111
+ </div>
112
+ )}
113
+ </div>
114
+ </section>
115
+ </div>
116
+
117
+ </div>
118
+ </main>
119
+ </div>
120
+ );
121
+ };
122
+
123
+ export default App;
README.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+ <img width="1200" height="475" alt="GHBanner" src="https://github.com/user-attachments/assets/0aa67016-6eaf-458a-adb2-6e31a0763ed6" />
3
+ </div>
4
+
5
+ # Run and deploy your AI Studio app
6
+
7
+ This contains everything you need to run your app locally.
8
+
9
+ View your app in AI Studio: https://ai.studio/apps/drive/11PqQcvbximK-gZm6C_WJvim1s8AJatXz
10
+
11
+ ## Run Locally
12
+
13
+ **Prerequisites:** Node.js
14
+
15
+
16
+ 1. Install dependencies:
17
+ `npm install`
18
+ 2. Set the `GEMINI_API_KEY` in [.env.local](.env.local) to your Gemini API key
19
+ 3. Run the app:
20
+ `npm run dev`
RTM_base_6h/20240101-12/001.zarr/channel/tess ADDED
File without changes
components/Header.tsx ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { Camera, Sparkles } from 'lucide-react';
3
+
4
+ export const Header: React.FC = () => {
5
+ return (
6
+ <header className="w-full py-6 px-4 border-b border-stone-200 bg-white/80 backdrop-blur-sm sticky top-0 z-50">
7
+ <div className="max-w-5xl mx-auto flex items-center justify-between">
8
+ <div className="flex items-center space-x-3">
9
+ <div className="p-2 bg-red-800 rounded-lg text-white">
10
+ <Sparkles size={24} />
11
+ </div>
12
+ <div>
13
+ <h1 className="text-2xl font-bold text-stone-800 tracking-wider">AI 汉服衣橱</h1>
14
+ <p className="text-xs text-stone-500">穿越千年的美丽 (Beauty through the millennium)</p>
15
+ </div>
16
+ </div>
17
+ <div className="hidden sm:block text-right text-stone-600 text-sm">
18
+ Generated by Gemini 2.5
19
+ </div>
20
+ </div>
21
+ </header>
22
+ );
23
+ };
components/ImageUploader.tsx ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useCallback } from 'react';
2
+ import { Upload } from 'lucide-react';
3
+
4
+ interface ImageUploaderProps {
5
+ onImageSelect: (base64: string) => void;
6
+ selectedImage: string | null;
7
+ }
8
+
9
+ export const ImageUploader: React.FC<ImageUploaderProps> = ({ onImageSelect, selectedImage }) => {
10
+ const handleFileChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
11
+ const file = event.target.files?.[0];
12
+ if (file) {
13
+ const reader = new FileReader();
14
+ reader.onloadend = () => {
15
+ onImageSelect(reader.result as string);
16
+ };
17
+ reader.readAsDataURL(file);
18
+ }
19
+ }, [onImageSelect]);
20
+
21
+ return (
22
+ <div className="w-full">
23
+ <label className="block w-full cursor-pointer group">
24
+ <input
25
+ type="file"
26
+ accept="image/*"
27
+ onChange={handleFileChange}
28
+ className="hidden"
29
+ />
30
+ <div className={`
31
+ relative w-full aspect-[3/4] sm:aspect-square rounded-2xl border-2 border-dashed
32
+ transition-all duration-300 overflow-hidden flex flex-col items-center justify-center
33
+ ${selectedImage ? 'border-red-800/50' : 'border-stone-300 hover:border-red-800 hover:bg-red-50'}
34
+ `}>
35
+ {selectedImage ? (
36
+ <img
37
+ src={selectedImage}
38
+ alt="Uploaded"
39
+ className="w-full h-full object-cover"
40
+ />
41
+ ) : (
42
+ <div className="text-center p-6">
43
+ <div className="w-16 h-16 mx-auto mb-4 bg-stone-100 text-stone-400 rounded-full flex items-center justify-center group-hover:bg-white group-hover:text-red-800 transition-colors">
44
+ <Upload size={32} />
45
+ </div>
46
+ <p className="text-lg font-medium text-stone-700">上传照片</p>
47
+ <p className="text-sm text-stone-500 mt-2">点击或拖拽上传全身照</p>
48
+ </div>
49
+ )}
50
+
51
+ {selectedImage && (
52
+ <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
53
+ <span className="text-white font-medium flex items-center gap-2">
54
+ <Upload size={20} /> 更换图片
55
+ </span>
56
+ </div>
57
+ )}
58
+ </div>
59
+ </label>
60
+ </div>
61
+ );
62
+ };
components/OptionsPanel.tsx ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { DYNASTY_OPTIONS, CUSTOMIZATION_OPTIONS } from '../constants';
3
+ import { Dynasty } from '../types';
4
+ import { Check } from 'lucide-react';
5
+
6
+ interface OptionsPanelProps {
7
+ selectedDynasty: Dynasty;
8
+ onSelectDynasty: (d: Dynasty) => void;
9
+ selectedCustomizations: string[];
10
+ onToggleCustomization: (id: string) => void;
11
+ isGenerating: boolean;
12
+ onGenerate: () => void;
13
+ hasImage: boolean;
14
+ }
15
+
16
+ export const OptionsPanel: React.FC<OptionsPanelProps> = ({
17
+ selectedDynasty,
18
+ onSelectDynasty,
19
+ selectedCustomizations,
20
+ onToggleCustomization,
21
+ isGenerating,
22
+ onGenerate,
23
+ hasImage
24
+ }) => {
25
+ return (
26
+ <div className="space-y-8">
27
+ {/* Dynasty Selection */}
28
+ <section>
29
+ <h3 className="text-lg font-bold text-stone-800 mb-4 flex items-center gap-2">
30
+ <span className="w-1 h-6 bg-red-800 rounded-full"></span>
31
+ 选择朝代 (Select Dynasty)
32
+ </h3>
33
+ <div className="grid grid-cols-1 gap-3">
34
+ {DYNASTY_OPTIONS.map((option) => (
35
+ <button
36
+ key={option.id}
37
+ onClick={() => onSelectDynasty(option.id)}
38
+ disabled={isGenerating}
39
+ className={`
40
+ relative p-4 rounded-xl text-left border-2 transition-all duration-200
41
+ ${selectedDynasty === option.id
42
+ ? 'border-red-800 bg-red-50'
43
+ : 'border-stone-200 hover:border-red-200 bg-white'}
44
+ `}
45
+ >
46
+ <div className="flex items-start justify-between">
47
+ <div>
48
+ <div className={`font-bold ${selectedDynasty === option.id ? 'text-red-900' : 'text-stone-700'}`}>
49
+ {option.name}
50
+ </div>
51
+ <div className="text-sm text-stone-500 mt-1">
52
+ {option.description}
53
+ </div>
54
+ </div>
55
+ {selectedDynasty === option.id && (
56
+ <div className="bg-red-800 text-white p-1 rounded-full">
57
+ <Check size={14} />
58
+ </div>
59
+ )}
60
+ </div>
61
+ </button>
62
+ ))}
63
+ </div>
64
+ </section>
65
+
66
+ {/* Customization Selection */}
67
+ <section>
68
+ <h3 className="text-lg font-bold text-stone-800 mb-4 flex items-center gap-2">
69
+ <span className="w-1 h-6 bg-red-800 rounded-full"></span>
70
+ 妆容与配饰 (Customization)
71
+ </h3>
72
+ <div className="grid grid-cols-2 gap-3">
73
+ {CUSTOMIZATION_OPTIONS.map((option) => {
74
+ const isSelected = selectedCustomizations.includes(option.id);
75
+ return (
76
+ <button
77
+ key={option.id}
78
+ onClick={() => onToggleCustomization(option.id)}
79
+ disabled={isGenerating}
80
+ className={`
81
+ p-3 rounded-lg text-sm font-medium border transition-all duration-200
82
+ ${isSelected
83
+ ? 'bg-stone-800 text-white border-stone-800'
84
+ : 'bg-white text-stone-600 border-stone-200 hover:border-stone-400'}
85
+ `}
86
+ >
87
+ {option.label}
88
+ </button>
89
+ );
90
+ })}
91
+ </div>
92
+ </section>
93
+
94
+ {/* Action Button */}
95
+ <button
96
+ onClick={onGenerate}
97
+ disabled={!hasImage || isGenerating}
98
+ className={`
99
+ w-full py-4 rounded-xl font-bold text-lg shadow-lg transform transition-all
100
+ ${!hasImage || isGenerating
101
+ ? 'bg-stone-300 text-stone-500 cursor-not-allowed'
102
+ : 'bg-red-800 text-white hover:bg-red-900 hover:-translate-y-1 hover:shadow-xl'}
103
+ `}
104
+ >
105
+ {isGenerating ? '制作中... (Generating)' : '一键换装 (Try On Hanfu)'}
106
+ </button>
107
+
108
+ {!hasImage && (
109
+ <p className="text-center text-sm text-red-500 mt-2">
110
+ 请先上传照片 (Please upload a photo first)
111
+ </p>
112
+ )}
113
+ </div>
114
+ );
115
+ };
components/ResultViewer.tsx ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { Download, Share2, RefreshCw } from 'lucide-react';
3
+
4
+ interface ResultViewerProps {
5
+ originalImage: string;
6
+ resultImage: string | null;
7
+ isLoading: boolean;
8
+ }
9
+
10
+ export const ResultViewer: React.FC<ResultViewerProps> = ({ originalImage, resultImage, isLoading }) => {
11
+ if (!resultImage && !isLoading) return null;
12
+
13
+ return (
14
+ <div className="w-full h-full flex flex-col">
15
+ <div className="relative w-full aspect-[3/4] sm:aspect-square bg-stone-100 rounded-2xl overflow-hidden shadow-inner border border-stone-200">
16
+ {isLoading ? (
17
+ <div className="absolute inset-0 flex flex-col items-center justify-center bg-white/90 z-10">
18
+ <div className="w-12 h-12 border-4 border-red-800 border-t-transparent rounded-full animate-spin mb-4"></div>
19
+ <p className="text-red-900 font-medium animate-pulse">正在量体裁衣 (Designing Hanfu)...</p>
20
+ <p className="text-stone-500 text-sm mt-2">AI is weaving the fabric of history</p>
21
+ </div>
22
+ ) : resultImage ? (
23
+ <img
24
+ src={resultImage}
25
+ alt="Generated Hanfu"
26
+ className="w-full h-full object-cover animate-fade-in"
27
+ />
28
+ ) : null}
29
+ </div>
30
+
31
+ {resultImage && !isLoading && (
32
+ <div className="flex gap-3 mt-4">
33
+ <button
34
+ onClick={() => {
35
+ const link = document.createElement('a');
36
+ link.href = resultImage;
37
+ link.download = 'hanfu-tryon.png';
38
+ link.click();
39
+ }}
40
+ className="flex-1 flex items-center justify-center gap-2 py-3 bg-stone-800 text-white rounded-xl hover:bg-stone-900 transition-colors"
41
+ >
42
+ <Download size={18} /> 保存图片
43
+ </button>
44
+ </div>
45
+ )}
46
+ </div>
47
+ );
48
+ };
constants.ts ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Dynasty, HanfuOption, CustomizationOption } from './types';
2
+
3
+ export const DYNASTY_OPTIONS: HanfuOption[] = [
4
+ {
5
+ id: Dynasty.Tang,
6
+ name: "大唐盛世 (Tang)",
7
+ description: "雍容华贵,齐胸衫裙,色彩艳丽。",
8
+ imagePlaceholder: "https://picsum.photos/400/600?random=1"
9
+ },
10
+ {
11
+ id: Dynasty.Song,
12
+ name: "雅宋清韵 (Song)",
13
+ description: "清雅婉约,褙子宋裤,简约自然。",
14
+ imagePlaceholder: "https://picsum.photos/400/600?random=2"
15
+ },
16
+ {
17
+ id: Dynasty.Ming,
18
+ name: "端庄大明 (Ming)",
19
+ description: "端庄大气,马面裙,袄裙,织金工艺。",
20
+ imagePlaceholder: "https://picsum.photos/400/600?random=3"
21
+ }
22
+ ];
23
+
24
+ export const CUSTOMIZATION_OPTIONS: CustomizationOption[] = [
25
+ { id: 'hairpin', label: '金步摇 (Gold Hairpin)', promptAddon: 'wearing a traditional Chinese gold hairpin (Buyao) on hair' },
26
+ { id: 'makeup', label: '花钿妆 (Huadian Makeup)', promptAddon: 'wearing traditional Chinese Huadian makeup styles with flower mark on forehead' },
27
+ { id: 'fan', label: '团扇 (Round Fan)', promptAddon: 'holding a traditional Chinese silk round fan' },
28
+ { id: 'lantern', label: '宫灯 (Lantern)', promptAddon: 'holding a glowing traditional paper lantern' }
29
+ ];
index.html ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>AI 汉服衣橱</title>
7
+ <script src="https://cdn.tailwindcss.com"></script>
8
+ <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;700&display=swap" rel="stylesheet">
9
+ <style>
10
+ body {
11
+ font-family: 'Noto Serif SC', serif;
12
+ background-color: #fcfbf9; /* Rice paper color */
13
+ }
14
+ </style>
15
+ <script type="importmap">
16
+ {
17
+ "imports": {
18
+ "react": "https://esm.sh/react@^19.2.3",
19
+ "react-dom/": "https://esm.sh/react-dom@^19.2.3/",
20
+ "react/": "https://esm.sh/react@^19.2.3/",
21
+ "@google/genai": "https://esm.sh/@google/genai@^1.34.0",
22
+ "lucide-react": "https://esm.sh/lucide-react@^0.562.0"
23
+ }
24
+ }
25
+ </script>
26
+ </head>
27
+ <body>
28
+ <div id="root"></div>
29
+ <script type="module" src="/index.tsx"></script>
30
+ </body>
31
+ </html>
index.tsx ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import ReactDOM from 'react-dom/client';
3
+ import App from './App';
4
+
5
+ const rootElement = document.getElementById('root');
6
+ if (!rootElement) {
7
+ throw new Error("Could not find root element to mount to");
8
+ }
9
+
10
+ const root = ReactDOM.createRoot(rootElement);
11
+ root.render(
12
+ <React.StrictMode>
13
+ <App />
14
+ </React.StrictMode>
15
+ );
metadata.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "name": "AI 汉服衣橱 (AI Hanfu Wardrobe)",
3
+ "description": "An AI-powered application allowing users to virtually try on traditional Chinese Hanfu from Tang, Song, and Ming dynasties using generative AI technology.",
4
+ "requestFramePermissions": []
5
+ }
package.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "ai-汉服衣橱-(ai-hanfu-wardrobe)",
3
+ "private": true,
4
+ "version": "0.0.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "vite",
8
+ "build": "vite build",
9
+ "preview": "vite preview"
10
+ },
11
+ "dependencies": {
12
+ "react": "^19.2.3",
13
+ "react-dom": "^19.2.3",
14
+ "@google/genai": "^1.34.0",
15
+ "lucide-react": "^0.562.0"
16
+ },
17
+ "devDependencies": {
18
+ "@types/node": "^22.14.0",
19
+ "@vitejs/plugin-react": "^5.0.0",
20
+ "typescript": "~5.8.2",
21
+ "vite": "^6.2.0"
22
+ }
23
+ }
services/geminiService.ts ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { GoogleGenAI } from "@google/genai";
2
+ import { Dynasty } from '../types';
3
+
4
+ const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
5
+
6
+ const SUPPORTED_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/heic', 'image/heif'];
7
+
8
+ const convertToJpeg = (base64Source: string): Promise<{ mimeType: string, data: string }> => {
9
+ return new Promise((resolve, reject) => {
10
+ const img = new Image();
11
+ img.onload = () => {
12
+ const canvas = document.createElement('canvas');
13
+ canvas.width = img.width;
14
+ canvas.height = img.height;
15
+ const ctx = canvas.getContext('2d');
16
+ if (!ctx) {
17
+ reject(new Error('Failed to create canvas context'));
18
+ return;
19
+ }
20
+ // Fill white background to handle transparent PNGs converting to JPEG
21
+ ctx.fillStyle = '#FFFFFF';
22
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
23
+ ctx.drawImage(img, 0, 0);
24
+
25
+ const jpegUrl = canvas.toDataURL('image/jpeg', 0.85);
26
+ const data = jpegUrl.replace(/^data:image\/jpeg;base64,/, "");
27
+ resolve({ mimeType: 'image/jpeg', data });
28
+ };
29
+ img.onerror = () => reject(new Error('Failed to load image for conversion'));
30
+ img.src = base64Source;
31
+ });
32
+ };
33
+
34
+ export const generateHanfuTryOn = async (
35
+ base64Image: string,
36
+ dynasty: Dynasty,
37
+ customizations: string[]
38
+ ): Promise<string> => {
39
+
40
+ // Extract mime type from base64 string
41
+ // Use a broader regex to catch types like image/svg+xml or image/avif
42
+ const mimeTypeMatch = base64Image.match(/^data:(image\/[a-zA-Z0-9.+-]+);base64,/);
43
+ const currentMimeType = mimeTypeMatch ? mimeTypeMatch[1] : '';
44
+
45
+ let finalMimeType = currentMimeType;
46
+ let finalData = base64Image.replace(/^data:image\/[a-zA-Z0-9.+-]+;base64,/, "");
47
+
48
+ // If MIME type is not natively supported by Gemini, convert to JPEG
49
+ if (currentMimeType && !SUPPORTED_MIME_TYPES.includes(currentMimeType)) {
50
+ try {
51
+ console.log(`Format ${currentMimeType} not supported by API. Converting to JPEG...`);
52
+ const converted = await convertToJpeg(base64Image);
53
+ finalMimeType = converted.mimeType;
54
+ finalData = converted.data;
55
+ } catch (e) {
56
+ console.warn("Image conversion failed, attempting to send original.", e);
57
+ }
58
+ }
59
+
60
+ let dynastyPrompt = "";
61
+ switch (dynasty) {
62
+ case Dynasty.Tang:
63
+ dynastyPrompt = "Tang Dynasty style Hanfu (Qixiong Ruqun), luxurious, colorful silk, high waist skirt";
64
+ break;
65
+ case Dynasty.Song:
66
+ dynastyPrompt = "Song Dynasty style Hanfu (Beizi), elegant, subtle colors, slender silhouette, sophisticated";
67
+ break;
68
+ case Dynasty.Ming:
69
+ dynastyPrompt = "Ming Dynasty style Hanfu (Mamian skirt and Aoqun), dignified, gold embroidery, structured";
70
+ break;
71
+ }
72
+
73
+ const customizationPrompt = customizations.join(", ");
74
+
75
+ const prompt = `Change the outfit of the person in this image to a ${dynastyPrompt}. ${customizationPrompt ? `Accessories: ${customizationPrompt}.` : ''} Keep the face, pose, and body shape unchanged. Photorealistic, high quality.`;
76
+
77
+ try {
78
+ const response = await ai.models.generateContent({
79
+ model: 'gemini-2.5-flash-image',
80
+ contents: {
81
+ parts: [
82
+ {
83
+ inlineData: {
84
+ mimeType: finalMimeType || 'image/jpeg',
85
+ data: finalData,
86
+ },
87
+ },
88
+ {
89
+ text: prompt,
90
+ },
91
+ ],
92
+ },
93
+ });
94
+
95
+ // Extract image from response
96
+ let generatedImageBase64 = null;
97
+
98
+ // Gemini 2.5 Flash Image returns parts. We need to find the image part.
99
+ if (response.candidates && response.candidates[0] && response.candidates[0].content && response.candidates[0].content.parts) {
100
+ for (const part of response.candidates[0].content.parts) {
101
+ if (part.inlineData && part.inlineData.data) {
102
+ generatedImageBase64 = part.inlineData.data;
103
+ break;
104
+ }
105
+ }
106
+ }
107
+
108
+ if (!generatedImageBase64) {
109
+ console.error("Unexpected response structure:", response);
110
+ throw new Error("No image data found in the response.");
111
+ }
112
+
113
+ return `data:image/png;base64,${generatedImageBase64}`;
114
+
115
+ } catch (error) {
116
+ console.error("Gemini API Error:", error);
117
+ throw error;
118
+ }
119
+ };
tsconfig.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "experimentalDecorators": true,
5
+ "useDefineForClassFields": false,
6
+ "module": "ESNext",
7
+ "lib": [
8
+ "ES2022",
9
+ "DOM",
10
+ "DOM.Iterable"
11
+ ],
12
+ "skipLibCheck": true,
13
+ "types": [
14
+ "node"
15
+ ],
16
+ "moduleResolution": "bundler",
17
+ "isolatedModules": true,
18
+ "moduleDetection": "force",
19
+ "allowJs": true,
20
+ "jsx": "react-jsx",
21
+ "paths": {
22
+ "@/*": [
23
+ "./*"
24
+ ]
25
+ },
26
+ "allowImportingTsExtensions": true,
27
+ "noEmit": true
28
+ }
29
+ }
types.ts ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export enum Dynasty {
2
+ Tang = 'Tang',
3
+ Song = 'Song',
4
+ Ming = 'Ming'
5
+ }
6
+
7
+ export interface HanfuOption {
8
+ id: Dynasty;
9
+ name: string;
10
+ description: string;
11
+ imagePlaceholder: string;
12
+ }
13
+
14
+ export interface CustomizationOption {
15
+ id: string;
16
+ label: string;
17
+ promptAddon: string;
18
+ }
19
+
20
+ export interface GenerationState {
21
+ isLoading: boolean;
22
+ error: string | null;
23
+ resultImage: string | null;
24
+ }
vite.config.ts ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import path from 'path';
2
+ import { defineConfig, loadEnv } from 'vite';
3
+ import react from '@vitejs/plugin-react';
4
+
5
+ export default defineConfig(({ mode }) => {
6
+ const env = loadEnv(mode, '.', '');
7
+ return {
8
+ server: {
9
+ port: 3000,
10
+ host: '0.0.0.0',
11
+ },
12
+ plugins: [react()],
13
+ define: {
14
+ 'process.env.API_KEY': JSON.stringify(env.GEMINI_API_KEY),
15
+ 'process.env.GEMINI_API_KEY': JSON.stringify(env.GEMINI_API_KEY)
16
+ },
17
+ resolve: {
18
+ alias: {
19
+ '@': path.resolve(__dirname, '.'),
20
+ }
21
+ }
22
+ };
23
+ });