forked from EuclidStellar/LexicraftAI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeminiAPI.js
More file actions
1141 lines (985 loc) · 37.2 KB
/
geminiAPI.js
File metadata and controls
1141 lines (985 loc) · 37.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { GoogleGenerativeAI } from '@google/generative-ai';
const BACKEND_BASE_URL = (process.env.REACT_APP_BACKEND_URL || '').replace(/\/$/, '');
class GeminiService {
constructor() {
this.genAI = null;
this.backendBase = BACKEND_BASE_URL;
this.usingBackend = Boolean(this.backendBase);
}
setApiKey(apiKey) {
this.genAI = new GoogleGenerativeAI(apiKey);
}
async requestBackend(path, payload) {
if (!this.backendBase) {
throw new Error('Backend URL not configured');
}
try {
const response = await fetch(`${this.backendBase}${path}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
const contentType = response.headers.get('content-type') || '';
const isJson = contentType.includes('application/json');
const data = isJson ? await response.json() : null;
if (!response.ok) {
const detail = data?.detail || data?.error || response.statusText;
throw new Error(detail || 'Backend request failed');
}
return data ?? {};
} catch (error) {
throw new Error(error.message || 'Backend request failed');
}
}
// Helper function to clean and parse AI responses
cleanAndParseResponse(responseText) {
// Remove markdown code blocks
let cleanText = responseText.replace(/```json\s*/g, '').replace(/```\s*/g, '');
// Try to extract JSON from the response
const jsonMatch = cleanText.match(/\{[\s\S]*\}/);
if (jsonMatch) {
try {
return JSON.parse(jsonMatch[0]);
} catch (e) {
console.warn('Failed to parse JSON:', e);
return null;
}
}
return null;
}
// Enhanced paraphrasing with literary styles
async advancedParaphrase(text, options = {}) {
const {
mode = 'Literary',
writingStyle = 'neutral',
targetAudience = 'general',
preserveDialogue = true,
} = options;
if (this.usingBackend) {
return await this.requestBackend('/api/paraphrase/advanced', {
text,
mode,
writingStyle,
targetAudience,
preserveDialogue,
});
}
if (!this.genAI) {
throw new Error('API key not set');
}
let prompt = `Transform the following text with these specifications:
- Literary Mode: ${mode}
- Writing Style: ${writingStyle}
- Target Audience: ${targetAudience}
- Preserve Dialogue: ${preserveDialogue}
Focus on:
1. Enhancing literary quality while maintaining meaning
2. Improving sentence variety and flow
3. Elevating vocabulary appropriately
4. Maintaining character voice consistency
Text: "${text}"
Provide ONLY the refined version without any explanations or formatting.`;
try {
const model = this.genAI.getGenerativeModel({ model: "gemini-2.0-flash" });
const result = await model.generateContent(prompt);
const response = await result.response;
return {
success: true,
result: response.text().trim(),
originalLength: text.length,
newLength: response.text().length
};
} catch (error) {
throw new Error(`Advanced paraphrasing failed: ${error.message}`);
}
}
// Advanced grammar and style checking
async checkGrammarAdvanced(text, level) {
if (this.usingBackend) {
return await this.requestBackend('/api/grammar/check', { text, level });
}
if (!this.genAI) {
throw new Error('API key not set');
}
let analysisDepth;
switch (level) {
case 'basic':
analysisDepth = 'Focus only on grammar errors and basic punctuation';
break;
case 'standard':
analysisDepth = 'Check grammar, punctuation, style, and clarity issues';
break;
case 'comprehensive':
analysisDepth = 'Comprehensive analysis including grammar, style, flow, consistency, and literary quality';
break;
case 'literary':
analysisDepth = 'Literary analysis focusing on creative writing, narrative voice, character consistency, and artistic expression';
break;
}
const prompt = `Perform a ${level} grammar and style analysis of the following text.
${analysisDepth}
Text: "${text}"
Respond with ONLY a valid JSON object (no markdown formatting) in this exact format:
{
"overallScore": 85,
"issues": [
{
"type": "Grammar",
"severity": "critical",
"originalText": "exact text with issue",
"description": "explanation of the issue",
"suggestion": "corrected version"
}
],
"readability": "Grade level or description",
"sentenceVariety": "Assessment of sentence structure variety",
"vocabularyLevel": "Assessment of vocabulary complexity",
"passiveVoiceUsage": 15,
"styleNotes": "Overall style assessment"
}`;
try {
const model = this.genAI.getGenerativeModel({ model: "gemini-2.0-flash" });
const result = await model.generateContent(prompt);
const response = await result.response;
const analysis = this.cleanAndParseResponse(response.text()) || {
overallScore: 75,
issues: [],
readability: "Analysis completed successfully",
sentenceVariety: "Standard variety observed",
vocabularyLevel: "Appropriate for intended audience",
passiveVoiceUsage: 0,
styleNotes: "Text analyzed for style and structure"
};
return { success: true, analysis };
} catch (error) {
throw new Error(`Grammar check failed: ${error.message}`);
}
}
// Character analysis and development
async analyzeCharacter(text, characterName, analysisType) {
if (this.usingBackend) {
return await this.requestBackend('/api/character/analyze', {
text,
characterName,
analysisType,
});
}
if (!this.genAI) {
throw new Error('API key not set');
}
let analysisPrompt;
switch (analysisType) {
case 'voice':
analysisPrompt = 'Analyze the character\'s unique voice, speech patterns, vocabulary, and dialogue style';
break;
case 'development':
analysisPrompt = 'Analyze character development, growth, motivations, and character arc';
break;
case 'consistency':
analysisPrompt = 'Check for consistency in character behavior, voice, and personality traits';
break;
case 'dialogue':
analysisPrompt = 'Focus on dialogue quality, authenticity, and character-specific speech patterns';
break;
case 'backstory':
analysisPrompt = 'Analyze implied backstory and suggest areas for character depth';
break;
}
const prompt = `Analyze the character "${characterName}" in the following text.
Focus: ${analysisPrompt}
Text: "${text}"
Respond with ONLY a valid JSON object (no markdown formatting) in this exact format:
{
"traits": ["trait1", "trait2", "trait3"],
"voiceTone": "description of speaking style",
"speechPattern": "characteristic speech patterns",
"vocabularyLevel": "assessment of vocabulary used",
"emotionalRange": "range of emotions displayed",
"developmentNotes": "character development observations",
"inconsistencies": ["issue1", "issue2"],
"strengths": ["strength1", "strength2"],
"improvementAreas": ["area1", "area2"]
}`;
try {
const model = this.genAI.getGenerativeModel({ model: "gemini-2.0-flash" });
const result = await model.generateContent(prompt);
const response = await result.response;
const analysis = this.cleanAndParseResponse(response.text()) || {
traits: ["Character analyzed"],
voiceTone: "Analysis completed successfully",
speechPattern: "Patterns identified",
vocabularyLevel: "Appropriate level",
emotionalRange: "Emotions observed",
developmentNotes: "Character development noted",
inconsistencies: [],
strengths: ["Character strengths identified"],
improvementAreas: ["Areas for development noted"]
};
return { success: true, analysis };
} catch (error) {
throw new Error(`Character analysis failed: ${error.message}`);
}
}
// Generate character enhancement suggestions
async generateCharacterSuggestions(characterName, traits, focusArea) {
if (this.usingBackend) {
return await this.requestBackend('/api/character/suggestions', {
characterName,
traits,
focusArea,
});
}
if (!this.genAI) {
throw new Error('API key not set');
}
const prompt = `Generate creative enhancement suggestions for the character "${characterName}" with traits: ${traits.join(', ')}.
Focus area: ${focusArea}
Provide practical, creative suggestions for character development.
Respond with ONLY a valid JSON array (no markdown formatting) in this exact format:
[
{
"category": "Dialogue",
"description": "detailed suggestion",
"example": "example implementation"
}
]`;
try {
const model = this.genAI.getGenerativeModel({ model: "gemini-2.0-flash" });
const result = await model.generateContent(prompt);
const response = await result.response;
let suggestions = this.cleanAndParseResponse(response.text());
if (!Array.isArray(suggestions)) {
suggestions = [
{
category: "General Development",
description: "Character enhancement suggestions generated",
example: "See detailed analysis for specific recommendations"
}
];
}
return { success: true, suggestions };
} catch (error) {
throw new Error(`Character suggestions failed: ${error.message}`);
}
}
// Plot structure analysis
async analyzePlotStructure(text, plotType, directives = '') {
if (this.usingBackend) {
return await this.requestBackend('/api/plot/analyze', { text, plotType, directives });
}
if (!this.genAI) {
throw new Error('API key not set');
}
let structureGuide;
switch (plotType) {
case 'three-act':
structureGuide = 'Three-Act Structure: Setup (25%), Confrontation (50%), Resolution (25%)';
break;
case 'heros-journey':
structureGuide = "Hero's Journey: Ordinary World, Call to Adventure, Refusal, Meeting Mentor, Crossing Threshold, Tests, Ordeal, Reward, Road Back, Resurrection, Return";
break;
case 'seven-point':
structureGuide = 'Seven-Point Structure: Hook, Plot Turn 1, Pinch Point 1, Midpoint, Pinch Point 2, Plot Turn 2, Resolution';
break;
case 'freytag':
structureGuide = "Freytag's Pyramid: Exposition, Rising Action, Climax, Falling Action, Denouement";
break;
case 'fichtean':
structureGuide = 'Fichtean Curve: Series of crises building to climax';
break;
default:
structureGuide = 'Custom analysis of narrative structure';
}
const directiveText = directives?.trim()
? `Additional directives for chapter planning: ${directives.trim()}\n\n`
: '';
const prompt = `Analyze the plot structure of the following story using ${structureGuide}.
Text: "${text}"
${directiveText}Follow any explicit directives about chapter count or focus. If none are provided, produce a 12-chapter outline that fully covers the narrative arc.
Deliver:
1. A structure analysis highlighting acts/stages, turning points, pacing, conflict, character arcs, themes, and actionable recommendations.
2. A chapter layout that distributes the story across the requested or default chapter count. Each chapter must include purpose, primary conflict/tension, and hooks, and should go beyond summarizing an act.
Respond with ONLY a valid JSON object (no markdown formatting) in this exact format:
{
"analysis": {
"overallScore": 85,
"structureSummary": "one paragraph overview",
"stages": [
{
"name": "Act I – Setup",
"focus": "what this stage accomplishes",
"progressPercent": 25,
"keyBeats": ["inciting incident", "turning point"],
"notes": "analysis of strengths and risks"
}
],
"pacing": "assessment of story pacing",
"conflict": "analysis of central conflict",
"characterArc": "character development assessment",
"themeDevelopment": "theme analysis",
"themes": ["theme1", "theme2"],
"recommendations": [
{
"priority": "high",
"title": "recommendation title",
"description": "detailed recommendation"
}
]
},
"chapterLayout": [
{
"number": 1,
"title": "Chapter title",
"summary": "short synopsis",
"purpose": "narrative purpose",
"conflict": "primary tension",
"hooks": ["hook1"],
"tags": ["setup", "character"]
}
]
}`;
try {
const model = this.genAI.getGenerativeModel({ model: "gemini-2.0-flash" });
const result = await model.generateContent(prompt);
const response = await result.response;
const parsed = this.cleanAndParseResponse(response.text());
const analysis = parsed?.analysis || {
overallScore: 75,
structureSummary: 'Plot structure analyzed successfully',
stages: [
{
name: 'Structure Analysis',
focus: 'Overview of acts and turning points',
progressPercent: 75,
keyBeats: ['Inciting Incident', 'Climax'],
notes: 'Continue developing your story structure'
}
],
pacing: 'Pacing analysis completed',
conflict: 'Conflict development noted',
characterArc: 'Character development observed',
themeDevelopment: 'Themes identified',
themes: ['Perseverance'],
recommendations: [
{
priority: 'medium',
title: 'General Development',
description: 'Continue refining your plot structure'
}
]
};
const layout = Array.isArray(parsed?.chapterLayout)
? parsed.chapterLayout
: Array.isArray(parsed?.chapters)
? parsed.chapters
: [];
return { success: true, analysis, chapters: layout };
} catch (error) {
throw new Error(`Plot analysis failed: ${error.message}`);
}
}
// NEW: Manuscript Manager
async analyzeManuscript(chapters) {
if (this.usingBackend) {
return await this.requestBackend('/api/manuscript/analyze', { chapters });
}
if (!this.genAI) {
throw new Error('API key not set');
}
const prompt = `Analyze this manuscript structure and provide insights:
Chapters: ${JSON.stringify(chapters)}
Respond with ONLY a valid JSON object (no markdown formatting) in this exact format:
{
"overallProgress": 65,
"totalWordCount": 50000,
"averageChapterLength": 2500,
"paceAnalysis": "analysis of pacing across chapters",
"consistencyIssues": ["issue1", "issue2"],
"suggestions": ["suggestion1", "suggestion2"],
"readabilityScore": 85,
"chapterInsights": [
{
"chapterNumber": 1,
"strengths": ["strength1"],
"improvements": ["improvement1"],
"paceRating": "good"
}
]
}`;
try {
const model = this.genAI.getGenerativeModel({ model: "gemini-2.0-flash" });
const result = await model.generateContent(prompt);
const response = await result.response;
const analysis = this.cleanAndParseResponse(response.text()) || {
overallProgress: 0,
totalWordCount: 0,
averageChapterLength: 0,
paceAnalysis: "Analysis in progress",
consistencyIssues: [],
suggestions: ["Continue writing your manuscript"],
readabilityScore: 75,
chapterInsights: []
};
return { success: true, analysis };
} catch (error) {
throw new Error(`Manuscript analysis failed: ${error.message}`);
}
}
// NEW: Scene Builder
async analyzeScene(sceneText, sceneType) {
if (this.usingBackend) {
return await this.requestBackend('/api/scene/analyze', { sceneText, sceneType });
}
if (!this.genAI) {
throw new Error('API key not set');
}
const prompt = `Analyze this scene for conflict, tension, and effectiveness:
Scene Type: ${sceneType}
Scene Text: "${sceneText}"
Respond with ONLY a valid JSON object (no markdown formatting) in this exact format:
{
"conflictLevel": 85,
"tensionRating": 90,
"paceRating": 75,
"dialogueQuality": 80,
"characterDevelopment": 70,
"conflictTypes": ["internal", "external"],
"tensionTechniques": ["technique1", "technique2"],
"strengths": ["strength1", "strength2"],
"improvements": ["improvement1", "improvement2"],
"suggestions": [
{
"type": "Conflict",
"description": "suggestion description",
"example": "example implementation"
}
]
}`;
try {
const model = this.genAI.getGenerativeModel({ model: "gemini-2.0-flash" });
const result = await model.generateContent(prompt);
const response = await result.response;
const analysis = this.cleanAndParseResponse(response.text()) || {
conflictLevel: 50,
tensionRating: 50,
paceRating: 50,
dialogueQuality: 50,
characterDevelopment: 50,
conflictTypes: ["general"],
tensionTechniques: ["basic tension"],
strengths: ["Scene analyzed"],
improvements: ["Continue developing"],
suggestions: [
{
type: "General",
description: "Scene analysis completed",
example: "Continue refining your scene"
}
]
};
return { success: true, analysis };
} catch (error) {
throw new Error(`Scene analysis failed: ${error.message}`);
}
}
async generateChapterDraft({ chapterTitle, outline, scenes, directives, mainCharacters = [], supportingCharacters = [] }) {
if (!Array.isArray(scenes) || scenes.length === 0) {
throw new Error('At least one scene is required to compose a chapter draft.');
}
const characterBlock = buildCharacterBlock(mainCharacters, supportingCharacters);
if (this.usingBackend) {
return await this.requestBackend('/api/chapter/draft', {
chapterTitle,
outline,
scenes: scenes.map((scene, index) => ({
title: scene.title || `Scene ${index + 1}`,
type: scene.type || scene.sceneType || 'general',
text: scene.text || '',
notes: scene.notes || '',
})),
directives,
mainCharacters: characterBlock.main,
supportingCharacters: characterBlock.supporting,
});
}
const fallbackDraft = {
title: chapterTitle,
summary: outline || 'Draft generated from available scenes.',
sections: scenes.map((scene, index) => ({
heading: scene.title || `Scene ${index + 1}`,
objective: scene.notes || '',
beats: [],
text: (scene.text && scene.text.trim()) ? [scene.text.trim()] : [],
})),
styleNotes: directives ? [directives] : [
'Draft assembled locally from scene text. Consider refining with the hosted backend for richer output.',
],
};
const fallbackPrompt = `${characterBlock.text}Compose a chapter draft for "${chapterTitle}" using the provided scenes.`;
const fallbackPreview = JSON.stringify(fallbackDraft).slice(0, 400);
return { success: true, draft: fallbackDraft, prompt: fallbackPrompt, responsePreview: fallbackPreview };
}
async generateScenePlan({ chapterTitle, outline, desiredScenes, directives, sceneFocus, mainCharacters = [], supportingCharacters = [] }) {
if (!outline || !outline.trim()) {
throw new Error('A chapter outline is required to plan scenes.');
}
const characterBlock = buildCharacterBlock(mainCharacters, supportingCharacters);
if (this.usingBackend) {
return await this.requestBackend('/api/scene/plan', {
chapterTitle,
chapterOutline: outline,
desiredScenes,
directives,
sceneFocus,
mainCharacters: characterBlock.main,
supportingCharacters: characterBlock.supporting,
});
}
const outlineLines = outline.split('\n').map(line => line.trim()).filter(Boolean);
const totalScenes = desiredScenes || Math.max(3, Math.min(outlineLines.length, 6));
const scenes = Array.from({ length: totalScenes }).map((_, index) => {
const snippet = outlineLines[index] || outlineLines[outlineLines.length - 1] || outline;
return {
title: `${chapterTitle || 'Chapter'} – Scene ${index + 1}`,
type: 'general',
summary: snippet,
purpose: 'Advance the chapter narrative.',
beats: [],
notes: directives || '',
tone: '',
length: 'medium',
setting: '',
};
});
const fallbackPrompt = `${characterBlock.text}Outline ${totalScenes} scenes for chapter "${chapterTitle || 'Untitled'}" based on the provided outline.`;
const fallbackPreview = scenes.map(scene => scene.title).join(', ').slice(0, 400);
return { success: true, scenes, prompt: fallbackPrompt, responsePreview: fallbackPreview };
}
async refineSceneText({ mode = 'expand', sceneTitle, sceneText, chapterTitle, chapterOutline, directives, targetWords, mainCharacters = [], supportingCharacters = [] }) {
if (!sceneText || !sceneText.trim()) {
throw new Error('Scene text is required to refine.');
}
const characterBlock = buildCharacterBlock(mainCharacters, supportingCharacters);
if (this.usingBackend) {
return await this.requestBackend('/api/scene/refine', {
mode,
sceneTitle,
sceneText,
chapterTitle,
chapterOutline,
directives,
targetWords,
mainCharacters: characterBlock.main,
supportingCharacters: characterBlock.supporting,
});
}
const words = sceneText.split(/\s+/).filter(Boolean);
let text;
if (mode === 'tighten') {
const keep = Math.max(1, Math.floor(words.length * 0.75));
text = words.slice(0, keep).join(' ');
} else {
text = `${sceneText}\n\n[Expand this scene with richer detail when connected to the backend.]`;
}
const fallbackPrompt = `${characterBlock.text}${mode === 'tighten' ? 'Tighten' : 'Expand'} the scene "${sceneTitle}".`;
const fallbackPreview = text.slice(0, 400);
return {
success: true,
scene: {
title: sceneTitle,
text,
beats: [],
notes: directives || '',
},
prompt: fallbackPrompt,
responsePreview: fallbackPreview,
};
}
// NEW: Readability Optimizer
async analyzeReadability(text, targetAudience) {
if (this.usingBackend) {
return await this.requestBackend('/api/readability/analyze', { text, targetAudience });
}
if (!this.genAI) {
throw new Error('API key not set');
}
const prompt = `Analyze the readability of this text for target audience: ${targetAudience}
Text: "${text}"
Respond with ONLY a valid JSON object (no markdown formatting) in this exact format:
{
"readabilityScore": 85,
"gradeLevel": "8th Grade",
"targetMatch": true,
"wordComplexity": "appropriate",
"sentenceLength": "good",
"vocabularyLevel": "suitable",
"improvements": [
{
"issue": "issue description",
"suggestion": "how to fix",
"example": "example fix"
}
],
"strengths": ["strength1", "strength2"],
"optimizedVersion": "optimized text version"
}`;
try {
const model = this.genAI.getGenerativeModel({ model: "gemini-2.0-flash" });
const result = await model.generateContent(prompt);
const response = await result.response;
const analysis = this.cleanAndParseResponse(response.text()) || {
readabilityScore: 75,
gradeLevel: "General Adult",
targetMatch: true,
wordComplexity: "appropriate",
sentenceLength: "good",
vocabularyLevel: "suitable",
improvements: [
{
issue: "Analysis completed",
suggestion: "Continue refining text",
example: "Keep developing your writing"
}
],
strengths: ["Text analyzed successfully"],
optimizedVersion: text
};
return { success: true, analysis };
} catch (error) {
throw new Error(`Readability analysis failed: ${error.message}`);
}
}
// Existing methods with improved response handling...
async paraphraseText(text, mode, customPrompt = '') {
if (this.usingBackend) {
return await this.requestBackend('/api/paraphrase', { text, mode, customPrompt });
}
if (!this.genAI) {
throw new Error('API key not set. Please configure your Gemini API key.');
}
let prompt;
switch (mode) {
case 'Formal':
prompt = `Rewrite the following text in a formal, professional tone while maintaining the original meaning. Provide ONLY the rewritten text without explanations: "${text}"`;
break;
case 'Academic':
prompt = `Rewrite the following text in an academic, scholarly style with appropriate terminology. Provide ONLY the rewritten text: "${text}"`;
break;
case 'Simple':
prompt = `Simplify the following text to make it easier to read and understand. Provide ONLY the simplified text: "${text}"`;
break;
case 'Creative':
prompt = `Creatively rewrite the following text with fresh, original phrasing and style. Provide ONLY the creative version: "${text}"`;
break;
case 'Shorten':
prompt = `Condense the following text while retaining all main points. Provide ONLY the shortened text: "${text}"`;
break;
case 'Expand':
prompt = `Expand the following text by adding more detail and elaboration. Provide ONLY the expanded text: "${text}"`;
break;
case 'Custom':
prompt = `${customPrompt}. Provide ONLY the result: "${text}"`;
break;
default:
prompt = `Paraphrase the following text. Provide ONLY the paraphrased version: "${text}"`;
}
try {
const model = this.genAI.getGenerativeModel({ model: "gemini-2.0-flash" });
const result = await model.generateContent(prompt);
const response = await result.response;
const paraphrasedText = response.text().trim();
return {
success: true,
result: paraphrasedText,
originalLength: text.length,
newLength: paraphrasedText.length
};
} catch (error) {
throw new Error(`Paraphrasing failed: ${error.message}`);
}
}
async summarizeText(text, length = 'medium') {
if (this.usingBackend) {
return await this.requestBackend('/api/summarize', { text, length });
}
if (!this.genAI) {
throw new Error('API key not set');
}
let prompt;
switch (length) {
case 'short':
prompt = `Provide a brief summary (2-3 sentences) of the following text. Provide ONLY the summary: "${text}"`;
break;
case 'long':
prompt = `Provide a detailed summary with key points and supporting details. Provide ONLY the summary: "${text}"`;
break;
default:
prompt = `Provide a concise summary of the following text. Provide ONLY the summary: "${text}"`;
}
try {
const model = this.genAI.getGenerativeModel({ model: "gemini-2.0-flash" });
const result = await model.generateContent(prompt);
const response = await result.response;
const summary = response.text().trim();
return {
success: true,
summary,
originalLength: text.length,
summaryLength: summary.length,
compressionRatio: ((text.length - summary.length) / text.length * 100).toFixed(1)
};
} catch (error) {
throw new Error(`Summarization failed: ${error.message}`);
}
}
async analyzeTone(text) {
if (this.usingBackend) {
return await this.requestBackend('/api/analyze-tone', { text });
}
if (!this.genAI) {
throw new Error('API key not set');
}
const prompt = `Analyze the tone of the following text.
Text: "${text}"
Respond with ONLY a valid JSON object (no markdown formatting) in this exact format:
{
"overallTone": "description",
"sentiment": "positive",
"confidence": "high",
"emotions": ["emotion1", "emotion2"],
"suggestions": "improvement suggestions"
}`;
try {
const model = this.genAI.getGenerativeModel({ model: "gemini-2.0-flash" });
const result = await model.generateContent(prompt);
const response = await result.response;
const analysis = this.cleanAndParseResponse(response.text()) || {
overallTone: "Neutral tone detected",
sentiment: "neutral",
confidence: "medium",
emotions: ["general"],
suggestions: "Tone analysis completed successfully"
};
return { success: true, analysis };
} catch (error) {
throw new Error(`Tone analysis failed: ${error.message}`);
}
}
async getSynonyms(word, context) {
if (this.usingBackend) {
return await this.requestBackend('/api/synonyms', { word, context });
}
if (!this.genAI) {
throw new Error('API key not set');
}
const prompt = `Provide 8 synonyms for the word "${word}" in this context: "${context}".
Return ONLY a JSON array of synonyms: ["synonym1", "synonym2", "synonym3", "synonym4", "synonym5", "synonym6", "synonym7", "synonym8"]`;
try {
const model = this.genAI.getGenerativeModel({ model: "gemini-2.0-flash" });
const result = await model.generateContent(prompt);
const response = await result.response;
let synonyms = this.cleanAndParseResponse(response.text());
if (!Array.isArray(synonyms)) {
synonyms = response.text().split(',').map(s => s.trim().replace(/['"]/g, '')).slice(0, 8);
}
return { success: true, synonyms };
} catch (error) {
throw new Error(`Synonyms failed: ${error.message}`);
}
}
async humanizeText(text) {
if (this.usingBackend) {
return await this.requestBackend('/api/humanize', { text });
}
if (!this.genAI) {
throw new Error('API key not set');
}
const prompt = `Make the following AI-generated text sound more natural and human-written. Provide ONLY the humanized version without explanations:
Text: "${text}"`;
try {
const model = this.genAI.getGenerativeModel({ model: "gemini-2.0-flash" });
const result = await model.generateContent(prompt);
const response = await result.response;
return { success: true, result: response.text().trim() };
} catch (error) {
throw new Error(`Humanization failed: ${error.message}`);
}
}
// Script Breakdown Analysis
async analyzeScriptBreakdown(scriptText) {
if (this.usingBackend) {
return await this.requestBackend('/api/script/breakdown', { scriptText });
}
if (!this.genAI) {
throw new Error('API key not set');
}
const prompt = `Analyze this screenplay and identify production elements in these categories:
- props: Physical items handled or seen
- wardrobe: Clothing items and accessories
- cast: Character names
- locations: All settings and locations
- sfx: Sound effects and audio elements
- vehicles: Cars, trucks, planes, etc.
- animals: Any animals mentioned
- stunts: Physical action sequences
- makeup: Special makeup requirements
- equipment: Special filmmaking equipment needed
- extras: Background performers needed
Script:
"${scriptText}"
Respond with ONLY a valid JSON object (no markdown formatting) in this exact format:
{
"props": ["prop1", "prop2"],
"wardrobe": ["item1", "item2"],
"cast": ["character1", "character2"],
"locations": ["location1", "location2"],
"sfx": ["effect1", "effect2"],
"vehicles": ["vehicle1", "vehicle2"],
"animals": ["animal1", "animal2"],
"stunts": ["stunt1", "stunt2"],
"makeup": ["makeup1", "makeup2"],
"equipment": ["equipment1", "equipment2"],
"extras": ["extra1", "extra2"]
}`;
try {
const model = this.genAI.getGenerativeModel({ model: "gemini-2.0-flash" });
const result = await model.generateContent(prompt);
const response = await result.response;
const analysis = this.cleanAndParseResponse(response.text()) || {
props: [],
wardrobe: [],
cast: [],
locations: [],
sfx: [],
vehicles: [],
animals: [],
stunts: [],
makeup: [],
equipment: [],
extras: []