File size: 6,814 Bytes
0aabf7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4ac627
 
0aabf7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4ac627
0aabf7d
 
 
 
 
 
 
a4ac627
 
0aabf7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4ac627
0aabf7d
 
 
 
 
 
a4ac627
 
0aabf7d
a4ac627
0aabf7d
 
 
 
 
 
 
 
a4ac627
0aabf7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
function generatePrompt() {
    if (!document.getElementById('apiKey').value) {
        alert("APIキーを入力してください");
        return;
    }
    let query = document.getElementById('query').value;
    let textFormat = 'str';

    if (document.getElementById('splitStringsSwitch').checked) {
        query = Array.from(document.getElementById('query').value).join(":::");
        //textFormat = 'array, # テキストは1character(not word)ずつ格納した配列にして返すこと。 Example: ["I", "t", " ", "i", "s", " ", "a", " ", "p", "e", "n", "."], ["こ", "れ", "は", " ", "ペ", "ン", "で", "す", "。"], ';
    }

    let anotherLanguage = "";

    if (!["en", "ja"].includes(i18next.language)) {
        anotherLanguage = `,

{

    "language": "${i18next.language}",

    "text": ${textFormat},

    "title": str

}`;
    }

    const selectedEndpoint = document.getElementById('endpointSelect').value;
    const url = `https://generativelanguage.googleapis.com/v1beta/models/${selectedEndpoint}:generateContent?key=` + document.getElementById('apiKey').value;

    const text = `「 ${query} 」をテーマに画像生成AIに送るプロンプトを考えてください。

背景や小物のディテイール、構図、視覚効果など視覚的な情報のみに言及すること。

その上で長文を日本語と英語で返信してください。

返答は以下のフォーマットのjson形式でのみ行う。json以外の内容をレスポンスに含めないこと。

\`\`\`json

{

"results": [

{

    "language": "en",

    "text": ${textFormat} # ${document.getElementById('characterCount').value}文字程度,

    "title": str

},

{

    "language": "danbooru",

    "tags": [str],

},

{

    "language": "ja",

    "text": ${textFormat},

    "title": str

}${anotherLanguage}

]

}

\`\`\`

`;
    const payload = {
        contents: [
            {
                parts: [
                    { text: text }
                ]
            }
        ],
        generation_config: {
            max_output_tokens: 4095,
            temperature: 1,
            top_p: 1,
            top_k: 32
        },
        safetySettings: [
            {
                category: "HARM_CATEGORY_SEXUALLY_EXPLICIT",
                threshold: "BLOCK_NONE"
            }
        ]
    };

    console.debug(text);

    // モーダルを表示
    const loadingModal = new bootstrap.Modal(document.getElementById('loadingModal'));
    loadingModal.show();

    // ローディングアイコンを表示
    document.getElementById('loading').classList.remove('d-none');
    // generatePromptボタンを無効化
    document.getElementById('generatePromptButton').disabled = true;
    document.getElementById('generatePromptButton').classList.remove('btn-primary');
    document.getElementById('generatePromptButton').classList.remove('btn-danger');
    document.getElementById('generatePromptButton').classList.add('btn-secondary');
    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
    })
        .then(response => response.json())
        .then(data => {
            console.debug(data.candidates[0].content);
            // レスポンスからテキストを抽出
            const responseText = data.candidates[0].content.parts[0].text
            console.debug(responseText);

            let jsonString = responseText.replace(/```json|```/g, '').trim();
            jsonString = jsonString.replace(/\n/g, '');
            console.debug(jsonString);
            // JSONをパース
            const parsedData = JSON5.parse(jsonString);

            // 結果を表示
            console.debug(parsedData);
            let promptEn = parsedData.results.find(x => x.language === 'en').text;
            let promptMyLanguage = parsedData.results.find(x => x.language === i18next.language).text;
            [promptEn, promptMyLanguage] = [promptEn, promptMyLanguage].map(x => {
                return Array.isArray(x) ? x.join("") : x;
            });
            document.getElementById('promptEn').value = promptEn.replace(/\. ?/g, '.\n\n');
            document.getElementById('promptEn').value = document.getElementById('promptEn').value.replace(/^ */g, '');
            document.getElementById('promptMyLanguage').value = promptMyLanguage.replace(/\。 ?/g, '。\n\n');

            let danbooruTags = parsedData.results.find(x => x.language === 'danbooru');
            if (danbooruTags.tags) {
                danbooruTags = danbooruTags.tags.map(x => x.replace("_", " "));
                document.getElementById('danbooruTags').value = danbooruTags.join(", ");
            }
            if (danbooruTags.text) {
                danbooruTags = danbooruTags.text.map(x => x.replace("_", " "));
                document.getElementById('danbooruTags').value = danbooruTags.join(", ");
            }

            const title = parsedData.results.find(x => x.language === i18next.language).title;

            // ローディングアイコンを非表示
            document.getElementById('loading').classList.add('d-none');
            document.getElementById('generatePromptButton').disabled = false;
            document.getElementById('generatePromptButton').classList.remove('btn-secondary');
            document.getElementById('generatePromptButton').classList.add('btn-primary');

            document.getElementById('query').value = query;
            saveToUserStorage(true);
            saveToHistory(title); // 履歴に保存
        })
        .catch(error => {
            console.error(error);
            // エラー時の処理
            document.getElementById('generatePromptButton').classList.remove('btn-secondary');
            document.getElementById('generatePromptButton').classList.add('btn-danger');
        })
        .finally(() => {
            document.getElementById('query').value = query;
            // ローディングアイコンを非表示
            document.getElementById('loading').classList.add('d-none');
            document.getElementById('generatePromptButton').disabled = false;
            document.getElementById('generatePromptButton').classList.remove('btn-secondary');
            if (!document.getElementById('generatePromptButton').classList.contains('btn-danger')) {
                document.getElementById('generatePromptButton').classList.add('btn-primary');
            }
            
            // モーダルを非表示
            setTimeout(() => {
                loadingModal.hide();
            }, 500);
        });
};