Я создал базовый объект JSON в качестве запроса на Chatgpt, а затем я пробегаю кучу изображений, выбранных с помощью входного тега, и динамически добавляю их в объект, чтобы он посмотрел на изображения и писать для них контент Alt. API CHATGPT. В настоящее время у меня есть массив, к которому я добавляю счет, а затем назначаю их на основе порядка этого массива. < /P>
Это работает, но только около 70% случаев. < /P>
var nLoopIds = [];
const files = document.getElementById("fileImages").files
for (let i = 0; i < files.length; i++)
{
const fileReader = new FileReader();
fileReader.onloadend = function(event)
{
// Add to data object
data.response_format.json_schema.schema.properties["alt_" + i] =
{
"type": "string"
};
data.response_format.json_schema.schema.required.push("alt_" + i);
const b64 = event.target.result.split(",")[1]; // Extract base64 data
var image_url =
{
"url": "data:image/jpeg;base64," + b64
}
var image =
{
"type": "image_url",
"image_url": image_url
}
data.messages[1].content.push(image);
// Add to show order uploaded
nLoopIds.push(i);
// Post to ChatGPT
if (nCount == files.length - 1)
{
// Send the POST request using fetch
fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": "Bearer api-key",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then((response) => response.json())
.then((data) => loadText(data, nLoopIds))
.catch((error) => alert(error));
}
}
fileReader.readAsDataURL(files); // Read selected file as Data URL
}
< /code>
Это код, который получает ответ JSON от Chatgpt. < /p>
function loadText(data, nLoopIds)
{
var obj = JSON.parse(data["choices"][0]["message"]["content"]);
document.getElementById("strTitle").value = obj["title"];
document.getElementById("strShort").value = obj["short"];
document.getElementById("strDescription").value = obj["description"];
document.getElementById("strTheme").value = obj["theme"];
document.getElementById("strTags").value = obj["tags"];
for (let i = 0; i < nLoopIds.length; i++)
{
document.getElementById("imgAlt-" + nLoopIds).value = obj["alt_" + i];
}
}
< /code>
плюс исходный объект данных. < /p>
var data = {
model: "",
//user: "",
response_format:
{
"type": "json_schema",
"json_schema":
{
"name": "generate_project",
"strict": true,
"schema":
{
"type": "object",
"properties":
{
"title":
{
"type": "string"
},
"short":
{
"type": "string"
},
"description":
{
"type": "string"
},
"theme":
{
"type": "string"
},
"tags":
{
"type": "string"
}
},
"required": ["title", "short", "description", "theme", "tags"],
"additionalProperties": false
}
}
},
messages: [
{
role: "system",
content: ""
},
{
role: "user",
content: [
{
"type": "text",
"text": document.getElementById("strPrompt").value
}]
}]
};
Подробнее здесь: https://stackoverflow.com/questions/797 ... s-files-in
Как управлять/записать заказ FileReader загружать файлы? ⇐ Javascript
Форум по Javascript
-
Anonymous
1753779812
Anonymous
Я создал базовый объект JSON в качестве запроса на Chatgpt, а затем я пробегаю кучу изображений, выбранных с помощью входного тега, и динамически добавляю их в объект, чтобы он посмотрел на изображения и писать для них контент Alt. API CHATGPT. В настоящее время у меня есть массив, к которому я добавляю счет, а затем назначаю их на основе порядка этого массива. < /P>
Это работает, но только около 70% случаев. < /P>
var nLoopIds = [];
const files = document.getElementById("fileImages").files
for (let i = 0; i < files.length; i++)
{
const fileReader = new FileReader();
fileReader.onloadend = function(event)
{
// Add to data object
data.response_format.json_schema.schema.properties["alt_" + i] =
{
"type": "string"
};
data.response_format.json_schema.schema.required.push("alt_" + i);
const b64 = event.target.result.split(",")[1]; // Extract base64 data
var image_url =
{
"url": "data:image/jpeg;base64," + b64
}
var image =
{
"type": "image_url",
"image_url": image_url
}
data.messages[1].content.push(image);
// Add to show order uploaded
nLoopIds.push(i);
// Post to ChatGPT
if (nCount == files.length - 1)
{
// Send the POST request using fetch
fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": "Bearer api-key",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then((response) => response.json())
.then((data) => loadText(data, nLoopIds))
.catch((error) => alert(error));
}
}
fileReader.readAsDataURL(files[i]); // Read selected file as Data URL
}
< /code>
Это код, который получает ответ JSON от Chatgpt. < /p>
function loadText(data, nLoopIds)
{
var obj = JSON.parse(data["choices"][0]["message"]["content"]);
document.getElementById("strTitle").value = obj["title"];
document.getElementById("strShort").value = obj["short"];
document.getElementById("strDescription").value = obj["description"];
document.getElementById("strTheme").value = obj["theme"];
document.getElementById("strTags").value = obj["tags"];
for (let i = 0; i < nLoopIds.length; i++)
{
document.getElementById("imgAlt-" + nLoopIds[i]).value = obj["alt_" + i];
}
}
< /code>
плюс исходный объект данных. < /p>
var data = {
model: "",
//user: "",
response_format:
{
"type": "json_schema",
"json_schema":
{
"name": "generate_project",
"strict": true,
"schema":
{
"type": "object",
"properties":
{
"title":
{
"type": "string"
},
"short":
{
"type": "string"
},
"description":
{
"type": "string"
},
"theme":
{
"type": "string"
},
"tags":
{
"type": "string"
}
},
"required": ["title", "short", "description", "theme", "tags"],
"additionalProperties": false
}
}
},
messages: [
{
role: "system",
content: ""
},
{
role: "user",
content: [
{
"type": "text",
"text": document.getElementById("strPrompt").value
}]
}]
};
Подробнее здесь: [url]https://stackoverflow.com/questions/79718356/how-to-control-record-the-order-filereader-uploads-files-in[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия