forked from cokice/japanese-analyzer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.html
More file actions
1079 lines (963 loc) · 49.6 KB
/
Copy pathtest.html
File metadata and controls
1079 lines (963 loc) · 49.6 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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>日本語文章解析器 - AI驱动</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Noto+Sans+JP:wght@400;500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<style>
body {
font-family: 'Inter', 'Noto Sans JP', sans-serif;
background-color: #f0f2f5;
}
.premium-card {
background-color: white;
border-radius: 12px;
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
padding: 2rem;
margin-bottom: 1.5rem;
}
.premium-button {
padding: 0.75rem 1.5rem;
border-radius: 8px;
font-weight: 500;
transition: all 0.3s ease;
display: inline-flex;
align-items: center;
justify-content: center;
}
.premium-button-primary {
background-color: #007AFF; /* Apple Blue */
color: white;
}
.premium-button-primary:hover {
background-color: #005ecb;
}
.premium-button-secondary {
background-color: #5856D6; /* Apple Indigo */
color: white;
}
.premium-button-secondary:hover {
background-color: #3938AC;
}
.premium-button-outlined {
background-color: transparent;
color: #007AFF;
border: 1px solid #007AFF;
}
.premium-button-outlined:hover {
background-color: rgba(0, 122, 255, 0.1);
}
.premium-button-success {
background-color: #34C759; /* Apple Green */
color: white;
}
.premium-button-success:hover {
background-color: #2ea14a;
}
#analyzedSentenceOutput {
line-height: 3.0;
padding-top: 0.6em;
word-spacing: 0.2em;
}
.word-unit-wrapper {
display: inline-flex;
flex-direction: column;
align-items: center;
margin: 0 2px;
padding: 0;
vertical-align: baseline;
position: relative;
}
.word-token {
position: relative;
display: inline-block;
padding: 0 2px;
padding-bottom: 2px;
font-size: 1.2rem;
color: #2c3e50;
cursor: pointer;
transition: color 0.2s ease;
line-height: 1;
}
.word-token::after {
content: '';
position: absolute;
left: 5%;
right: 5%;
width: 90%;
bottom: -2px;
height: 3px;
background-color: transparent;
border-radius: 1.5px;
transition: background-color 0.2s ease;
}
.word-token.pos-名詞::after { background-color: #89CFF0; }
.word-token.pos-動詞::after { background-color: #77DD77; }
.word-token.pos-形容詞::after { background-color: #FFB347; }
.word-token.pos-副詞::after { background-color: #C3B1E1; }
.word-token.pos-助詞::after { background-color: #FF6961; }
.word-token.pos-助動詞::after { background-color: #FF8FAB; }
.word-token.pos-接続詞::after { background-color: #D2B48C; }
.word-token.pos-感動詞::after { background-color: #AEC6CF; }
.word-token.pos-連体詞::after { background-color: #7FFFD4; }
.word-token.pos-代名詞::after { background-color: #ADD8E6; }
.word-token.pos-形状詞::after { background-color: #FDFD96; }
.word-token.pos-記号::after { background-color: transparent !important; }
.word-token.pos-接頭辞::after { background-color: #DCDCDC; }
.word-token.pos-接尾辞::after { background-color: #E6E6FA; }
.word-token.pos-フィラー::after { background-color: #F5F5F5; }
.word-token.pos-その他::after { background-color: #C0C0C0; }
.word-token.pos-default::after { background-color: #E0E0E0; }
ruby {
ruby-position: over;
text-align: center;
}
rt {
font-size: 0.6em;
color: #555;
user-select: none;
line-height: 1.1;
text-align: center;
}
rb {
font-size: 1em;
line-height: 1.2;
text-align: center;
}
.romaji-text {
font-size: 0.7em;
color: #7f8c8d;
margin-top: 3px;
line-height: 1.1;
user-select: none;
text-align: center;
width: 100%;
}
.loading-spinner {
border: 4px solid rgba(0, 0, 0, 0.1);
border-left-color: #007AFF;
border-radius: 50%;
width: 24px;
height: 24px;
animation: spin 1s linear infinite;
margin-right: 8px;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.word-token.active-word {
font-weight: 600;
}
.word-token.active-word::after {
height: 4px;
bottom: -3px;
}
#wordDetailInlineContainer {
background-color: #ffffff;
border: 1px solid #e0e0e0;
border-radius: 10px;
padding: 1.5rem;
margin-top: 1rem;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
animation: slideDownFadeIn 0.3s ease-out;
position: relative;
}
#wordDetailInlineContainer .detail-close-button {
position: absolute;
top: 10px;
right: 10px;
background: #e5e5ea;
color: #8e8e93;
border: none;
border-radius: 50%;
width: 28px;
height: 28px;
font-size: 18px;
line-height: 28px;
text-align: center;
cursor: pointer;
transition: background-color 0.2s, color 0.2s;
}
#wordDetailInlineContainer .detail-close-button:hover {
background-color: #d1d1d6;
color: #000;
}
.read-aloud-button {
background: none;
border: none;
color: #007AFF;
cursor: pointer;
font-size: 1.1em;
padding: 0 0.3em;
margin-left: 0.3em;
vertical-align: middle;
}
.read-aloud-button:hover {
color: #005ecb;
}
@keyframes slideDownFadeIn {
from { opacity: 0; transform: translateY(-10px); }
to { opacity: 1; transform: translateY(0); }
}
.detail-pos-tag {
display: inline-block;
padding: 0.25em 0.7em;
font-size: 0.9em;
font-weight: 600;
line-height: 1;
color: #333;
text-align: center;
white-space: nowrap;
vertical-align: baseline;
border-radius: 0.3rem;
border: 1px solid;
background-color: #f8f9fa;
}
.detail-pos-tag.pos-名詞 { border-color: #89CFF0; }
.detail-pos-tag.pos-動詞 { border-color: #77DD77; }
.detail-pos-tag.pos-形容詞 { border-color: #FFB347; }
.detail-pos-tag.pos-副詞 { border-color: #C3B1E1; }
.detail-pos-tag.pos-助詞 { border-color: #FF6961; }
.detail-pos-tag.pos-助動詞 { border-color: #FF8FAB; }
.detail-pos-tag.pos-接続詞 { border-color: #D2B48C; }
.detail-pos-tag.pos-感動詞 { border-color: #AEC6CF; }
.detail-pos-tag.pos-連体詞 { border-color: #7FFFD4; }
.detail-pos-tag.pos-代名詞 { border-color: #ADD8E6; }
.detail-pos-tag.pos-形状詞 { border-color: #FDFD96; }
.detail-pos-tag.pos-記号 { border-color: #B2BEB5; }
.detail-pos-tag.pos-接頭辞 { border-color: #DCDCDC; }
.detail-pos-tag.pos-接尾辞 { border-color: #E6E6FA; }
.detail-pos-tag.pos-フィラー { border-color: #F5F5F5; }
.detail-pos-tag.pos-その他 { border-color: #C0C0C0; }
.detail-pos-tag.pos-default { border-color: #E0E0E0; }
.tooltip {
}
.tooltip .tooltiptext {
visibility: hidden;
width: auto;
min-width: 80px;
background-color: rgba(0,0,0,0.8);
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 8px;
position: absolute;
z-index: 20;
bottom: 105%;
left: 50%;
transform: translateX(-50%);
opacity: 0;
transition: opacity 0.2s ease-in-out, visibility 0.2s ease-in-out;
font-size: 0.8rem;
white-space: nowrap;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
#imageUploadStatus, #settingsStatus { /* Updated ID for settings status */
font-size: 0.9em;
color: #555;
margin-top: 0.5rem;
min-height: 1.2em;
}
/* Settings Modal Styles */
.settings-modal {
display: none; /* Hidden by default */
position: fixed;
z-index: 1001; /* Higher than other elements */
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.4);
justify-content: center;
align-items: center;
}
.settings-modal-content {
background-color: #fff;
margin: auto;
padding: 25px;
border-radius: 10px;
box-shadow: 0 5px 15px rgba(0,0,0,0.3);
width: 90%;
max-width: 450px; /* Adjusted width */
animation: fadeInModal 0.3s;
}
@keyframes fadeInModal {
from {opacity: 0; transform: translateY(-20px) scale(0.98);}
to {opacity: 1; transform: translateY(0) scale(1);}
}
.settings-modal-close-button {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
cursor: pointer;
line-height: 1;
}
.settings-modal-close-button:hover,
.settings-modal-close-button:focus {
color: black;
text-decoration: none;
}
#settingsButton {
position: fixed;
top: 1.5rem;
right: 1.5rem;
z-index: 1000;
background-color: white;
color: #007AFF;
border: 1px solid #007AFF;
border-radius: 50%;
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
cursor: pointer;
transition: all 0.2s ease;
}
#settingsButton:hover {
background-color: #f0f2f5;
transform: scale(1.1);
}
</style>
</head>
<body class="min-h-screen flex flex-col items-center justify-start pt-8 sm:pt-12 lg:pt-16 p-4">
<button id="settingsButton" title="API 设置">
<i class="fas fa-cog"></i>
</button>
<div id="settingsModal" class="settings-modal">
<div class="settings-modal-content">
<span id="closeSettingsModal" class="settings-modal-close-button">×</span>
<h3 class="text-xl font-semibold text-gray-700 mb-4">API 设置</h3>
<div class="mb-4">
<label for="modalApiKeyInput" class="block text-sm font-medium text-gray-700 mb-1">Gemini API 密钥:</label>
<input type="password" id="modalApiKeyInput" class="w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500" placeholder="输入您的 API 密钥">
</div>
<div class="mb-4">
<label for="modalApiUrlInput" class="block text-sm font-medium text-gray-700 mb-1">自定义 API URL (OpenAI 兼容):</label>
<input type="text" id="modalApiUrlInput" class="w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500" placeholder="例如: https://generativelanguage.googleapis.com/v1beta/openai/chat/completions">
<p class="text-xs text-gray-500 mt-1">留空则使用默认端点。</p>
</div>
<button id="saveSettingsButton" class="premium-button premium-button-success w-full">
<i class="fas fa-save mr-2"></i>保存设置
</button>
<div id="settingsStatus" class="mt-3 text-sm"></div>
</div>
</div>
<div class="w-full max-w-3xl">
<header class="text-center mb-8 mt-16"> <h1 class="text-4xl font-bold text-gray-800">日本語<span class="text-[#007AFF]">文章</span>解析器</h1>
<p class="text-lg text-gray-600 mt-2">AI驱动・深入理解日语句子结构与词义</p>
</header>
<main>
<div class="premium-card">
<h2 class="text-2xl font-semibold text-gray-700 mb-4">输入日语句子</h2>
<textarea id="japaneseInput" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#007AFF] focus:border-[#007AFF] transition duration-150 ease-in-out resize-none" rows="4" placeholder="例:今日はいい天気ですね。或上传图片识别文字。"></textarea>
<div class="mt-4 flex flex-col sm:flex-row sm:items-center sm:justify-between">
<input type="file" id="imageUploadInput" accept="image/*" class="hidden">
<button id="uploadImageButton" class="premium-button premium-button-secondary w-full sm:w-auto mb-3 sm:mb-0 sm:order-1">
<i class="fas fa-camera mr-2"></i>
<span class="button-text">上传图片提取文字</span>
<div class="loading-spinner" style="display: none;"></div>
</button>
<button id="analyzeButton" class="premium-button premium-button-primary w-full sm:w-auto sm:order-2">
<span class="button-text">解析句子</span>
<div class="loading-spinner" style="display: none;"></div>
</button>
</div>
<div id="imageUploadStatus" class="mt-2 text-sm text-gray-600"></div>
</div>
<div id="analysisResultCard" class="premium-card" style="display: none;">
<h2 class="text-2xl font-semibold text-gray-700 mb-4">解析结果</h2>
<div id="analyzedSentenceOutput" class="text-gray-800 mb-2 p-3 bg-gray-50 rounded-lg min-h-[70px]">
</div>
<div id="wordDetailInlineContainer" style="display: none;">
</div>
<p class="text-sm text-gray-500 italic mt-3">点击词汇查看详细释义。悬停词汇可查看词性。</p>
</div>
<div id="fullTranslationCard" class="premium-card" style="display: none;">
<div class="flex justify-between items-center mb-3">
<h2 class="text-2xl font-semibold text-gray-700">全文翻译 (中)</h2>
<button id="toggleFullTranslationButton" class="premium-button premium-button-outlined text-sm px-3 py-1">
隐藏
</button>
</div>
<div id="fullTranslationOutput" class="text-gray-800 p-3 bg-gray-50 rounded-lg min-h-[50px]">
</div>
</div>
<div class="mt-6 flex flex-col sm:flex-row sm:justify-center space-y-3 sm:space-y-0 sm:space-x-4">
<button id="translateSentenceButton" class="premium-button premium-button-primary w-full sm:w-auto"> <span class="button-text">翻译整句</span>
<div class="loading-spinner" style="display: none;"></div>
</button>
</div>
</main>
<footer class="text-center mt-12 py-6 border-t border-gray-200">
<p class="text-gray-500 text-sm">© 2025 高级日语解析工具. All rights reserved.</p>
<p class="text-gray-400 text-xs mt-1">Powered by Gemini AI</p>
</footer>
</div>
<script>
const japaneseInput = document.getElementById('japaneseInput');
const analyzeButton = document.getElementById('analyzeButton');
const analyzedSentenceOutput = document.getElementById('analyzedSentenceOutput');
const analysisResultCard = document.getElementById('analysisResultCard');
const wordDetailInlineContainer = document.getElementById('wordDetailInlineContainer');
const translateSentenceButton = document.getElementById('translateSentenceButton');
const fullTranslationCard = document.getElementById('fullTranslationCard');
const fullTranslationOutput = document.getElementById('fullTranslationOutput');
const toggleFullTranslationButton = document.getElementById('toggleFullTranslationButton');
const imageUploadInput = document.getElementById('imageUploadInput');
const uploadImageButton = document.getElementById('uploadImageButton');
const imageUploadStatus = document.getElementById('imageUploadStatus');
// Settings Modal Elements
const settingsButton = document.getElementById('settingsButton');
const settingsModal = document.getElementById('settingsModal');
const closeSettingsModalButton = document.getElementById('closeSettingsModal');
const modalApiKeyInput = document.getElementById('modalApiKeyInput');
const modalApiUrlInput = document.getElementById('modalApiUrlInput');
const saveSettingsButton = document.getElementById('saveSettingsButton');
const settingsStatus = document.getElementById('settingsStatus');
const modelName = "gemini-2.5-flash-preview-05-20";
const defaultOpenAiCompatibleBaseUrl = "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions";
let userProvidedApiKey = localStorage.getItem('userGeminiApiKey') || "";
let userProvidedApiUrl = localStorage.getItem('userGeminiApiUrl') || defaultOpenAiCompatibleBaseUrl;
function getApiKeyForRequest() {
return userProvidedApiKey;
}
function getApiUrlForRequest() {
return userProvidedApiUrl || defaultOpenAiCompatibleBaseUrl;
}
const posChineseMap = {
"名詞": "名词", "動詞": "动词", "形容詞": "形容词", "副詞": "副词",
"助詞": "助词", "助動詞": "助动词", "接続詞": "接续词", "感動詞": "感动词",
"連体詞": "连体词", "代名詞": "代名词", "形状詞": "形容动词", "記号": "符号",
"接頭辞": "接头辞", "接尾辞": "接尾辞", "フィラー": "填充词", "その他": "其他",
"default": "未知词性"
};
let currentActiveWordTokenElement = null;
function containsKanji(text) {
const kanjiRegex = /[\u4E00-\u9FAF\u3400-\u4DBF]/;
return kanjiRegex.test(text);
}
function showLoading(button, text = "处理中...") {
const buttonTextEl = button.querySelector('.button-text');
if (buttonTextEl) {
buttonTextEl.style.display = 'none';
} else {
button.childNodes.forEach(node => {
if (node.nodeType === Node.TEXT_NODE) node.nodeValue = '';
});
}
const loadingSpinner = button.querySelector('.loading-spinner');
if (loadingSpinner) loadingSpinner.style.display = 'inline-block';
button.disabled = true;
}
function hideLoading(button, originalText = "解析句子") {
const buttonTextEl = button.querySelector('.button-text');
if (buttonTextEl) {
buttonTextEl.textContent = originalText;
buttonTextEl.style.display = 'inline-block';
} else {
button.childNodes.forEach(node => {
if (node.nodeType === Node.TEXT_NODE && node.nodeValue === '') node.nodeValue = originalText;
});
}
const loadingSpinner = button.querySelector('.loading-spinner');
if(loadingSpinner) loadingSpinner.style.display = 'none';
button.disabled = false;
}
function getPosClass(pos) {
const basePos = pos.split('-')[0];
const knownPos = ["名詞", "動詞", "形容詞", "副詞", "助詞", "助動詞", "接続詞", "感動詞", "連体詞", "代名詞", "形状詞", "記号", "接頭辞", "接尾辞", "フィラー", "その他"];
if (knownPos.includes(basePos)) {
return `pos-${basePos}`;
}
return 'pos-default';
}
// Settings Modal Logic
settingsButton.addEventListener('click', () => {
settingsModal.style.display = 'flex';
modalApiKeyInput.value = userProvidedApiKey;
modalApiUrlInput.value = userProvidedApiUrl === defaultOpenAiCompatibleBaseUrl ? '' : userProvidedApiUrl; // Show empty if default
settingsStatus.textContent = ''; // Clear previous status
});
closeSettingsModalButton.addEventListener('click', () => {
settingsModal.style.display = 'none';
});
window.addEventListener('click', (event) => {
if (event.target == settingsModal) {
settingsModal.style.display = 'none';
}
});
saveSettingsButton.addEventListener('click', () => {
const newApiKey = modalApiKeyInput.value.trim();
const newApiUrl = modalApiUrlInput.value.trim();
if (newApiKey) {
userProvidedApiKey = newApiKey;
localStorage.setItem('userGeminiApiKey', newApiKey);
} else {
userProvidedApiKey = ""; // Clear if input is empty
localStorage.removeItem('userGeminiApiKey');
}
if (newApiUrl) {
userProvidedApiUrl = newApiUrl;
localStorage.setItem('userGeminiApiUrl', newApiUrl);
} else {
userProvidedApiUrl = defaultOpenAiCompatibleBaseUrl; // Reset to default if empty
localStorage.removeItem('userGeminiApiUrl');
}
settingsStatus.textContent = '设置已保存!';
settingsStatus.className = 'mt-3 text-sm text-green-600';
setTimeout(() => { settingsModal.style.display = 'none'; }, 1500);
});
// Image Upload Logic
uploadImageButton.addEventListener('click', () => {
if (!getApiKeyForRequest()) {
settingsStatus.textContent = '请先在设置中填写API密钥以上传图片。';
settingsStatus.className = 'mt-3 text-sm text-red-600';
settingsModal.style.display = 'flex';
modalApiKeyInput.focus();
return;
}
imageUploadInput.click();
});
imageUploadInput.addEventListener('change', async (event) => {
const file = event.target.files[0];
if (!file) return;
if (!file.type.startsWith('image/')) {
imageUploadStatus.textContent = '请上传图片文件!';
imageUploadStatus.className = 'mt-2 text-sm text-red-600';
return;
}
showLoading(uploadImageButton, "提取中...");
imageUploadStatus.textContent = '正在上传并识别图片中的文字...';
imageUploadStatus.className = 'mt-2 text-sm text-gray-600';
const reader = new FileReader();
reader.onloadend = async () => {
const base64ImageData = reader.result.split(',')[1];
const currentApiKey = getApiKeyForRequest();
const currentApiUrl = getApiUrlForRequest();
if (!currentApiKey) {
imageUploadStatus.textContent = 'API密钥未设置,无法提取文字。';
imageUploadStatus.className = 'mt-2 text-sm text-red-600';
hideLoading(uploadImageButton, "上传图片提取文字");
return;
}
const imageExtractionPrompt = "请仅提取并返回这张图片中的所有日文文字。不要添加任何其他评论、解释或格式化。如果文字是多行或者分散的,请将它们合并成一个单一的文本字符串,用换行符(\\n)分隔不同的文本块(如果适用)。";
const payload = {
model: modelName,
reasoning_effort: "none",
messages: [
{
role: "user",
content: [
{ type: "text", text: imageExtractionPrompt },
{
type: "image_url",
image_url: {
url: `data:${file.type};base64,${base64ImageData}`
}
}
]
}
]
};
try {
const response = await fetch(currentApiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${currentApiKey}`
},
body: JSON.stringify(payload)
});
if (!response.ok) {
const errorData = await response.json();
console.error('API Error (Image Upload):', errorData);
imageUploadStatus.textContent = `文字提取失败:${errorData.error?.message || response.statusText || '未知错误'}`;
imageUploadStatus.className = 'mt-2 text-sm text-red-600';
return;
}
const result = await response.json();
if (result.choices && result.choices[0] && result.choices[0].message && result.choices[0].message.content) {
const extractedText = result.choices[0].message.content.trim();
japaneseInput.value = extractedText;
imageUploadStatus.textContent = '文字提取成功!请确认后点击“解析句子”。';
imageUploadStatus.className = 'mt-2 text-sm text-green-600';
} else {
imageUploadStatus.textContent = '未能从图片中提取到文字,或结果格式错误。';
imageUploadStatus.className = 'mt-2 text-sm text-orange-600';
console.error('Unexpected API response structure (Image Upload):', result);
}
} catch (error) {
console.error('Error during image text extraction:', error);
imageUploadStatus.textContent = `提取时发生错误: ${error.message}。`;
imageUploadStatus.className = 'mt-2 text-sm text-red-600';
} finally {
hideLoading(uploadImageButton, "上传图片提取文字");
imageUploadInput.value = '';
}
};
reader.readAsDataURL(file);
});
analyzeButton.addEventListener('click', async () => {
const sentence = japaneseInput.value.trim();
if (!sentence) {
alert('请输入日语句子!');
return;
}
const currentApiKey = getApiKeyForRequest();
const currentApiUrl = getApiUrlForRequest();
if (!currentApiKey) {
settingsStatus.textContent = '请先在设置中填写API密钥以解析句子。';
settingsStatus.className = 'mt-3 text-sm text-red-600';
settingsModal.style.display = 'flex';
modalApiKeyInput.focus();
return;
}
showLoading(analyzeButton, "解析中...");
analyzedSentenceOutput.innerHTML = '<div class="flex items-center justify-center py-4"><div class="loading-spinner"></div><span class="ml-2 text-gray-500">正在解析,请稍候...</span></div>';
analysisResultCard.style.display = 'block';
wordDetailInlineContainer.style.display = 'none';
const analysisPrompt = `请对以下日语句子进行详细的词法分析,并以JSON数组格式返回结果。每个对象应包含以下字段:"word", "pos", "furigana", "romaji"。确保输出是严格的JSON格式,不包含任何markdown或其他非JSON字符。
待解析句子: "${sentence}"`;
const payload = {
model: modelName,
reasoning_effort: "none",
messages: [{ role: "user", content: analysisPrompt }],
};
try {
const response = await fetch(currentApiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${currentApiKey}`
},
body: JSON.stringify(payload)
});
if (!response.ok) {
const errorData = await response.json();
console.error('API Error (Analysis):', errorData);
analyzedSentenceOutput.innerHTML = `<p class="text-red-500 p-3">解析失败:${errorData.error?.message || response.statusText || '未知错误'}</p>`;
return;
}
const result = await response.json();
if (result.choices && result.choices[0] && result.choices[0].message && result.choices[0].message.content) {
let responseContent = result.choices[0].message.content;
try {
const jsonMatch = responseContent.match(/```json\n([\s\S]*?)\n```/);
if (jsonMatch && jsonMatch[1]) {
responseContent = jsonMatch[1];
}
const parsedTokens = JSON.parse(responseContent);
displayAnalyzedSentence(parsedTokens, sentence);
} catch (e) {
console.error("Failed to parse JSON from analysis response:", e, responseContent);
analyzedSentenceOutput.innerHTML = `<p class="text-red-500 p-3">解析结果JSON格式错误。原始回复: <pre class="whitespace-pre-wrap">${responseContent}</pre></p>`;
}
} else {
analyzedSentenceOutput.innerHTML = '<p class="text-red-500 p-3">解析结果格式错误,请重试。</p>';
console.error('Unexpected API response structure (Analysis):', result);
}
} catch (error) {
console.error('Error during analysis:', error);
analyzedSentenceOutput.innerHTML = `<p class="text-red-500 p-3">解析时发生错误: ${error.message}。</p>`;
} finally {
hideLoading(analyzeButton, "解析句子");
}
});
function displayAnalyzedSentence(tokens, originalSentence) {
analyzedSentenceOutput.innerHTML = '';
if (!tokens || !Array.isArray(tokens) || tokens.length === 0) {
analyzedSentenceOutput.textContent = '未能解析句子或返回数据格式不正确。';
console.error("displayAnalyzedSentence received invalid tokens:", tokens);
return;
}
tokens.forEach(token => {
if (typeof token !== 'object' || token === null || !token.word || !token.pos) {
console.warn("Skipping invalid token:", token);
return;
}
const wordUnitWrapper = document.createElement('span');
wordUnitWrapper.className = 'word-unit-wrapper tooltip';
const wordTokenSpan = document.createElement('span');
wordTokenSpan.className = `word-token ${getPosClass(token.pos)}`;
wordTokenSpan.dataset.word = token.word;
wordTokenSpan.dataset.pos = token.pos;
wordTokenSpan.dataset.furigana = token.furigana || '';
wordTokenSpan.dataset.romaji = token.romaji || '';
const rubyEl = document.createElement('ruby');
const rbEl = document.createElement('rb');
rbEl.textContent = token.word;
rubyEl.appendChild(rbEl);
if (token.furigana && token.furigana !== token.word && containsKanji(token.word) && token.pos !== '記号') {
const rtEl = document.createElement('rt');
rtEl.textContent = token.furigana;
rubyEl.appendChild(rtEl);
}
wordTokenSpan.appendChild(rubyEl);
wordUnitWrapper.appendChild(wordTokenSpan);
if (token.romaji && token.pos !== '記号') {
const romajiSpan = document.createElement('span');
romajiSpan.className = 'romaji-text';
romajiSpan.textContent = token.romaji;
wordUnitWrapper.appendChild(romajiSpan);
}
const tooltipTextSpan = document.createElement('span');
tooltipTextSpan.className = 'tooltiptext';
tooltipTextSpan.textContent = posChineseMap[token.pos.split('-')[0]] || posChineseMap['default'];
wordUnitWrapper.appendChild(tooltipTextSpan);
wordTokenSpan.addEventListener('click', (event) => {
event.stopPropagation();
if (currentActiveWordTokenElement === wordTokenSpan && wordDetailInlineContainer.style.display !== 'none') {
wordDetailInlineContainer.style.display = 'none';
wordTokenSpan.classList.remove('active-word');
currentActiveWordTokenElement = null;
} else {
if (currentActiveWordTokenElement) {
currentActiveWordTokenElement.classList.remove('active-word');
}
wordTokenSpan.classList.add('active-word');
currentActiveWordTokenElement = wordTokenSpan;
fetchWordDetails(token.word, token.pos, originalSentence, token.furigana, token.romaji);
}
});
analyzedSentenceOutput.appendChild(wordUnitWrapper);
});
}
async function fetchWordDetails(word, pos, sentence, furigana, romaji) {
const currentApiKey = getApiKeyForRequest();
const currentApiUrl = getApiUrlForRequest();
if (!currentApiKey) {
settingsStatus.textContent = '请先在设置中填写API密钥以获取词汇详解。';
settingsStatus.className = 'mt-3 text-sm text-red-600';
settingsModal.style.display = 'flex';
modalApiKeyInput.focus();
wordDetailInlineContainer.innerHTML = `<p class="text-red-500 p-3">错误:API密钥未设置。</p>`;
wordDetailInlineContainer.style.display = 'block';
return;
}
wordDetailInlineContainer.innerHTML = '<div class="flex items-center justify-center py-5"><div class="loading-spinner"></div><span class="ml-2 text-gray-600">正在查询释义...</span></div>';
wordDetailInlineContainer.style.display = 'block';
let contextWordInfo = `单词 "${word}" (词性: ${pos}`;
if (furigana && furigana !== word && containsKanji(word)) contextWordInfo += `, 读音: ${furigana}`;
if (romaji) contextWordInfo += `, 罗马音: ${romaji}`;
contextWordInfo += `)`;
const wordDetailPrompt = `在日语句子 "${sentence}" 的上下文中,${contextWordInfo} 的具体含义是什么?请提供以下信息,并以严格的JSON对象格式返回,不要包含任何markdown或其他非JSON字符:
{
"originalWord": "${word}",
"chineseTranslation": "中文翻译",
"pos": "${pos}",
"furigana": "${(furigana && furigana !== word && containsKanji(word)) ? furigana : ''}",
"romaji": "${romaji || ''}",
"dictionaryForm": "辞书形(如果适用)",
"explanation": "中文解释(包括外来语来源和活用形原因)"
}
例如,对于 "食べます",返回:
{
"originalWord": "食べます",
"chineseTranslation": "吃",
"pos": "動詞",
"furigana": "たべます",
"romaji": "tabemasu",
"dictionaryForm": "食べる",
"explanation": "动词“食べる”(吃)的ます形,表示礼貌的现在或将来时态。"
}`;
const payload = {
model: modelName,
reasoning_effort: "none",
messages: [{ role: "user", content: wordDetailPrompt }],
};
try {
const response = await fetch(currentApiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${currentApiKey}`
},
body: JSON.stringify(payload)
});
let details;
if (!response.ok) {
const errorData = await response.json();
console.error('API Error (Word Detail):', errorData);
details = { originalWord: word, pos: pos, furigana: (furigana && furigana !== word && containsKanji(word)) ? furigana : '', romaji: romaji || '', dictionaryForm: '', chineseTranslation: '错误', explanation: `查询释义失败:${errorData.error?.message || response.statusText || '未知错误'}` };
} else {
const result = await response.json();
if (result.choices && result.choices[0] && result.choices[0].message && result.choices[0].message.content) {
let responseContent = result.choices[0].message.content;
try {
const jsonMatch = responseContent.match(/```json\n([\s\S]*?)\n```/);
if (jsonMatch && jsonMatch[1]) {
responseContent = jsonMatch[1];
}
details = JSON.parse(responseContent);
if (!details.furigana && furigana && furigana !== word && containsKanji(word)) details.furigana = furigana;
if (!details.romaji && romaji) details.romaji = romaji;
} catch (e) {
console.error("Failed to parse JSON from word detail response:", e, responseContent);
details = { originalWord: word, pos: pos, furigana: (furigana && furigana !== word && containsKanji(word)) ? furigana : '', romaji: romaji || '', dictionaryForm: '', chineseTranslation: '错误', explanation: `释义结果JSON格式错误。原始回复: ${responseContent}`};
}
} else {
console.error('Unexpected API response structure for word detail:', result);
details = { originalWord: word, pos: pos, furigana: (furigana && furigana !== word && containsKanji(word)) ? furigana : '', romaji: romaji || '', dictionaryForm: '', chineseTranslation: '错误', explanation: '释义结果格式错误。'};
}
}
displayWordDetailsInline(details);
} catch (error) {
console.error('Error fetching word details:', error);
displayWordDetailsInline({ originalWord: word, pos: pos, furigana: (furigana && furigana !== word && containsKanji(word)) ? furigana : '', romaji: romaji || '', dictionaryForm: '', chineseTranslation: '错误', explanation: `查询释义时发生错误: ${error.message}。`});
}
}
function displayWordDetailsInline(details) {
const detailPosClass = getPosClass(details.pos);
let furiganaDisplay = (details.furigana && details.originalWord && containsKanji(details.originalWord) && details.furigana !== details.originalWord)
? `<p class="mb-1"><strong>读音 (Furigana):</strong> <span class="text-sm text-purple-700">${details.furigana}</span></p>`
: '';
let romajiDisplay = details.romaji ? `<p class="mb-1"><strong>罗马音 (Romaji):</strong> <span class="text-sm text-cyan-700">${details.romaji}</span></p>` : '';
let dictionaryFormDisplay = '';
if (details.dictionaryForm && details.dictionaryForm !== details.originalWord) {
dictionaryFormDisplay = `<p class="mb-2"><strong>辞书形:</strong> <span class="text-md text-blue-700 font-medium">${details.dictionaryForm}</span></p>`;
}
const readAloudButtonHTML = `<button id="readAloudWordButton" class="read-aloud-button" title="朗读此词汇"><i class="fas fa-volume-up"></i></button>`;
wordDetailInlineContainer.innerHTML = `
<button class="detail-close-button" title="关闭详情">×</button>
<h3 class="text-xl font-semibold text-[#007AFF] mb-3">词汇详解</h3>
<p class="mb-1"><strong>原文:</strong> <span class="font-mono text-lg text-gray-800">${details.originalWord}</span> ${readAloudButtonHTML}</p>
${furiganaDisplay}
${romajiDisplay}
${dictionaryFormDisplay}
<p class="mb-2"><strong>词性:</strong> <span class="detail-pos-tag ${detailPosClass}">${details.pos} (${posChineseMap[details.pos.split('-')[0]] || posChineseMap['default']})</span></p>
<p class="mb-2"><strong>中文译文:</strong> <span class="text-lg text-green-700 font-medium">${details.chineseTranslation}</span></p>
<div class="mb-1"><strong>解释:</strong></div>
<p class="text-gray-700 bg-gray-50 p-3 rounded-md text-base leading-relaxed">${details.explanation}</p>
`;
wordDetailInlineContainer.style.display = 'block';
const readAloudBtn = document.getElementById('readAloudWordButton');
if(readAloudBtn) {
readAloudBtn.addEventListener('click', () => {
speakJapanese(details.originalWord);
});
}
wordDetailInlineContainer.querySelector('.detail-close-button').addEventListener('click', () => {
wordDetailInlineContainer.style.display = 'none';
if (currentActiveWordTokenElement) {
currentActiveWordTokenElement.classList.remove('active-word');
currentActiveWordTokenElement = null;
}
});
}
function speakJapanese(text) {
if ('speechSynthesis' in window) {
window.speechSynthesis.cancel();
const utterance = new SpeechSynthesisUtterance(text);
utterance.lang = 'ja-JP';
utterance.rate = 0.9;
utterance.pitch = 1;
window.speechSynthesis.speak(utterance);
} else {
alert('抱歉,您的浏览器不支持语音朗读功能。');
}
}
translateSentenceButton.addEventListener('click', async () => {
const sentence = japaneseInput.value.trim();
if (!sentence) {
alert('请输入要翻译的日语句子!');
return;
}
const currentApiKey = getApiKeyForRequest();
const currentApiUrl = getApiUrlForRequest();
if (!currentApiKey) {
settingsStatus.textContent = '请先在设置中填写API密钥以翻译句子。';
settingsStatus.className = 'mt-3 text-sm text-red-600';
settingsModal.style.display = 'flex';
modalApiKeyInput.focus();
return;
}
showLoading(translateSentenceButton, "翻译中...");
fullTranslationOutput.innerHTML = '<div class="flex items-center justify-center py-4"><div class="loading-spinner"></div><span class="ml-2 text-gray-500">正在翻译,请稍候...</span></div>';
fullTranslationCard.style.display = 'block';
toggleFullTranslationButton.textContent = '隐藏';
const translationPrompt = `请将以下日语句子翻译成简体中文:\n\n"${sentence}"\n\n请仅返回翻译后的中文文本。`;
const payload = {
model: modelName,
reasoning_effort: "none",
messages: [{ role: "user", content: translationPrompt }]