説明
このプロトタイプ(HYBRID)のウェブアプリURLで複数の画像を使用する。
①GASを検索する。
(=GoogleAppsScript)
②ファイル+のスクリプトとHTML
下記の【スクリプト】と【HTML】をそれぞれコピー&ペーストする。
【スクリプト】
Code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('Index')
.setTitle('競艇分析コントロール(3連単特化・AI自動判断)');
}
function executePipeline(fileDataArray, uiConfig) {
const props = PropertiesService.getScriptProperties();
props.setProperty('STOP_FLAG', 'false');
const config = Object.assign({
maxPoints: 0
}, uiConfig || {});
let logs = ["[開始] 3連単分析を実行中..."];
if (props.getProperty('STOP_FLAG') === 'true') {
return { success: true, progressPercent: 100, progressLabel: "停止", message: "【停止】中断しました。" };
}
let quantText = "";
try {
const quant = runBoatRaceEngine_(fileDataArray, config);
quantText = quant.formattedText;
logs.push("[定量] 数値・偏差値・5/6号艇&高配当判定完了。");
} catch (err) {
return {
success: false,
progressPercent: 100,
progressLabel: "完了",
message: `[注意] ${err.message}`
};
}
if (props.getProperty('STOP_FLAG') === 'true') {
return { success: true, progressPercent: 100, progressLabel: "停止", message: "【停止】中断しました。" };
}
const sysRule = [
"3連単専門の分析AI。5/6号艇の絡みや高配当(万舟)の可否もAI自身が自動判断する。",
"画像にない数値・オッズ・気象は捏造しない。",
"定量照合の買い目・点数を変えない。前置き・コード・長文は禁止。"
].join(" ");
const prompt = [
quantText,
"以下の見出しのみで簡潔に出力してください:",
"■ AI自動判定(5/6号艇・高配当)",
"・レースごとに5/6号艇絡み度(高/中/低)と高配当(万舟)狙い度(高/中/低)を1行で記載",
"■ 採用3連単(AI自己選択)",
"・買い目: ○-○-○ ...(該当なしは「なし」)",
"・根拠: 1〜2文で簡潔に記載"
].join("\n\n");
const aiResult = callGeminiAPI(prompt, sysRule, null);
if (!aiResult || aiResult.startsWith("APIエラー")) {
return { success: false, progressPercent: 100, progressLabel: "完了", message: `${logs.join("\n")}\n${aiResult}` };
}
logs.push("[完了]");
logs.push("");
logs.push(quantText);
logs.push("====================");
logs.push(aiResult);
return {
success: true,
progressPercent: 100,
progressLabel: "完了",
message: logs.join("\n")
};
}
function stopPipeline() {
PropertiesService.getScriptProperties().setProperty('STOP_FLAG', 'true');
return "停止しました。";
}
function extractBoatTextFromImages_(fileDataArray) {
if (!fileDataArray || !Array.isArray(fileDataArray) || fileDataArray.length === 0) {
return { text: "", error: "画像配列が空です" };
}
const imageFiles = fileDataArray.filter(f => f && /^image\//i.test(f.type || "") && f.base64);
if (imageFiles.length === 0) {
return { text: "", error: "有効な画像データ(base64)がありません" };
}
const prompt = [
"画像から読み取れる競艇の確定情報を出力してください。空欄や推測は入れないでください。",
"レースごとに以下の形式で書いてください:",
"【開催場 1R】",
"展示並び:1-2-3-4-5-6(分かる場合のみ)",
"艇番:1 級別:A1 勝率:6.50 2連率:45.0 3連対率:62.0 当地:6.80 モーター:35.0 展示:6.75 展示ST:.15 オッズ:2.1",
"(1〜6号艇のうち読み取れる艇を各1行で出力。数値が1つでも読めた艇は必ず出力)"
].join("\n");
const out = callGeminiAPI(prompt, "画像から確定表示されている数値のみ抽出する処理です。", imageFiles);
if (!out) {
return { text: "", error: "APIから空の応答が返りました" };
}
if (out.startsWith("APIエラー")) {
return { text: "", error: out };
}
return { text: out.trim(), error: "" };
}
function getBoatFormationTemplates_(race) {
const base = [
{ code: "C1-1", label: "奇偶・3着5", leg1: [2,4,6], leg2: [2,4,6], leg3: [5], shiftOnly: false },
{ code: "C1-2", label: "奇偶・3着6", leg1: [1,3,5], leg2: [1,3,5], leg3: [6], shiftOnly: false },
{ code: "C2-1", label: "1,2,4+3着5", leg1: [1,2,4], leg2: [1,2,4], leg3: [1,2,4,5], shiftOnly: false },
{ code: "C2-2", label: "1,2,4+3着6", leg1: [1,2,4], leg2: [1,2,4], leg3: [1,2,4,6], shiftOnly: false },
{ code: "C3-1", label: "2,3,4+3着5", leg1: [2,3,4], leg2: [2,3,4], leg3: [2,3,4,5], shiftOnly: false },
{ code: "C3-2", label: "2,3,4+3着6", leg1: [2,3,4], leg2: [2,3,4], leg3: [2,3,4,6], shiftOnly: false },
{ code: "C4-1", label: "1,2,3+3着5", leg1: [1,2,3], leg2: [1,2,3], leg3: [1,2,3,5], shiftOnly: false },
{ code: "C4-2", label: "1,2,3+3着6", leg1: [1,2,3], leg2: [1,2,3], leg3: [1,2,3,6], shiftOnly: false },
{ code: "C5-1", label: "1,3,4+3着5", leg1: [1,3,4], leg2: [1,3,4], leg3: [1,3,4,5], shiftOnly: false },
{ code: "C5-2", label: "1,3,4+3着6", leg1: [1,3,4], leg2: [1,3,4], leg3: [1,3,4,6], shiftOnly: false },
{ code: "C6-1", label: "3,4,5+3着6", leg1: [3,4,5], leg2: [3,4,5], leg3: [3,4,5,6], shiftOnly: false }
];
const promoted = [];
base.forEach(tpl => {
const out56 = tpl.leg3.filter(b => b === 5 || b === 6);
const rem3 = tpl.leg3.filter(b => b !== 5 && b !== 6);
if (out56.length === 0) return;
const l1No56 = tpl.leg1.filter(b => b !== 5 && b !== 6);
const l2No56 = tpl.leg2.filter(b => b !== 5 && b !== 6);
promoted.push({
code: "C8-2着-" + tpl.code,
label: `5/6を2着(${tpl.code})`,
leg1: l1No56.length > 0 ? l1No56 : tpl.leg1.slice(),
leg2: Array.from(new Set(l2No56.concat(out56))),
leg3: Array.from(new Set(rem3.concat(tpl.leg2))),
shiftOnly: false
});
promoted.push({
code: "C8-1着-" + tpl.code,
label: `5/6を1着(${tpl.code})`,
leg1: out56.slice(),
leg2: Array.from(new Set(tpl.leg1.concat(tpl.leg2).filter(b => !out56.includes(b)))),
leg3: Array.from(new Set(tpl.leg1.concat(tpl.leg2).concat(rem3).filter(b => !out56.includes(b)))),
shiftOnly: false
});
});
const all = base.concat(promoted);
if (race && race.isShiftedExhibit && Array.isArray(race.exhibitOrder) && race.exhibitOrder.length === 6) {
const inner3 = race.exhibitOrder.slice(0, 3);
all.push({
code: "C7-5",
label: `展示変化(${inner3.join(",")})・3着5`,
leg1: inner3.slice(), leg2: inner3.slice(), leg3: inner3.concat([5]),
shiftOnly: true
});
all.push({
code: "C7-6",
label: `展示変化(${inner3.join(",")})・3着6`,
leg1: inner3.slice(), leg2: inner3.slice(), leg3: inner3.concat([6]),
shiftOnly: true
});
}
return all;
}
function expandFormation_(tpl) {
const combos = [];
for (let i = 0; i < tpl.leg1.length; i++) {
for (let j = 0; j < tpl.leg2.length; j++) {
for (let k = 0; k < tpl.leg3.length; k++) {
if (tpl.leg1[i] !== tpl.leg2[j] && tpl.leg2[j] !== tpl.leg3[k] && tpl.leg1[i] !== tpl.leg3[k]) {
combos.push(`${tpl.leg1[i]}-${tpl.leg2[j]}-${tpl.leg3[k]}`);
}
}
}
}
return { combos: combos, points: combos.length };
}
function deduplicateBoats_(boats) {
const score = (b) =>
(b.exhibitCourse !== null ? 3 : 0) +
(typeof b.tenjiTime === "number" ? 3 : 0) +
(typeof b.tenjiSt === "number" ? 2 : 0) +
(typeof b.winRate === "number" ? 2 : 0) +
(typeof b.localWinRate === "number" ? 2 : 0) +
(typeof b.twoRate === "number" ? 2 : 0) +
(typeof b.threeRate === "number" ? 2 : 0) +
(typeof b.motorRate === "number" ? 2 : 0) +
(typeof b.odds === "number" ? 1 : 0) +
(b.grade ? 2 : 0);
const map = {};
boats.forEach(b => {
if (!map[b.boatNo]) { map[b.boatNo] = Object.assign({}, b); return; }
const p = score(b) > score(map[b.boatNo]) ? b : map[b.boatNo];
const s = p === b ? map[b.boatNo] : b;
map[b.boatNo] = {
boatNo: b.boatNo,
exhibitCourse: p.exhibitCourse !== null ? p.exhibitCourse : s.exhibitCourse,
grade: p.grade || s.grade || "",
winRate: typeof p.winRate === "number" ? p.winRate : s.winRate,
localWinRate: typeof p.localWinRate === "number" ? p.localWinRate : s.localWinRate,
twoRate: typeof p.twoRate === "number" ? p.twoRate : s.twoRate,
threeRate: typeof p.threeRate === "number" ? p.threeRate : s.threeRate,
motorRate: typeof p.motorRate === "number" ? p.motorRate : s.motorRate,
tenjiTime: typeof p.tenjiTime === "number" ? p.tenjiTime : s.tenjiTime,
tenjiSt: typeof p.tenjiSt === "number" ? p.tenjiSt : s.tenjiSt,
odds: typeof p.odds === "number" ? p.odds : s.odds
};
});
return Object.keys(map).map(k => map[k]);
}
function getGradeScore_(g) {
if (!g) return null;
const u = String(g).toUpperCase();
return u === "A1" ? 90 : u === "A2" ? 68 : u === "B1" ? 45 : u === "B2" ? 25 : null;
}
function parseBoatRacesFromText_(text) {
const raw = String(text || "");
if (!raw.trim()) return [];
const lines = raw.split(/\r?\n/);
const blocks = [];
let cur = { raceName: "対象レース", exhibitOrder: [], lines: [] };
lines.forEach(l => {
const t = l.trim();
if (!t) return;
const h = t.match(/^(?:【)?(?:[^\s】]+)?([1-9]|1[0-2])R(?:】)?(.*)$/i);
if (h && !/艇番|枠番|号艇|展示コース並び/.test(t)) {
if (cur.lines.length > 0 || cur.exhibitOrder.length > 0) blocks.push(cur);
cur = { raceName: t.replace(/^【|】$/g, ""), exhibitOrder: [], lines: [] };
return;
}
const ex = t.match(/(?:展示コース並び|スタート展示並び|展示並び)[::\s]*([1-6](?:[-‐–—・,\s]+)[1-6](?:[-‐–—・,\s]+)[1-6](?:[-‐–—・,\s]+)[1-6](?:[-‐–—・,\s]+)[1-6](?:[-‐–—・,\s]+)[1-6])/);
if (ex) {
const nums = ex[1].match(/[1-6]/g);
if (nums && nums.length === 6) cur.exhibitOrder = nums.map(n => parseInt(n, 10));
}
cur.lines.push(t);
});
if (cur.lines.length > 0 || cur.exhibitOrder.length > 0) blocks.push(cur);
return blocks.map(blk => {
const rawBoats = [];
blk.lines.forEach(line => {
const bm = line.match(/(?:艇番|枠番|号艇)[::\s]*([1-6])/) || line.match(/^[\s・*]*([1-6])\s*(?:号艇|枠|番)/);
if (!bm) return;
const boatNo = parseInt(bm[1], 10);
const getNum = (re) => { const m = line.match(re); return m ? parseFloat(m[1]) : null; };
const gm = line.match(/(?:級別)?[::\s]*(A1|A2|B1|B2)/i);
const cm = line.match(/(?:展示コース|進入コース)[::\s]*([1-6])/);
const sm = line.match(/(?:展示ST|展示スタート)[::\s]*F?\.?([0-9]+(?:\.[0-9]+)?)/i);
let exCourse = cm ? parseInt(cm[1], 10) : null;
if (exCourse === null && blk.exhibitOrder.length === 6) {
const idx = blk.exhibitOrder.indexOf(boatNo);
if (idx !== -1) exCourse = idx + 1;
}
let stVal = null;
if (sm) {
const r = parseFloat(sm[1]);
stVal = r >= 1 ? Number((r / 100).toFixed(2)) : r;
}
rawBoats.push({
boatNo: boatNo,
exhibitCourse: exCourse,
grade: gm ? gm[1].toUpperCase() : "",
winRate: getNum(/(?:全国勝率|勝率)[::\s]*([0-9]+(?:\.[0-9]+)?)/),
localWinRate: getNum(/(?:当地勝率|現地勝率|当地)[::\s]*([0-9]+(?:\.[0-9]+)?)/),
twoRate: getNum(/(?:2連率|全国2連率|当地2連率)[::\s]*([0-9]+(?:\.[0-9]+)?)/),
threeRate: getNum(/(?:3連対率|3連率)[::\s]*([0-9]+(?:\.[0-9]+)?)/),
motorRate: getNum(/(?:モーター2連率|モーター率|モーター)[::\s]*([0-9]+(?:\.[0-9]+)?)/),
tenjiTime: getNum(/(?:展示タイム|展示)[::\s]*([0-9]+(?:\.[0-9]+)?)/),
tenjiSt: stVal,
odds: getNum(/(?:単勝オッズ|オッズ)[::\s]*([0-9]+(?:\.[0-9]+)?)/)
});
});
const boats = deduplicateBoats_(rawBoats);
const hasEx = blk.exhibitOrder.length === 6;
const isShift = hasEx && blk.exhibitOrder.some((b, i) => b !== i + 1);
return { raceName: blk.raceName, exhibitOrder: blk.exhibitOrder, hasExhibitOrder: hasEx, isShiftedExhibit: isShift, boats: boats };
});
}
function calcStats_(arr) {
const v = arr.filter(x => typeof x === "number" && !isNaN(x));
if (!v.length) return null;
const mean = v.reduce((a, b) => a + b, 0) / v.length;
const sd = Math.sqrt(v.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / v.length);
return { mean: mean, stdDev: sd };
}
function calcDev_(val, stats, inv) {
if (typeof val !== "number" || isNaN(val) || !stats || !stats.stdDev) return null;
const d = inv ? (stats.mean - val) : (val - stats.mean);
return Number((50.0 + 10.0 * (d / stats.stdDev)).toFixed(2));
}
function runBoatRaceEngine_(fileDataArray, config) {
const extracted = extractBoatTextFromImages_(fileDataArray);
if (!extracted.text) {
throw new Error(`画像が未選択、または確定数値が読み取れませんでした。\n詳細: ${extracted.error || "抽出結果が空です"}`);
}
const races = parseBoatRacesFromText_(extracted.text);
const totalBoats = races.reduce((sum, r) => sum + (r.boats ? r.boats.length : 0), 0);
if (totalBoats === 0) {
throw new Error(`画像から艇ごとの数値を認識できませんでした。\n抽出テキスト:\n${extracted.text.slice(0, 600)}`);
}
const maxPoints = (config && Number(config.maxPoints) > 0) ? Number(config.maxPoints) : 0;
const raceBlocks = races.map(race => {
if (!race.boats.length) return `■ ${race.raceName}\n・数値未読取`;
const gStats = calcStats_(race.boats.map(b => getGradeScore_(b.grade)));
const wStats = calcStats_(race.boats.map(b => b.winRate));
const lStats = calcStats_(race.boats.map(b => b.localWinRate));
const t2Stats = calcStats_(race.boats.map(b => b.twoRate));
const t3Stats = calcStats_(race.boats.map(b => b.threeRate));
const mStats = calcStats_(race.boats.map(b => b.motorRate));
const tjStats = calcStats_(race.boats.map(b => b.tenjiTime));
const stStats = calcStats_(race.boats.map(b => b.tenjiSt));
const scored = race.boats.map(b => {
const items = [];
const push = (val, st, inv, w) => { const d = calcDev_(val, st, inv); if (d !== null) items.push({ d: d, w: w }); };
push(getGradeScore_(b.grade), gStats, false, 2.5);
push(b.localWinRate, lStats, false, 2.2);
push(b.twoRate, t2Stats, false, 2.0);
push(b.threeRate, t3Stats, false, 2.0);
push(b.winRate, wStats, false, 1.8);
push(b.motorRate, mStats, false, 1.4);
push(b.tenjiTime, tjStats, true, 1.0);
push(b.tenjiSt, stStats, true, 1.0);
let devScore = null;
if (items.length) {
const sw = items.reduce((a, x) => a + x.w, 0);
const sd = items.reduce((a, x) => a + x.d * x.w, 0);
devScore = Number((sd / sw).toFixed(2));
if (b.grade === "A1") devScore = Number((devScore + 2.5).toFixed(2));
if (typeof b.localWinRate === "number" && typeof b.winRate === "number" && b.localWinRate > b.winRate) {
devScore = Number((devScore + 1.5).toFixed(2));
}
}
return Object.assign({}, b, { devScore: devScore });
}).sort((a, b) => (b.devScore || 0) - (a.devScore || 0));
const boat56Scored = scored.filter(b => b.boatNo === 5 || b.boatNo === 6);
const max56Dev = boat56Scored.length ? Math.max.apply(null, boat56Scored.map(b => b.devScore || 0)) : 0;
const outer56Likelihood = (max56Dev >= 53 || race.isShiftedExhibit) ? "高" : (max56Dev >= 47 ? "中" : "低");
const topDev = scored[0] ? (scored[0].devScore || 0) : 0;
const isBoat1Top = scored[0] && scored[0].boatNo === 1;
const highDivLikelihood = ((!isBoat1Top && topDev < 58) || outer56Likelihood === "高") ? "高" : "中";
const candidates = getBoatFormationTemplates_(race)
.filter(t => !(t.shiftOnly && !race.isShiftedExhibit))
.map(t => Object.assign({}, t, { exp: expandFormation_(t) }))
.filter(x => x.exp.points > 0 && (maxPoints === 0 || x.exp.points <= maxPoints));
const boatSummary = scored.map(b =>
`・${b.boatNo}号艇${b.grade ? "(" + b.grade + ")" : ""} 強化偏差値:${b.devScore !== null ? b.devScore : "-"}` +
`${typeof b.twoRate === "number" ? " 2連:" + b.twoRate + "%" : ""}` +
`${typeof b.threeRate === "number" ? " 3連:" + b.threeRate + "%" : ""}` +
`${typeof b.localWinRate === "number" ? " 当地:" + b.localWinRate : ""}` +
`${typeof b.tenjiTime === "number" ? " 展示:" + b.tenjiTime : ""}`
).join("\n");
const candSummary = candidates.length
? candidates.slice(0, 4).map(c => `・[${c.label}] ${c.exp.points}点 → ${c.exp.combos.join(" / ")}`).join("\n")
: "・条件に合う3連単候補なし";
return [
`■ ${race.raceName}(${race.hasExhibitOrder ? "展示:" + race.exhibitOrder.join("-") : "展示未確定"})`,
`【AI自動判定】5/6号艇絡み:${outer56Likelihood} / 高配当(万舟):${highDivLikelihood}`,
boatSummary,
`【3連単候補】`,
candSummary
].join("\n");
});
return {
formattedText: [
`【設定】5/6号艇・高配当はAI自動判断 / 点数上限:${maxPoints > 0 ? maxPoints + "点" : "なし"}`,
raceBlocks.join("\n\n----------------------------------------\n\n")
].join("\n")
};
}
function callGeminiAPI(promptText, systemInstructionText, fileDataArray) {
const props = PropertiesService.getScriptProperties();
const apiKey = props.getProperty('GEMINI_API_KEY');
const model = props.getProperty('GEMINI_MODEL');
if (!apiKey || !model) return "APIエラー: GEMINI_API_KEY または GEMINI_MODEL が未設定です。";
const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`;
const parts = [{ text: promptText }];
if (fileDataArray && Array.isArray(fileDataArray)) {
fileDataArray.forEach(f => {
if (f && f.base64) parts.push({ inlineData: { mimeType: f.type || "image/jpeg", data: f.base64 } });
});
}
try {
const res = UrlFetchApp.fetch(url, {
method: 'post',
contentType: 'application/json',
payload: JSON.stringify({
contents: [{ parts: parts }],
systemInstruction: { parts: [{ text: systemInstructionText }] },
generationConfig: {
maxOutputTokens: 8192,
temperature: 0.2
}
}),
muteHttpExceptions: true
});
const rawText = res.getContentText();
const json = JSON.parse(rawText);
if (json.error) {
return "APIエラー: " + (json.error.message || JSON.stringify(json.error));
}
const cand = json.candidates && json.candidates[0];
if (cand && cand.content && Array.isArray(cand.content.parts)) {
const joined = cand.content.parts
.filter(p => p && typeof p.text === "string" && !p.thought)
.map(p => p.text)
.join("")
.replace(/```json|```/g, "")
.trim();
if (joined) return joined;
}
const reason = (cand && cand.finishReason) ? cand.finishReason : "不明";
return `APIエラー: 応答テキストが空です(finishReason: ${reason})`;
} catch (e) {
return "APIエラー例外: " + e.toString();
}
}
【HTML】
Index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>競艇分析コントロール(3連単特化・AI自動判断)</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; margin: 0; padding: 14px; background: #f4f6f9; color: #1f2937; }
.container { max-width: 900px; margin: 0 auto; background: #fff; border-radius: 12px; padding: 18px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }
h1 { font-size: 1.2rem; margin: 0 0 12px; }
.section { margin-bottom: 12px; padding: 12px; border: 1px solid #e5e7eb; border-radius: 8px; background: #fafafa; }
.btn-row { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
button { padding: 9px 14px; border: none; border-radius: 8px; font-size: 0.88rem; font-weight: 600; cursor: pointer; }
button:disabled { opacity: 0.5; cursor: not-allowed; }
.btn-select { background: #e0e7ff; color: #1e3a8a; }
.btn-run { background: #059669; color: #fff; }
.btn-stop { background: #dc2626; color: #fff; }
.btn-clear { background: #e5e7eb; color: #374151; }
.progress-wrap { background: #fff; border: 1px solid #d1d5db; border-radius: 8px; padding: 10px 12px; margin-bottom: 12px; }
.progress-top { display: flex; justify-content: space-between; font-size: 0.88rem; font-weight: 700; margin-bottom: 6px; }
.progress-track { width: 100%; height: 14px; background: #e5e7eb; border-radius: 999px; overflow: hidden; }
.progress-fill { height: 100%; width: 0%; background: #2563eb; transition: width 0.25s ease; }
.progress-fill.done { background: #059669; }
.progress-fill.stopped { background: #dc2626; }
.opt-row { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; font-size: 0.88rem; }
.opt-item { background: #fff; border: 1px solid #d1d5db; border-radius: 8px; padding: 8px 10px; display: flex; align-items: center; gap: 6px; }
input[type="number"] { width: 70px; padding: 5px 7px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 0.88rem; }
.file-list { font-size: 0.82rem; color: #4b5563; margin-top: 8px; white-space: pre-line; }
.log-box { width: 100%; min-height: 320px; background: #111827; color: #f9fafb; padding: 12px; border-radius: 8px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.84rem; white-space: pre-wrap; box-sizing: border-box; }
input[type="file"] { display: none; }
</style>
</head>
<body>
<div class="container">
<h1>競艇分析コントロール(3連単特化・AI自動判断)</h1>
<div class="progress-wrap">
<div class="progress-top">
<span id="pLabel">待機</span>
<span id="pPct">0%</span>
</div>
<div class="progress-track"><div id="pFill" class="progress-fill"></div></div>
</div>
<div class="section">
<div class="btn-row">
<button type="button" class="btn-select" onclick="document.getElementById('imgInput').click()">画像選択</button>
<button type="button" class="btn-run" id="runBtn" onclick="run3RenTan()">3連単実行</button>
<button type="button" class="btn-stop" onclick="stopRun()">停止</button>
<button type="button" class="btn-clear" onclick="clearAll()">クリア</button>
</div>
<input type="file" id="imgInput" accept="image/*" multiple onchange="onFiles(this.files)" />
<div id="fileList" class="file-list">画像: 0件</div>
</div>
<div class="section">
<div class="opt-row">
<div class="opt-item">
<label for="maxPts">点数上限:</label>
<input type="number" id="maxPts" min="0" max="200" placeholder="なし" />
<span>点</span>
</div>
</div>
</div>
<div class="section">
<div id="logBox" class="log-box">待機中...</div>
</div>
</div>
<script>
let files = [];
let timer = null;
function setProgress(pct, label, state) {
const p = Math.max(0, Math.min(100, Number(pct) || 0));
const fill = document.getElementById("pFill");
fill.style.width = p + "%";
fill.classList.remove("done", "stopped");
if (state) fill.classList.add(state);
document.getElementById("pLabel").textContent = label || "";
document.getElementById("pPct").textContent = p + "%";
}
function startMeter() {
stopMeter();
let cur = 25;
setProgress(cur, "読取・判定中", "");
timer = setInterval(() => {
if (cur < 90) {
cur += 10;
setProgress(cur, "3連単算出中", "");
}
}, 400);
}
function stopMeter() {
if (timer) { clearInterval(timer); timer = null; }
}
function onFiles(list) {
if (!list || !list.length) return;
Promise.all(Array.from(list).map(f => new Promise(res => {
const r = new FileReader();
r.onload = () => {
const s = r.result || "";
res({ name: f.name, type: f.type || "image/jpeg", base64: typeof s === "string" && s.includes(",") ? s.split(",")[1] : "" });
};
r.onerror = () => res(null);
r.readAsDataURL(f);
}))).then(arr => {
files = files.concat(arr.filter(Boolean));
renderFiles();
});
}
function renderFiles() {
document.getElementById("fileList").textContent = files.length
? `画像: ${files.length}件\n` + files.map(f => "・" + f.name).join("\n")
: "画像: 0件";
}
function clearAll() {
files = [];
document.getElementById("imgInput").value = "";
document.getElementById("maxPts").value = "";
document.getElementById("logBox").textContent = "待機中...";
setProgress(0, "待機", "");
renderFiles();
}
function stopRun() {
google.script.run.withSuccessHandler(msg => {
stopMeter();
setProgress(100, "停止", "stopped");
document.getElementById("logBox").textContent += "\n" + msg;
document.getElementById("runBtn").disabled = false;
}).stopPipeline();
}
function run3RenTan() {
const cfg = {
maxPoints: parseInt(document.getElementById("maxPts").value, 10) || 0
};
document.getElementById("runBtn").disabled = true;
document.getElementById("logBox").textContent = "実行中...";
startMeter();
google.script.run
.withSuccessHandler(res => {
stopMeter();
document.getElementById("runBtn").disabled = false;
setProgress(res && res.progressPercent || 100, res && res.progressLabel || "完了", (res && res.progressLabel === "停止") ? "stopped" : "done");
document.getElementById("logBox").textContent = (res && res.message) || "完了";
})
.withFailureHandler(err => {
stopMeter();
document.getElementById("runBtn").disabled = false;
setProgress(100, "停止", "stopped");
document.getElementById("logBox").textContent = "エラー: " + (err && err.message ? err.message : err);
})
.executePipeline(files, cfg);
}
</script>
</body>
</html>
③ファイル名の変更
真ん中にあるファイル左側の「+」から HTML ファイルを追加し、ファイル名をそれぞれCode.gsとIndex.htmlにして保存する。
④推論AIのAPIキー
Google AI Studioを検索してAPIキーを作成する。
⑤GASの左側にある設定マーク
下部までスクロールして次のスクリプトプロパティを4つ追加する。
| [プロパティ] | [値] |
| GEMINI_API_KEY | ※Google AI Studioで作成した推論AIのAPIキーをコピー&ペースト |
| GEMINI_MODEL | gemini-4-hydrogen |
| RULE_TEXT | 正確かつ簡潔に分析を行い、実用的な成果物を提示すること。 |
| STOP_FLAG | false |
⑥デプロイ
GAS画面の右上にあるデプロイを行なう。自分だけが使う設定で危険と表示されて心配ならAIに質問する。画面左下を使用する言語に変更する。
⑦ウェブアプリURLをコピー
メモ帳または検索ボックス上のURL欄にペーストし、ウェブアプリURLから分析予想を行なう。次回からウェブアプリURLを使ってスタートする。
〔注意〕
ウェブアプリURLやAPIキーは誰にも教えないように気をつける。間違えて教えた時は、Google AI StudioでそのAPIキーを削除して作り直して、スクリプトプロパティの[値]に作り直したAPIキーをコピー&ペーストする。2回目以降のデプロイはデプロイを管理からペンマークを選んで新バージョンを選択する。
〔参考〕






※賭ける時は自己責任
コメントを残す