saliseabeali commited on
Commit
b1fa3c1
·
verified ·
1 Parent(s): 5d3e602

Upload script (2).js

Browse files
Files changed (1) hide show
  1. script (2).js +804 -0
script (2).js ADDED
@@ -0,0 +1,804 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Added global error handling for WebsimSocket
2
+ window.onerror = function(message, source, lineno, colno, error) {
3
+ console.error("Global error:", { message, source, lineno, colno, error });
4
+ };
5
+
6
+ // Fallback WebsimSocket mock for development/testing
7
+ if (typeof websim === 'undefined') {
8
+ console.warn("WebsimSocket not found. Creating mock implementation.");
9
+ window.websim = {
10
+ imageGen: async function(options) {
11
+ console.warn("Mock imageGen called with options:", options);
12
+ // Return a mock image URL for testing
13
+ return {
14
+ url: "https://via.placeholder.com/512x512?text=Image+Generation+Mocked"
15
+ };
16
+ },
17
+ chat: {
18
+ completions: {
19
+ create: async function(params) {
20
+ console.warn("Mock chat completions called with params:", params);
21
+ return {
22
+ content: "This is a mock AI response for testing.",
23
+ role: "assistant"
24
+ };
25
+ }
26
+ }
27
+ }
28
+ };
29
+ }
30
+
31
+ const promptInput = document.getElementById('promptInput');
32
+ const negativePromptInput = document.getElementById('negativePromptInput');
33
+ const seedInput = document.getElementById('seedInput');
34
+ const styleSelect = document.getElementById('styleSelect');
35
+ const renderQualitySelect = document.getElementById('renderQualitySelect');
36
+ const lightingSelect = document.getElementById('lightingSelect');
37
+ const controlNetSelect = document.getElementById('controlNetSelect');
38
+ const anatomyControlSelect = document.getElementById('anatomyControlSelect');
39
+ const generateButton = document.getElementById('generateButton');
40
+ const generatedImage = document.getElementById('generatedImage');
41
+ const loadingIndicator = document.getElementById('loading');
42
+ const technicalExplanation = document.querySelector('.technical-explanation');
43
+
44
+ // Prompt Enhancer Module
45
+ const promptEnhancerModule = {
46
+ enhancements: {
47
+ "a cat": "a photorealistic fluffy white cat sitting on a windowsill, soft light, shallow depth of field, 4k resolution",
48
+ "a fox": "a majestic red fox standing in a misty forest, golden hour lighting, detailed fur, realistic anatomy, 8k resolution",
49
+ "a landscape": "a breathtaking mountain landscape with vibrant colors, sunrise lighting, crisp details, epic panoramic view, high resolution"
50
+ },
51
+
52
+ enhance: async function(originalPrompt) {
53
+ // First, use the new advanced prompt engineering module
54
+ const semanticAnalysis = await promptEngineeringModule.analyzeAndCorrectPrompt(originalPrompt);
55
+
56
+ // Then enhance with style and quality details
57
+ const enhancedPrompt = promptEngineeringModule.enhancePrompt(semanticAnalysis, {
58
+ style: styleSelect.value,
59
+ renderQuality: renderQualitySelect.value,
60
+ lighting: lightingSelect.value
61
+ });
62
+
63
+ return enhancedPrompt;
64
+ }
65
+ };
66
+
67
+ // Advanced Prompt Engineering Module
68
+ const promptEngineeringModule = {
69
+ // Enhanced prompt generation with more specific details
70
+ enhancePrompt: function(originalPrompt, options = {}) {
71
+ const {
72
+ style = 'default',
73
+ renderQuality = 'standard',
74
+ lighting = 'default',
75
+ detailLevel = 'high'
76
+ } = options;
77
+
78
+ const styleMap = {
79
+ 'default': '',
80
+ 'photorealistic': 'photorealistic, high detail, sharp focus',
81
+ 'anime': 'anime style, clean lines, vibrant colors',
82
+ 'digital-art': 'digital art, crisp edges, stylized',
83
+ 'studio-ghibli': 'Studio Ghibli style, soft colors, whimsical',
84
+ 'oil-painting': 'oil painting texture, rich brush strokes',
85
+ 'realistic': 'hyper-realistic, ultra-detailed',
86
+ 'dreamscape': 'surreal, dreamy, soft focus'
87
+ };
88
+
89
+ const lightingMap = {
90
+ 'default': '',
91
+ 'cinematic': 'cinematic lighting, dramatic shadows',
92
+ 'soft': 'soft, diffused light, gentle shadows',
93
+ 'dramatic': 'high contrast, strong directional light',
94
+ 'sunset': 'golden hour, warm tones, long shadows'
95
+ };
96
+
97
+ const qualityMap = {
98
+ 'standard': '512x512 resolution',
99
+ 'high': '768x768 resolution, enhanced details',
100
+ 'ultra': '1024x1024 resolution, maximum detail',
101
+ '4k': '2048x2048 resolution, ultra high quality'
102
+ };
103
+
104
+ const detailLevelMap = {
105
+ 'low': 'basic shapes, minimal detail',
106
+ 'medium': 'clear definition, moderate detail',
107
+ 'high': 'intricate details, sharp edges, textural complexity'
108
+ };
109
+
110
+ // Combine enhanced prompt with style and quality specifications
111
+ const enhancedPrompt = [
112
+ originalPrompt,
113
+ styleMap[style],
114
+ lightingMap[lighting],
115
+ qualityMap[renderQuality],
116
+ `${detailLevelMap[detailLevel]}, precise composition`
117
+ ].filter(Boolean).join(', ');
118
+
119
+ return enhancedPrompt;
120
+ },
121
+
122
+ // Advanced semantic analysis and prompt correction
123
+ analyzeAndCorrectPrompt: async function(prompt) {
124
+ try {
125
+ const completion = await websim.chat.completions.create({
126
+ messages: [
127
+ {
128
+ role: "system",
129
+ content: `You are an expert prompt engineer for AI image generation.
130
+ Analyze the given prompt and:
131
+ 1. Improve clarity and specificity
132
+ 2. Add missing descriptive details
133
+ 3. Ensure semantic consistency
134
+ 4. Optimize for better image generation`
135
+ },
136
+ {
137
+ role: "user",
138
+ content: prompt
139
+ }
140
+ ]
141
+ });
142
+
143
+ return completion.content || prompt;
144
+ } catch (error) {
145
+ console.warn("Prompt analysis fallback triggered:", error);
146
+ return prompt;
147
+ }
148
+ }
149
+ };
150
+
151
+ // Semantic Consistency Check Module
152
+ const semanticConsistencyModule = {
153
+ checks: [
154
+ {
155
+ name: "Anatomical Consistency",
156
+ check: async (prompt, imageUrl) => {
157
+ try {
158
+ const result = await websim.chat.completions.create({
159
+ messages: [
160
+ {
161
+ role: "system",
162
+ content: "Analyze the image for anatomical correctness based on the prompt. Report any inconsistencies concisely."
163
+ },
164
+ {
165
+ role: "user",
166
+ content: [
167
+ { type: "text", text: `Check anatomical correctness for prompt: ${prompt}` },
168
+ { type: "image_url", image_url: { url: imageUrl } }
169
+ ]
170
+ }
171
+ ]
172
+ });
173
+ return `Anatomical Check: ${result.content}`;
174
+ } catch (error) {
175
+ console.error("Anatomical consistency check failed:", error);
176
+ return `Anatomical Check: Error performing check - ${error.message}`;
177
+ }
178
+ }
179
+ },
180
+ {
181
+ name: "Prompt Adherence Check",
182
+ check: async (prompt, imageUrl) => {
183
+ try {
184
+ const result = await websim.chat.completions.create({
185
+ messages: [
186
+ {
187
+ role: "system",
188
+ content: "Compare the image against the provided prompt. Summarize how well the image matches the key elements of the prompt."
189
+ },
190
+ {
191
+ role: "user",
192
+ content: [
193
+ { type: "text", text: `Check adherence to prompt: ${prompt}` },
194
+ { type: "image_url", image_url: { url: imageUrl } }
195
+ ]
196
+ }
197
+ ]
198
+ });
199
+ return `Prompt Adherence: ${result.content}`;
200
+ } catch (error) {
201
+ console.error("Prompt adherence check failed:", error);
202
+ return `Prompt Adherence: Error performing check - ${error.message}`;
203
+ }
204
+ }
205
+ },
206
+ {
207
+ name: "Negative Prompt Check",
208
+ check: async (prompt, negativePrompt, imageUrl) => {
209
+ if (!negativePrompt || negativePrompt.trim() === '') {
210
+ return "Negative Prompt Check: No negative prompt provided.";
211
+ }
212
+ try {
213
+ const result = await websim.chat.completions.create({
214
+ messages: [
215
+ {
216
+ role: "system",
217
+ content: "Analyze the image to see if it contains elements explicitly mentioned in the negative prompt."
218
+ },
219
+ {
220
+ role: "user",
221
+ content: [
222
+ { type: "text", text: `Check negative prompt: ${prompt} with negative prompt: ${negativePrompt}` },
223
+ { type: "image_url", image_url: { url: imageUrl } }
224
+ ]
225
+ }
226
+ ]
227
+ });
228
+ return `Negative Prompt Check: ${result.content}`;
229
+ } catch (error) {
230
+ console.error("Negative prompt check failed:", error);
231
+ return `Negative Prompt Check: Error performing check - ${error.message}`;
232
+ }
233
+ }
234
+ }
235
+ ],
236
+
237
+ performChecks: async function(prompt, negativePrompt, imageUrl) {
238
+ const results = [];
239
+ // Clear previous results while checks are running
240
+ const semanticCheckList = document.getElementById('semanticCheckList');
241
+ if (semanticCheckList) {
242
+ semanticCheckList.innerHTML = '<li>Running semantic checks...</li>';
243
+ }
244
+
245
+ for (let check of this.checks) {
246
+ let checkResult;
247
+ if (check.name === "Negative Prompt Check") {
248
+ checkResult = await check.check(prompt, negativePrompt, imageUrl);
249
+ } else {
250
+ checkResult = await check.check(prompt, imageUrl);
251
+ }
252
+ results.push(checkResult);
253
+ }
254
+ return results;
255
+ }
256
+ };
257
+
258
+ // Layered Generation Module (basic placeholder)
259
+ const layeredGenerationModule = {
260
+ generateLayered: async function(prompt) {
261
+ // Placeholder for future implementation
262
+ console.log("Layered generation for:", prompt);
263
+ return null;
264
+ }
265
+ };
266
+
267
+ const styleMap = {
268
+ 'default': {
269
+ prompt_prefix: '',
270
+ model: 'stable-diffusion-xl',
271
+ sampler: 'Euler a'
272
+ },
273
+ 'photorealistic': {
274
+ prompt_prefix: 'highly detailed photorealistic, sharp focus, natural lighting',
275
+ model: 'realistic-vision-v5',
276
+ sampler: 'DPM++ 2M Karras'
277
+ },
278
+ 'anime': {
279
+ prompt_prefix: 'anime style, clean lines, vibrant colors, sharp details, kyoto animation aesthetic',
280
+ model: 'deliberate-v2',
281
+ sampler: 'Euler a'
282
+ },
283
+ 'digital-art': {
284
+ prompt_prefix: 'digital illustration, crisp edges, stylized, graphic novel aesthetic, high contrast',
285
+ model: 'dreamshaper-v8',
286
+ sampler: 'DDIM'
287
+ },
288
+ 'studio-ghibli': {
289
+ prompt_prefix: 'Studio Ghibli style, soft color palette, whimsical, hand-drawn texture, Miyazaki-inspired',
290
+ model: 'ghibli-diffusion',
291
+ sampler: 'Euler'
292
+ },
293
+ 'oil-painting': {
294
+ prompt_prefix: 'oil painting texture, rich brush strokes, impasto technique, canvas-like rendering',
295
+ model: 'anything-v5',
296
+ sampler: 'DPM++ SDE Karras'
297
+ },
298
+ 'realistic': {
299
+ prompt_prefix: 'ultra-realistic, hyper-detailed, natural textures, precise anatomical accuracy',
300
+ model: 'realistic-vision-v5',
301
+ sampler: 'DPM++ 2M Karras'
302
+ },
303
+ 'dreamscape': {
304
+ prompt_prefix: 'surreal, dreamy atmosphere, soft focus, ethereal lighting, blended reality',
305
+ model: 'stable-diffusion-xl',
306
+ sampler: 'Euler a'
307
+ }
308
+ };
309
+
310
+ function mapRenderQuality(quality) {
311
+ const qualityMap = {
312
+ "standard": {
313
+ width: 512,
314
+ height: 512,
315
+ description: "Standard Quality (512x512)"
316
+ },
317
+ "high": {
318
+ width: 768,
319
+ height: 768,
320
+ description: "High Quality (768x768)"
321
+ },
322
+ "ultra": {
323
+ width: 1024,
324
+ height: 1024,
325
+ description: "Ultra HD (1024x1024)"
326
+ },
327
+ "4k": {
328
+ width: 2048,
329
+ height: 2048,
330
+ description: "4K Ultra-Detailed (2048x2048)"
331
+ }
332
+ };
333
+ return qualityMap[quality] || qualityMap["standard"];
334
+ }
335
+
336
+ // Advanced Face Generation Module
337
+ const faceGenerationModule = {
338
+ // Advanced prompt engineering for high-quality face generation
339
+ enhanceFacePrompt: function(basePrompt, options = {}) {
340
+ const {
341
+ faceQuality = 'high',
342
+ symmetry = true,
343
+ style = 'photorealistic'
344
+ } = options;
345
+
346
+ const qualityPrefixes = {
347
+ 'low': 'basic face details',
348
+ 'medium': 'clear facial features, moderate detail',
349
+ 'high': 'perfect symmetrical face, high resolution, soft studio lighting, crisp details',
350
+ 'ultra': 'hyper-realistic face, professional DSLR photo quality, cinematic lighting, intricate skin texture'
351
+ };
352
+
353
+ const stylePrefixes = {
354
+ 'photorealistic': 'DSLR photo style, natural skin tones, precise facial structure',
355
+ 'anime': 'anime style, clean lines, large expressive eyes',
356
+ 'artistic': 'stylized face, painterly details, soft color palette',
357
+ 'sketch': 'pencil sketch style, delicate line work'
358
+ };
359
+
360
+ const symmetryPrefix = symmetry ? 'perfectly symmetrical, ' : '';
361
+
362
+ const enhancedPrompt = [
363
+ basePrompt,
364
+ symmetryPrefix,
365
+ qualityPrefixes[faceQuality],
366
+ stylePrefixes[style]
367
+ ].filter(Boolean).join(', ');
368
+
369
+ return enhancedPrompt;
370
+ },
371
+
372
+ // Advanced face correction using AI techniques
373
+ correctFace: async function(imageUrl) {
374
+ try {
375
+ // Simulate using GFPGAN or CodeFormer for face enhancement
376
+ const result = await websim.chat.completions.create({
377
+ messages: [
378
+ {
379
+ role: "system",
380
+ content: "Analyze and correct facial details in the image. Improve symmetry, skin texture, and overall facial structure. Provide a URL to the corrected image or indicate if no correction was needed."
381
+ },
382
+ {
383
+ role: "user",
384
+ content: [
385
+ { type: "text", text: "Enhance facial details" },
386
+ { type: "image_url", image_url: { url: imageUrl } }
387
+ ]
388
+ }
389
+ ]
390
+ });
391
+
392
+ try {
393
+ const response = JSON.parse(result.content);
394
+ if (response && response.url) {
395
+ console.log("Face correction applied. New image URL:", response.url);
396
+ return response.url;
397
+ } else {
398
+ console.log("Face correction analysis:", result.content);
399
+ return imageUrl;
400
+ }
401
+ } catch (e) {
402
+ console.log("Face correction analysis (non-JSON response):", result.content);
403
+ return imageUrl;
404
+ }
405
+
406
+ } catch (error) {
407
+ console.error("Face correction failed:", error);
408
+ return null;
409
+ }
410
+ },
411
+
412
+ // Advanced semantic face analysis
413
+ analyzeFace: async function(imageUrl) {
414
+ try {
415
+ const result = await websim.chat.completions.create({
416
+ messages: [
417
+ {
418
+ role: "system",
419
+ content: `Perform comprehensive face analysis:
420
+ 1. Check facial symmetry
421
+ 2. Verify anatomical correctness
422
+ 3. Assess style adherence
423
+ 4. Detect any artifacts or inconsistencies
424
+ 5. Provide a concise summary.`
425
+ },
426
+ {
427
+ role: "user",
428
+ content: [
429
+ { type: "text", text: "Analyze face in image" },
430
+ { type: "image_url", image_url: { url: imageUrl } }
431
+ ]
432
+ }
433
+ ]
434
+ });
435
+
436
+ return result.content;
437
+ } catch (error) {
438
+ console.error("Face analysis failed:", error);
439
+ return null;
440
+ }
441
+ }
442
+ };
443
+
444
+ async function generateImage(prompt, options = {}) {
445
+ const {
446
+ negativePrompt = '',
447
+ seed,
448
+ style = 'default',
449
+ renderQuality = 'standard',
450
+ lighting,
451
+ controlNetMode,
452
+ faceQuality,
453
+ faceStyle,
454
+ symmetry,
455
+ perspective,
456
+ objectPlacement,
457
+ lightSource,
458
+ depthPerception,
459
+ cfgScale,
460
+ steps
461
+ } = options;
462
+
463
+ // Get style-specific configuration
464
+ const styleConfig = styleMap[style] || styleMap['default'];
465
+
466
+ // Combine style-specific prefix with original prompt
467
+ let enhancedPrompt = `${styleConfig.prompt_prefix}, ${prompt}`;
468
+
469
+ // If face generation is detected, enhance the prompt
470
+ const isFacePrompt = prompt.toLowerCase().includes('face') ||
471
+ prompt.toLowerCase().includes('portrait');
472
+
473
+ if (isFacePrompt) {
474
+ enhancedPrompt = faceGenerationModule.enhanceFacePrompt(enhancedPrompt, {
475
+ faceQuality: faceQuality || 'high',
476
+ symmetry: symmetry !== false,
477
+ style: faceStyle || 'photorealistic'
478
+ });
479
+ }
480
+
481
+ // Enhanced Perspective Mapping
482
+ const perspectiveMap = {
483
+ 'front-view': 'viewed straight on, front perspective',
484
+ 'side-view': 'side angle view, profile perspective',
485
+ 'overhead': 'viewed from above, overhead perspective',
486
+ 'diagonal': 'diagonal angle, dynamic perspective',
487
+ 'tilted-view': 'slightly tilted view, subtle angle'
488
+ };
489
+
490
+ const objectPlacementMap = {
491
+ 'balanced': 'balanced composition, symmetric arrangement',
492
+ 'asymmetric': 'asymmetric layout, dynamic positioning',
493
+ 'rule-of-thirds': 'following rule of thirds, strategic placement',
494
+ 'centered': 'centered focal point, symmetrical design'
495
+ };
496
+
497
+ const lightSourceMap = {
498
+ 'left-side': 'light source from left side, creating defined shadows',
499
+ 'right-side': 'light source from right side, dramatic shadowing',
500
+ 'top-down': 'overhead lighting, creating vertical shadows',
501
+ 'diagonal': 'diagonal light, creating depth and dimension',
502
+ 'backlighting': 'backlight effect, silhouette and rim lighting',
503
+ 'soft-ambient': 'soft, diffused ambient lighting'
504
+ };
505
+
506
+ const depthPerceptionMap = {
507
+ 'shallow-depth': 'shallow depth of field, soft background blur',
508
+ 'deep-depth': 'deep depth of field, entire scene in focus',
509
+ 'layered-focus': 'layered focus, multiple depth levels',
510
+ 'foreground-emphasis': 'foreground elements sharply focused'
511
+ };
512
+
513
+ // Enhance prompt with perspective and composition details
514
+ if (perspective) {
515
+ enhancedPrompt += `, ${perspectiveMap[perspective]}`;
516
+ }
517
+
518
+ if (objectPlacement) {
519
+ enhancedPrompt += `, ${objectPlacementMap[objectPlacement]}`;
520
+ }
521
+
522
+ if (lightSource) {
523
+ enhancedPrompt += `, ${lightSourceMap[lightSource]}`;
524
+ }
525
+
526
+ if (depthPerception) {
527
+ enhancedPrompt += `, ${depthPerceptionMap[depthPerception]}`;
528
+ }
529
+
530
+ // Use the enhanced mapRenderQuality function
531
+ const qualitySettings = mapRenderQuality(renderQuality);
532
+
533
+ try {
534
+ const result = await websim.imageGen({
535
+ prompt: enhancedPrompt,
536
+ negative_prompt: getCombinedNegativePrompt(negativePrompt),
537
+ seed: seed,
538
+ style: style === 'default' ? undefined : style,
539
+ width: qualitySettings.width,
540
+ height: qualitySettings.height,
541
+ lighting: lighting === 'default' ? undefined : lighting,
542
+ controlnet_mode: controlNetMode === 'none' ? undefined : controlNetMode,
543
+ sampler: styleConfig.sampler,
544
+ model: styleConfig.model,
545
+ cfg_scale: cfgScale,
546
+ steps: steps,
547
+ perspective: perspective,
548
+ object_placement: objectPlacement,
549
+ light_source: lightSource,
550
+ depth_perception: depthPerception
551
+ });
552
+
553
+ console.log(`Generating image with ${qualitySettings.description}`);
554
+
555
+ // Post-generation face correction
556
+ if (isFacePrompt && result.url) {
557
+ const correctedImageUrl = await faceGenerationModule.correctFace(result.url);
558
+ result.url = correctedImageUrl || result.url;
559
+
560
+ // Optional face analysis
561
+ const faceAnalysis = await faceGenerationModule.analyzeFace(result.url);
562
+ console.log("Face Analysis:", faceAnalysis);
563
+ }
564
+
565
+ return result;
566
+ } catch (error) {
567
+ console.error("Advanced Image Generation Error:", error);
568
+ throw error;
569
+ }
570
+ }
571
+
572
+ function getCombinedNegativePrompt(userNegativePrompt) {
573
+ const baseAnatomyPreventionPrompts = [
574
+ "deformed anatomy",
575
+ "extra limbs",
576
+ "duplicate body parts",
577
+ "unnatural proportions",
578
+ "malformed features",
579
+ "unrealistic anatomy",
580
+ "missing limbs",
581
+ "mutated",
582
+ "twisted",
583
+ "bad eyes",
584
+ "extra fingers",
585
+ "missing fingers"
586
+ ];
587
+
588
+ const baseQualityPreventions = [
589
+ "low quality",
590
+ "blurry",
591
+ "watermark",
592
+ "text",
593
+ "disfigured",
594
+ "ugly",
595
+ "nonsensical",
596
+ "bad composition",
597
+ "poorly drawn",
598
+ "sketch",
599
+ "noise",
600
+ "grainy"
601
+ ];
602
+
603
+ const textSpecificPreventions = [
604
+ "unreadable text",
605
+ "gibberish",
606
+ "nonsense text",
607
+ "broken letters",
608
+ "random symbols"
609
+ ];
610
+
611
+ let combinedPrompts = [...baseAnatomyPreventionPrompts, ...baseQualityPreventions, ...textSpecificPreventions];
612
+
613
+ if (userNegativePrompt) {
614
+ combinedPrompts = combinedPrompts.concat(userNegativePrompt.split(',').map(p => p.trim()));
615
+ }
616
+
617
+ const uniquePrompts = [...new Set(combinedPrompts)].filter(p => p !== '');
618
+
619
+ return uniquePrompts.join(", ");
620
+ }
621
+
622
+ async function performSemanticChecks(prompt, imageUrl) {
623
+ const semanticCheckList = document.getElementById('semanticCheckList');
624
+ semanticCheckList.innerHTML = '<li>Running advanced semantic checks...</li>';
625
+
626
+ try {
627
+ const result = await websim.chat.completions.create({
628
+ messages: [
629
+ {
630
+ role: "system",
631
+ content: `Perform a comprehensive semantic analysis of the image:
632
+ 1. Check anatomical correctness
633
+ 2. Verify prompt adherence
634
+ 3. Detect any inconsistencies or artifacts
635
+ 4. Suggest potential improvements`
636
+ },
637
+ {
638
+ role: "user",
639
+ content: [
640
+ { type: "text", text: `Analyze image generated from prompt: ${prompt}` },
641
+ { type: "image_url", image_url: { url: imageUrl } }
642
+ ]
643
+ }
644
+ ]
645
+ });
646
+
647
+ semanticCheckList.innerHTML = result.content
648
+ .split('\n')
649
+ .map(line => `<li>${line}</li>`)
650
+ .join('');
651
+ } catch (error) {
652
+ console.error("Advanced Semantic Check Failed:", error);
653
+ semanticCheckList.innerHTML = `<li>Advanced semantic check failed: ${error.message}</li>`;
654
+ }
655
+ }
656
+
657
+ const faceQualitySelect = document.createElement('select');
658
+ faceQualitySelect.id = 'faceQualitySelect';
659
+ faceQualitySelect.innerHTML = `
660
+ <option value="low">Basic Quality</option>
661
+ <option value="medium">Medium Quality</option>
662
+ <option value="high" selected>High Quality</option>
663
+ <option value="ultra">Ultra Quality</option>
664
+ `;
665
+
666
+ const faceStyleSelect = document.createElement('select');
667
+ faceStyleSelect.id = 'faceStyleSelect';
668
+ faceStyleSelect.innerHTML = `
669
+ <option value="photorealistic" selected>Photorealistic</option>
670
+ <option value="anime">Anime Style</option>
671
+ <option value="artistic">Artistic</option>
672
+ <option value="sketch">Sketch Style</option>
673
+ `;
674
+
675
+ const perspectiveSelect = document.createElement('select');
676
+ perspectiveSelect.id = 'perspectiveSelect';
677
+ perspectiveSelect.innerHTML = `
678
+ <option value="front-view">Front View</option>
679
+ <option value="side-view">Side View</option>
680
+ <option value="overhead">Overhead View</option>
681
+ <option value="diagonal">Diagonal View</option>
682
+ <option value="tilted-view">Tilted View</option>
683
+ `;
684
+
685
+ const objectPlacementSelect = document.createElement('select');
686
+ objectPlacementSelect.id = 'objectPlacementSelect';
687
+ objectPlacementSelect.innerHTML = `
688
+ <option value="balanced">Balanced Composition</option>
689
+ <option value="asymmetric">Asymmetric Layout</option>
690
+ <option value="rule-of-thirds">Rule of Thirds</option>
691
+ <option value="centered">Centered Focal Point</option>
692
+ `;
693
+
694
+ const lightSourceSelect = document.createElement('select');
695
+ lightSourceSelect.id = 'lightSourceSelect';
696
+ lightSourceSelect.innerHTML = `
697
+ <option value="left-side">Left Side Lighting</option>
698
+ <option value="right-side">Right Side Lighting</option>
699
+ <option value="top-down">Top-Down Lighting</option>
700
+ <option value="diagonal">Diagonal Lighting</option>
701
+ <option value="backlighting">Backlighting</option>
702
+ <option value="soft-ambient">Soft Ambient Lighting</option>
703
+ `;
704
+
705
+ const depthPerceptionSelect = document.createElement('select');
706
+ depthPerceptionSelect.id = 'depthPerceptionSelect';
707
+ depthPerceptionSelect.innerHTML = `
708
+ <option value="shallow-depth">Shallow Depth of Field</option>
709
+ <option value="deep-depth">Deep Depth of Field</option>
710
+ <option value="layered-focus">Layered Focus</option>
711
+ <option value="foreground-emphasis">Foreground Emphasis</option>
712
+ `;
713
+
714
+ document.querySelector('.style-grid').appendChild(
715
+ createControlGroup('🖼️ Face Quality:', faceQualitySelect)
716
+ );
717
+ document.querySelector('.style-grid').appendChild(
718
+ createControlGroup('🎨 Face Style:', faceStyleSelect)
719
+ );
720
+ document.querySelector('.style-grid').appendChild(
721
+ createControlGroup('📸 Perspective:', perspectiveSelect)
722
+ );
723
+ document.querySelector('.style-grid').appendChild(
724
+ createControlGroup('🖌️ Object Placement:', objectPlacementSelect)
725
+ );
726
+ document.querySelector('.style-grid').appendChild(
727
+ createControlGroup('💡 Light Source:', lightSourceSelect)
728
+ );
729
+ document.querySelector('.style-grid').appendChild(
730
+ createControlGroup('🔍 Depth Perception:', depthPerceptionSelect)
731
+ );
732
+
733
+ function createControlGroup(labelText, selectElement) {
734
+ const container = document.createElement('div');
735
+ container.className = 'style-item';
736
+
737
+ const label = document.createElement('label');
738
+ label.textContent = labelText;
739
+
740
+ container.appendChild(label);
741
+ container.appendChild(selectElement);
742
+
743
+ return container;
744
+ }
745
+
746
+ generateButton.addEventListener('click', async () => {
747
+ const userPrompt = promptInput.value.trim();
748
+
749
+ if (!userPrompt) {
750
+ alert('Please enter a prompt to generate an image!');
751
+ return;
752
+ }
753
+
754
+ // Show loading indicator
755
+ loadingIndicator.classList.remove('hidden');
756
+ // Hide previous image
757
+ generatedImage.src = "";
758
+ // Clear previous semantic check results
759
+ const semanticCheckList = document.getElementById('semanticCheckList');
760
+ if (semanticCheckList) {
761
+ semanticCheckList.innerHTML = '';
762
+ }
763
+ document.getElementById('semanticCheckResult').classList.add('hidden');
764
+
765
+
766
+ try {
767
+ // Enhanced image generation with more control
768
+ const imageGenerationOptions = {
769
+ negativePrompt: negativePromptInput.value.trim(),
770
+ seed: seedInput.value ? parseInt(seedInput.value, 10) : undefined,
771
+ style: styleSelect.value,
772
+ renderQuality: renderQualitySelect.value,
773
+ lighting: lightingSelect.value,
774
+ controlNetMode: controlNetSelect.value,
775
+ faceQuality: faceQualitySelect.value,
776
+ faceStyle: faceStyleSelect.value,
777
+ symmetry: true,
778
+ perspective: perspectiveSelect.value,
779
+ objectPlacement: objectPlacementSelect.value,
780
+ lightSource: lightSourceSelect.value,
781
+ depthPerception: depthPerceptionSelect.value,
782
+ cfgScale: parseFloat(document.getElementById('cfgScaleInput').value),
783
+ steps: parseInt(document.getElementById('stepsInput').value, 10)
784
+ };
785
+
786
+ const result = await generateImage(userPrompt, imageGenerationOptions);
787
+
788
+ if (result && result.url) {
789
+ generatedImage.src = result.url;
790
+
791
+ // Additional semantic checks and enhancements
792
+ // Show semantic check results panel
793
+ document.getElementById('semanticCheckResult').classList.remove('hidden');
794
+ await performSemanticChecks(userPrompt, result.url);
795
+ }
796
+ } catch (error) {
797
+ console.error("Image Generation Process Failed:", error);
798
+ alert("Image generation failed: " + error.message);
799
+ generatedImage.src = "";
800
+ } finally {
801
+ // Hide loading indicator
802
+ loadingIndicator.classList.add('hidden');
803
+ }
804
+ });