説明
騎手リーディングまたは調教師リーディングを検索し、画面ごとスクリーンショットを行なう。上位100位ぐらいまでをそれぞれ撮影しておく。
JRAの出馬表を検索し、出馬表全体のスクリーンショットを行なう。一度で出馬表全体を撮影するのは無理なので、2〜3枚に分けて撮影しておく。
プロトタイプ(KAIRYOU)を用いたウェブアプリURLで、画像を使用する。
①GASを検索する。
(=GoogleAppsScript)
②ファイル+のスクリプトとHTML
下記の【スクリプト】と【HTML】をそれぞれコピー&ペーストする。
【スクリプト】
Code.gs
/**
* ウェブアプリとしてアクセスされたときにHTML(操作パネル)を表示する
*/
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('Index')
.setTitle('競馬分析コントロール');
}
// 会話の文脈を一時保持するサーバー側ストレージ
var conversationHistory = [];
/**
* メインの自律型AI処理ループ
*/
function executePipeline(userPrompt, fileDataArray, isContinue, uiConfig) {
const props = PropertiesService.getScriptProperties();
props.setProperty('STOP_FLAG', 'false');
let logs = [];
let progressPercent = 10;
let progressLabel = "初期化中...";
const config = uiConfig || {
mode: "ignore",
autoSuggest: false,
betType: "3連複フォーメーション",
selectedBetTypes: ["3連複フォーメーション"],
maxHorses: 0,
maxPoints: 0,
leg1: ["A"],
leg2: ["A", "B"],
leg3: ["A", "B", "C"]
};
if (!isContinue) {
conversationHistory = [];
logs.push("[システム] 分析を開始しました。");
}
if (fileDataArray && fileDataArray.length > 0) {
const imgCount = fileDataArray.filter(f => f && /^image\//i.test(f.type || "")).length;
logs.push(`[システム] ${fileDataArray.length}件のファイルを読み込みました(画像: ${imgCount}枚)。`);
}
// Step 1: 画像文字データ化&定量計算
progressPercent = 35;
progressLabel = "画像文字データ化・偏差値・買い目算出中...";
let quantAnalysisText = "";
let quantData = null;
try {
quantData = runQuantitativeRaceEngine_(fileDataArray, config);
quantAnalysisText = quantData.formattedText;
logs.push("[定量計算] 画像文字データ取り込み・偏差値・グループ・券種算出完了。");
} catch (err) {
quantAnalysisText = `[定量計算メモ] ${err.message}`;
logs.push(`[定量計算メモ] ${err.message}`);
}
if (props.getProperty('STOP_FLAG') === 'true') {
logs.push("【停止】中断しました。");
return {
success: true,
progressPercent: 100,
progressLabel: "停止済み",
message: logs.join("\n"),
quantData: quantData
};
}
const baseRule = props.getProperty('RULE_TEXT') || "正確かつ簡潔に分析を行い、実用的な成果物を提示すること。";
const modeRule =
config.mode === "ignore" ? "オッズと人気は完全に無視し、実数値の偏差値のみを根拠とすること。" :
config.mode === "use" ? "直前予想として、オッズ・人気の序列をベースに判断すること。" :
"偏差値グループと人気オッズグループの比較結果(特に偏差値より上位人気に推されている「あり」の馬)を重視すること。";
const targetBetLabel = config.autoSuggest
? "提案型(自動選択)"
: (config.betType || (config.selectedBetTypes && config.selectedBetTypes.join("、")) || "3連複フォーメーション");
const antiHallucinationRule = baseRule +
"\n\n【最重要ルール】" +
"\n1. 不確実な情報や推測を事実であるかのように出力しないこと。" +
"\n2. 根拠のない具体的な数値や架空のデータをでっち上げないこと。" +
"\n3. 偏差値・グループ分け・難易度・点数は【定量統計算出結果】の数値を絶対の事実とし、独自に改変しないこと。" +
"\n4. " + modeRule +
"\n5. 対象券種・フォーメーション(" + targetBetLabel + ")を中心に簡潔に解説すること。";
const fullContextPrompt = `【対象券種】${targetBetLabel}\n\n【定量統計算出結果(実数値ベース)】\n${quantAnalysisText}`;
// Step 2: 専門家並列処理
progressPercent = 75;
progressLabel = "各視点から並列分析中...";
logs.push("[処理] テクニカル・リスク・戦略の3視点で並列分析中...");
const targetFile = (fileDataArray && fileDataArray.length > 0) ? fileDataArray : null;
const specialistResults = executeParallelSpecialists(fullContextPrompt, antiHallucinationRule, targetFile);
// Step 3: 統合完了
progressPercent = 100;
progressLabel = "分析完了";
const integratedOutput = `${quantAnalysisText}\n\n====================\n\n` + integrateResults(specialistResults);
logs.push(`[完了]\n\n${integratedOutput}`);
conversationHistory.push(`対象: ${targetBetLabel}\n分析結果:\n${integratedOutput}`);
return {
success: true,
progressPercent: progressPercent,
progressLabel: progressLabel,
message: logs.join("\n"),
quantData: quantData
};
}
function normalizePersonName_(name) {
return String(name || "")
.replace(/[\s ]+/g, "")
.replace(/([^)]*)/g, "")
.replace(/\([^)]*\)/g, "")
.replace(/^(?:[A-Z]\.|[A-Za-z]+\.)/, "")
.trim();
}
/**
* 勝率表記(0.145 や 14.5%)を % 数値(14.5)に正規化する
*/
function normalizeWinRate_(rawVal) {
const num = parseFloat(String(rawVal).replace(/%/g, "").trim());
if (isNaN(num) || num < 0) return null;
if (num > 0 && num <= 1.0) {
return Number((num * 100).toFixed(2));
}
return Number(num.toFixed(2));
}
/**
* 添付画像(複数枚可)から出馬表・リーディング情報を構造化テキストへ変換する
*/
function extractTextFromImages_(fileDataArray) {
if (!fileDataArray || !Array.isArray(fileDataArray) || fileDataArray.length === 0) {
return "";
}
const imageFiles = fileDataArray.filter(f => f && /^image\//i.test(f.type || "") && f.base64);
if (imageFiles.length === 0) {
return "";
}
const prompt = [
"添付された画像(JRAの出馬表・成績・騎手リーディング・調教師リーディング等)から、読み取れる情報を文字データとして出力してください。",
"推測や架空の数値は絶対に入れず、画像に明記されている情報のみを出力してください。",
"1. リーディング表の行は次のように出力してください:",
"騎手:川田将雅 騎手勝率:21.3",
"調教師:福永祐一 調教師勝率:14.7",
"2. 出馬表の馬ごとの行は、読み取れる項目を1行にまとめて出力してください(不明な項目は省略可):",
"馬番:10 騎手:J.モレイラ 調教師:福永祐一 4角:4 着順:2 上がり3F:33.9 オッズ:3.1 人気:2",
"※出走取消や除外の馬は「取消」と明記してください。"
].join("\n");
const extracted = callGeminiAPI(
prompt,
"あなたは競馬画像から明記された数値と名称のみを抽出して整形する文字起こし処理です。",
imageFiles
);
if (!extracted || extracted.startsWith("APIエラー")) {
return "";
}
return extracted.trim();
}
/**
* 文字データから騎手・調教師の勝率マップ(%換算)を抽出する
*/
function extractLeadingRatesFromText_(text) {
const rates = { jockeys: {}, trainers: {} };
if (!text) return rates;
const lines = text.split(/\r?\n/);
lines.forEach(line => {
const jName = line.match(/(?:騎手名|騎手)[::\s]*([^\s,|/]+)/);
const jRate = line.match(/(?:騎手勝率|騎手率|勝率)[::\s]*([0-9]+(?:\.[0-9]+)?%?)/);
if (jName && jRate) {
const val = normalizeWinRate_(jRate[1]);
if (val !== null) {
rates.jockeys[normalizePersonName_(jName[1])] = val;
}
}
const tName = line.match(/(?:調教師名|調教師)[::\s]*([^\s,|/]+)/);
const tRate = line.match(/(?:調教師勝率|調教師率|勝率)[::\s]*([0-9]+(?:\.[0-9]+)?%?)/);
if (tName && tRate) {
const val = normalizeWinRate_(tRate[1]);
if (val !== null) {
rates.trainers[normalizePersonName_(tName[1])] = val;
}
}
});
return rates;
}
/**
* 【定量エンジン】
*/
function runQuantitativeRaceEngine_(fileDataArray, config) {
const fileText = extractTextFromSelectedFiles_(fileDataArray);
const imageText = extractTextFromImages_(fileDataArray);
const combinedText = [fileText, imageText].filter(t => t && t.trim() !== "").join("\n");
if (!combinedText || combinedText.trim() === "") {
throw new Error("選択された画像・ファイルから解析可能な文字データを抽出できませんでした。");
}
const leadingRates = extractLeadingRatesFromText_(combinedText);
const horses = parseHorsesFromText_(combinedText, leadingRates);
if (horses.length === 0) {
throw new Error("文字データから馬ごとの数値(馬番・騎手・調教師等)を抽出できませんでした。");
}
const jockeyStats = calcStats_(horses.map(h => h.jockeyRate));
const trainerStats = calcStats_(horses.map(h => h.trainerRate));
const corner4Stats = calcStats_(horses.map(h => -h.corner4));
const finishStats = calcStats_(horses.map(h => -h.finishOrder));
const agari3fStats = calcStats_(horses.map(h => -h.agari3f));
horses.forEach(h => {
h.jockeyDev = calcDeviation_(h.jockeyRate, jockeyStats);
h.trainerDev = calcDeviation_(h.trainerRate, trainerStats);
h.corner4Dev = calcDeviation_(-h.corner4, corner4Stats);
h.finishDev = calcDeviation_(-h.finishOrder, finishStats);
h.agari3fDev = calcDeviation_(-h.agari3f, agari3fStats);
h.horsePerfDev = (h.corner4Dev + h.finishDev + h.agari3fDev) / 3.0;
h.compositeDev = (h.jockeyDev + h.trainerDev + h.corner4Dev + h.finishDev + h.agari3fDev) / 5.0;
});
const devGroups = buildGroupsByMetric_(horses, h => h.compositeDev);
const hasOddsData = horses.some(h => h.odds !== null || h.popularity !== null);
let popGroups = { groupA: [], groupB: [], groupC: [] };
if (hasOddsData) {
popGroups = buildGroupsByMetric_(horses, h => {
if (h.odds !== null && h.odds > 0) return -h.odds;
if (h.popularity !== null && h.popularity > 0) return -h.popularity;
return -9999;
});
}
const comparisonReport = compareDevAndPopGroups_(horses, devGroups, popGroups, hasOddsData);
const difficulty = evaluateRaceDifficulty_(horses);
let activeGroups = devGroups;
if (config.mode === "use" && hasOddsData) {
activeGroups = popGroups;
} else if (config.mode === "compare" && hasOddsData) {
activeGroups = buildMergedCompareGroups_(devGroups, comparisonReport);
}
const firstCandidatesResult = selectFirstPlaceCandidates_(activeGroups.groupA, activeGroups.groupB);
let selectedLegs = {
leg1: Array.isArray(config.leg1) ? config.leg1 : ["A"],
leg2: Array.isArray(config.leg2) ? config.leg2 : ["A", "B"],
leg3: Array.isArray(config.leg3) ? config.leg3 : ["A", "B", "C"]
};
if (config.autoSuggest) {
selectedLegs = autoSuggestFormationLegs_(difficulty, config.maxHorses, config.maxPoints, activeGroups);
}
const formationResult = calcSanrenpukuFormation_(
selectedLegs,
activeGroups,
Number(config.maxHorses) || 0,
Number(config.maxPoints) || 0
);
const formattedText = formatQuantitativeReport_({
config,
leadingRates,
hasOddsData,
devGroups,
popGroups,
activeGroups,
comparisonReport,
difficulty,
firstCandidatesResult,
formationResult
});
return {
suggestedLegs: selectedLegs,
difficulty: difficulty,
totalPoints: formationResult.totalPoints,
totalUniqueHorses: formationResult.uniqueHorseCount,
formattedText: formattedText
};
}
/**
* 出走頭数に応じたグループA(A1-A4)・B(B1-B4)・C(C1-C4)の割り当て
* ・12頭以上: A4 / B4 / C4
* ・10頭: A4 / B4 / C2
* ・8頭: A4 / B4 / Cなし
* ・6頭: A4 / B2 / Cなし
*/
function buildGroupsByMetric_(horses, scoreFn) {
const sorted = horses.slice().sort((a, b) => scoreFn(b) - scoreFn(a));
const total = sorted.length;
let countA = 0;
let countB = 0;
let countC = 0;
if (total >= 12) {
countA = 4;
countB = 4;
countC = 4;
} else if (total === 10) {
countA = 4;
countB = 4;
countC = 2;
} else if (total === 8) {
countA = 4;
countB = 4;
countC = 0;
} else if (total === 6) {
countA = 4;
countB = 2;
countC = 0;
} else {
countA = Math.min(4, total);
countB = Math.min(4, Math.max(0, total - countA));
countC = Math.min(4, Math.max(0, total - countA - countB));
}
const labelsA = ["A1", "A2", "A3", "A4"];
const labelsB = ["B1", "B2", "B3", "B4"];
const labelsC = ["C1", "C2", "C3", "C4"];
const groupA = sorted.slice(0, countA).map((h, idx) =>
Object.assign({}, h, { slot: labelsA[idx], block: "グループA" })
);
const groupB = sorted.slice(countA, countA + countB).map((h, idx) =>
Object.assign({}, h, { slot: labelsB[idx], block: "グループB" })
);
const groupC = sorted.slice(countA + countB, countA + countB + countC).map((h, idx) =>
Object.assign({}, h, { slot: labelsC[idx], block: "グループC" })
);
return { groupA, groupB, groupC };
}
function compareDevAndPopGroups_(horses, devGroups, popGroups, hasOddsData) {
if (!hasOddsData) {
return { available: false, summary: "データ内にオッズ・人気数値がないため比較スキップ" };
}
const getRank = (groups, id) => {
if (groups.groupA.some(h => h.id === id)) return { label: "A", val: 3 };
if (groups.groupB.some(h => h.id === id)) return { label: "B", val: 2 };
if (groups.groupC.some(h => h.id === id)) return { label: "C", val: 1 };
return { label: "圏外", val: 0 };
};
const sameGroup = [], diffGroup = [], outToIn = [], outToOut = [], higherPopAri = [], lowerPopNashi = [];
horses.forEach(h => {
const d = getRank(devGroups, h.id);
const p = getRank(popGroups, h.id);
const tag = `馬番${h.id}(偏差値:${d.label} / 人気:${p.label})`;
if (d.val > 0 && d.val === p.val) sameGroup.push(tag);
else if (d.val > 0 && d.val !== p.val) diffGroup.push(tag);
else if (d.val === 0 && p.val > 0) outToIn.push(tag);
else outToOut.push(tag);
if (p.val > d.val) higherPopAri.push(Object.assign({}, h, { label: tag }));
if (d.val > 0 && p.val < d.val) lowerPopNashi.push(Object.assign({}, h, { label: tag }));
});
return { available: true, sameGroup, diffGroup, outToIn, outToOut, higherPopAri, lowerPopNashi };
}
function buildMergedCompareGroups_(devGroups, comp) {
if (!comp.available) return devGroups;
const nashiIds = new Set(comp.lowerPopNashi.map(h => h.id));
const filterOutNashi = (list) => list.filter(h => !nashiIds.has(h.id));
return {
groupA: filterOutNashi(devGroups.groupA),
groupB: filterOutNashi(devGroups.groupB),
groupC: filterOutNashi(devGroups.groupC)
};
}
function evaluateRaceDifficulty_(horses) {
const top4 = horses.slice().sort((a, b) => b.compositeDev - a.compositeDev).slice(0, 4);
if (top4.length === 0) {
return { level: "判定不能", reason: "データ不足", recommendedLegs: { leg1: ["A"], leg2: ["A", "B"], leg3: ["A", "B", "C"] } };
}
const avgJockey = top4.reduce((s, h) => s + h.jockeyDev, 0) / top4.length;
const avgHorse = top4.reduce((s, h) => s + h.horsePerfDev, 0) / top4.length;
const alignedCount = top4.filter(h => h.jockeyDev >= 55 && h.horsePerfDev >= 55).length;
if (alignedCount >= 3 && avgJockey >= 58 && avgHorse >= 58) {
return {
level: "低(堅実・軸明確)",
reason: `上位馬の騎手偏差値(平均${avgJockey.toFixed(1)})と馬成績偏差値(平均${avgHorse.toFixed(1)})が高く一致`,
recommendedLegs: { leg1: ["A"], leg2: ["A", "B"], leg3: ["A", "B"] }
};
} else if (alignedCount >= 1 && (avgJockey >= 53 || avgHorse >= 53)) {
return {
level: "中(標準・相手手広く)",
reason: `騎手成績と馬成績のバランスが標準的(一致頭数:${alignedCount}頭)`,
recommendedLegs: { leg1: ["A"], leg2: ["A", "B"], leg3: ["A", "B", "C"] }
};
} else {
return {
level: "高(波乱含み・広め推奨)",
reason: `上位馬で騎手偏差値と馬成績偏差値の乖離が大きい(一致頭数:${alignedCount}頭)`,
recommendedLegs: { leg1: ["A", "B"], leg2: ["A", "B", "C"], leg3: ["A", "B", "C"] }
};
}
}
function autoSuggestFormationLegs_(difficulty, maxHorses, maxPoints, groups) {
const candidates = [
difficulty.recommendedLegs,
{ leg1: ["A"], leg2: ["A", "B"], leg3: ["A", "B", "C"] },
{ leg1: ["A"], leg2: ["A", "B"], leg3: ["A", "B"] },
{ leg1: ["A"], leg2: ["A"], leg3: ["A", "B", "C"] },
{ leg1: ["A"], leg2: ["A"], leg3: ["A", "B"] },
{ leg1: ["A"], leg2: ["A"], leg3: ["A"] }
];
const hLimit = Number(maxHorses) || 0;
const pLimit = Number(maxPoints) || 0;
for (let i = 0; i < candidates.length; i++) {
const res = calcSanrenpukuFormation_(candidates[i], groups, 0, 0);
const okHorses = (hLimit === 0 || res.uniqueHorseCount <= hLimit);
const okPoints = (pLimit === 0 || res.totalPoints <= pLimit);
if (okHorses && okPoints && res.totalPoints > 0) {
return candidates[i];
}
}
return { leg1: ["A"], leg2: ["A"], leg3: ["A"] };
}
function selectFirstPlaceCandidates_(groupA, groupB) {
let condA1 = groupA.filter(h => h.trainerDev >= 65 && h.jockeyDev >= 65);
if (condA1.length > 0) return { sourceGroup: "グループA", ruleApplied: "調教師偏差値65以上 かつ 騎手偏差値65以上", candidates: condA1 };
let condA2 = groupA.filter(h => h.trainerDev >= 65 && h.jockeyDev < 60);
if (condA2.length > 0) return { sourceGroup: "グループA", ruleApplied: "調教師偏差値65以上 かつ 騎手偏差値60未満", candidates: condA2 };
let condA3 = groupA.filter(h => h.trainerDev >= 60 && h.jockeyDev < 50);
if (condA3.length > 0) return { sourceGroup: "グループA", ruleApplied: "調教師偏差値60以上 かつ 騎手偏差値50未満", candidates: condA3 };
const eligibleB = groupB.filter(h => h.trainerDev >= 50);
let condB1 = eligibleB.filter(h => h.trainerDev >= 50 && h.jockeyDev >= 50);
if (condB1.length > 0) return { sourceGroup: "グループB", ruleApplied: "調教師偏差値50以上 かつ 騎手偏差値50以上(調教師50未満は除外)", candidates: condB1 };
return { sourceGroup: "なし", ruleApplied: "条件合致馬なし(調教師偏差値50未満は除外)", candidates: [] };
}
function calcSanrenpukuFormation_(legs, groups, maxHorses, maxPoints) {
const mapGroup = { "A": groups.groupA, "B": groups.groupB, "C": groups.groupC };
const collectUniqueHorses = (gNames) => {
const seen = new Set();
const arr = [];
(gNames || []).forEach(g => {
(mapGroup[g] || []).forEach(h => {
if (!seen.has(h.id)) {
seen.add(h.id);
arr.push(h);
}
});
});
return arr;
};
let leg1Objs = collectUniqueHorses(legs.leg1);
let leg2Objs = collectUniqueHorses(legs.leg2);
let leg3Objs = collectUniqueHorses(legs.leg3);
if (maxHorses > 0) {
const allSelectedMap = new Map();
[...leg1Objs, ...leg2Objs, ...leg3Objs].forEach(h => allSelectedMap.set(h.id, h));
const allowedIds = new Set(
Array.from(allSelectedMap.values())
.sort((a, b) => b.compositeDev - a.compositeDev)
.slice(0, maxHorses)
.map(h => h.id)
);
leg1Objs = leg1Objs.filter(h => allowedIds.has(h.id));
leg2Objs = leg2Objs.filter(h => allowedIds.has(h.id));
leg3Objs = leg3Objs.filter(h => allowedIds.has(h.id));
}
if (leg1Objs.length === 0 || leg2Objs.length === 0 || leg3Objs.length === 0) {
return {
leg1Groups: legs.leg1,
leg2Groups: legs.leg2,
leg3Groups: legs.leg3,
leg1Labels: leg1Objs.map(h => `${h.slot}(馬番:${h.id})`),
leg2Labels: leg2Objs.map(h => `${h.slot}(馬番:${h.id})`),
leg3Labels: leg3Objs.map(h => `${h.slot}(馬番:${h.id})`),
uniqueHorseCount: new Set([...leg1Objs, ...leg2Objs, ...leg3Objs].map(h => h.id)).size,
totalPoints: 0,
truncatedByPoints: false
};
}
const comboMap = new Map();
for (let i = 0; i < leg1Objs.length; i++) {
for (let j = 0; j < leg2Objs.length; j++) {
for (let k = 0; k < leg3Objs.length; k++) {
const a = leg1Objs[i], b = leg2Objs[j], c = leg3Objs[k];
if (a.id !== b.id && b.id !== c.id && a.id !== c.id) {
const sorted = [a, b, c].sort((x, y) => String(x.id).localeCompare(String(y.id)));
const key = sorted.map(x => `${x.slot}(馬番:${x.id})`).join(" - ");
const score = a.compositeDev + b.compositeDev + c.compositeDev;
if (!comboMap.has(key)) comboMap.set(key, score);
}
}
}
}
let comboEntries = Array.from(comboMap.entries()).sort((a, b) => b[1] - a[1]);
let truncatedByPoints = false;
if (maxPoints > 0 && comboEntries.length > maxPoints) {
comboEntries = comboEntries.slice(0, maxPoints);
truncatedByPoints = true;
}
const uniqueHorseCount = new Set([...leg1Objs, ...leg2Objs, ...leg3Objs].map(h => h.id)).size;
return {
leg1Groups: legs.leg1,
leg2Groups: legs.leg2,
leg3Groups: legs.leg3,
leg1Labels: leg1Objs.map(h => `${h.slot}(馬番:${h.id})`),
leg2Labels: leg2Objs.map(h => `${h.slot}(馬番:${h.id})`),
leg3Labels: leg3Objs.map(h => `${h.slot}(馬番:${h.id})`),
uniqueHorseCount: uniqueHorseCount,
totalPoints: comboEntries.length,
truncatedByPoints: truncatedByPoints
};
}
function parseHorsesFromText_(text, leadingRates) {
const lines = text.split(/\r?\n/);
const horses = [];
lines.forEach(line => {
const trimmed = line.trim();
if (!trimmed) return;
if (/取消|除外/.test(trimmed)) return;
const horseNoMatch = trimmed.match(/(?:馬番|No\.?|no\.?)[::\s]*([0-9]{1,2})/i);
if (!horseNoMatch) return;
const jockeyRateMatch = trimmed.match(/(?:騎手勝率|騎手率)[::\s]*([0-9]+(?:\.[0-9]+)?%?)/);
const trainerRateMatch = trimmed.match(/(?:調教師勝率|調教師率)[::\s]*([0-9]+(?:\.[0-9]+)?%?)/);
const jockeyNameMatch = trimmed.match(/(?:騎手名|騎手)[::\s]*([^\s,|/]+)/);
const trainerNameMatch = trimmed.match(/(?:調教師名|調教師)[::\s]*([^\s,|/]+)/);
let jockeyRate = jockeyRateMatch ? normalizeWinRate_(jockeyRateMatch[1]) : null;
let trainerRate = trainerRateMatch ? normalizeWinRate_(trainerRateMatch[1]) : null;
if (jockeyRate === null && jockeyNameMatch && leadingRates && leadingRates.jockeys) {
const jKey = normalizePersonName_(jockeyNameMatch[1]);
if (typeof leadingRates.jockeys[jKey] === "number") {
jockeyRate = leadingRates.jockeys[jKey];
}
}
if (trainerRate === null && trainerNameMatch && leadingRates && leadingRates.trainers) {
const tKey = normalizePersonName_(trainerNameMatch[1]);
if (typeof leadingRates.trainers[tKey] === "number") {
trainerRate = leadingRates.trainers[tKey];
}
}
const corner4Match = trimmed.match(/(?:4コーナー|4角|4C)[::\s]*([0-9]+(?:\.[0-9]+)?)/);
const finishMatch = trimmed.match(/(?:着順|着)[::\s]*([0-9]+)/);
const agari3fMatch = trimmed.match(/(?:上がり3F|上3F|3F)[::\s]*([0-9]+(?:\.[0-9]+)?)/);
const oddsMatch = trimmed.match(/(?:単勝オッズ|オッズ)[::\s]*([0-9]+(?:\.[0-9]+)?)/);
const popMatch = trimmed.match(/(?:人気順|人気)[::\s]*([0-9]+)/);
horses.push({
id: horseNoMatch[1],
jockeyRate: jockeyRate !== null ? jockeyRate : 10.0,
trainerRate: trainerRate !== null ? trainerRate : 10.0,
corner4: corner4Match ? parseFloat(corner4Match[1]) : 5.0,
finishOrder: finishMatch ? parseFloat(finishMatch[1]) : 5.0,
agari3f: agari3fMatch ? parseFloat(agari3fMatch[1]) : 34.5,
odds: oddsMatch ? parseFloat(oddsMatch[1]) : null,
popularity: popMatch ? parseFloat(popMatch[1]) : null
});
});
return horses;
}
function extractTextFromSelectedFiles_(fileDataArray) {
if (!fileDataArray || !Array.isArray(fileDataArray) || fileDataArray.length === 0) return "";
const texts = [];
fileDataArray.forEach(file => {
if (!file) return;
if (typeof file.text === "string" && file.text.trim() !== "") {
texts.push(file.text);
return;
}
const mime = (file.type || "").toLowerCase();
const name = (file.name || "").toLowerCase();
const isTextLike =
mime.startsWith("text/") || mime.includes("csv") || mime.includes("json") ||
name.endsWith(".txt") || name.endsWith(".csv") || name.endsWith(".tsv") || name.endsWith(".md");
if (isTextLike && file.base64) {
try {
const bytes = Utilities.base64Decode(file.base64);
texts.push(Utilities.newBlob(bytes).getDataAsString("UTF-8"));
} catch (e) {}
}
});
return texts.join("\n");
}
function calcStats_(values) {
const n = values.length;
const mean = values.reduce((acc, v) => acc + v, 0) / n;
const variance = values.reduce((acc, v) => acc + Math.pow(v - mean, 2), 0) / n;
return { n, mean, variance, stdDev: Math.sqrt(variance) };
}
function calcDeviation_(value, stats) {
if (!stats || stats.stdDev === 0 || isNaN(stats.stdDev)) return 50.0;
return 50.0 + 10.0 * ((value - stats.mean) / stats.stdDev);
}
function formatQuantitativeReport_(p) {
const fmt = (n) => Number(n).toFixed(2);
const modeLabel =
p.config.mode === "ignore" ? "①オッズ人気は無視されるプロトタイプ" :
p.config.mode === "use" ? "②オッズ人気は無視されないプロトタイプ(直前予想向け)" :
"③オッズ人気と比較されるタイプ";
const jCount = Object.keys((p.leadingRates && p.leadingRates.jockeys) || {}).length;
const tCount = Object.keys((p.leadingRates && p.leadingRates.trainers) || {}).length;
const betLabel = p.config.autoSuggest
? "提案型(自動選択)"
: (p.config.betType || (p.config.selectedBetTypes && p.config.selectedBetTypes.join("、")) || "3連複フォーメーション");
let out = [];
out.push(`【指定券種】${betLabel}`);
out.push(`【動作モード】${modeLabel}`);
out.push(`【文字データ連携】画像文字起こし・勝率突合済(騎手:${jCount}名 / 調教師:${tCount}名)`);
out.push(`【レース難易度】${p.difficulty.level}(${p.difficulty.reason})`);
out.push("\n【1】採用グループA / B / C");
out.push("グループA: " + (p.activeGroups.groupA.length > 0
? p.activeGroups.groupA.map(h => `${h.slot}=馬番${h.id}(騎手:${fmt(h.jockeyDev)}, 調教師:${fmt(h.trainerDev)})`).join(" / ")
: "なし"));
out.push("グループB: " + (p.activeGroups.groupB.length > 0
? p.activeGroups.groupB.map(h => `${h.slot}=馬番${h.id}(騎手:${fmt(h.jockeyDev)}, 調教師:${fmt(h.trainerDev)})`).join(" / ")
: "なし"));
out.push("グループC: " + (p.activeGroups.groupC.length > 0
? p.activeGroups.groupC.map(h => `${h.slot}=馬番${h.id}(騎手:${fmt(h.jockeyDev)}, 調教師:${fmt(h.trainerDev)})`).join(" / ")
: "なし"));
if (p.config.mode === "compare") {
out.push("\n【①偏差値グループ vs ②人気オッズグループ 比較】");
if (!p.comparisonReport.available) {
out.push(p.comparisonReport.summary);
} else {
const c = p.comparisonReport;
out.push(`・①で属し②で同じグループ: ${c.sameGroup.join(", ") || "なし"}`);
out.push(`・①で属し②で違うグループ: ${c.diffGroup.join(", ") || "なし"}`);
out.push(`・①で圏外だが②で属する馬: ${c.outToIn.join(", ") || "なし"}`);
out.push(`・①でも②でも圏外の馬: ${c.outToOut.join(", ") || "なし"}`);
out.push(`・偏差値グループより上位の人気グループに属する馬【あり】: ${c.higherPopAri.map(x => x.label).join(", ") || "なし"}`);
out.push(`・偏差値グループより下位の人気グループに属する馬【なし(除外)】: ${c.lowerPopNashi.map(x => x.label).join(", ") || "なし"}`);
}
}
out.push("\n【2】1着候補");
if (p.firstCandidatesResult.candidates.length > 0) {
out.push(`候補(${p.firstCandidatesResult.sourceGroup} / ${p.firstCandidatesResult.ruleApplied}): ` +
p.firstCandidatesResult.candidates.map(h => `${h.slot}[馬番:${h.id}]`).join("、 "));
} else {
out.push(`該当馬なし(${p.firstCandidatesResult.ruleApplied})`);
}
out.push("\n【3】フォーメーション・点数目安");
out.push(`1頭目: ${p.formationResult.leg1Groups.join(",") || "未選択"} [${p.formationResult.leg1Labels.join(", ")}]`);
out.push(`2頭目: ${p.formationResult.leg2Groups.join(",") || "未選択"} [${p.formationResult.leg2Labels.join(", ")}]`);
out.push(`3頭目: ${p.formationResult.leg3Groups.join(",") || "未選択"} [${p.formationResult.leg3Labels.join(", ")}]`);
out.push(`対象ユニーク頭数: ${p.formationResult.uniqueHorseCount} 頭${p.config.maxHorses > 0 ? `(上限: ${p.config.maxHorses}頭以内)` : ""}`);
out.push(`合計点数: ${p.formationResult.totalPoints} 点${p.config.maxPoints > 0 ? `(上限: ${p.config.maxPoints}点以内${p.formationResult.truncatedByPoints ? "・上限カット済" : ""})` : ""}`);
return out.join("\n");
}
function callGeminiAPI(promptText, systemInstructionText, fileDataArray) {
const props = PropertiesService.getScriptProperties();
const apiKey = props.getProperty('GEMINI_API_KEY');
const model = props.getProperty('GEMINI_MODEL');
const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`;
let parts = [{ text: promptText }];
if (fileDataArray && Array.isArray(fileDataArray)) {
fileDataArray.forEach(file => {
parts.push({ inlineData: { mimeType: file.type || "image/jpeg", data: file.base64 } });
});
}
try {
const response = UrlFetchApp.fetch(url, {
method: 'post',
contentType: 'application/json',
payload: JSON.stringify({
contents: [{ parts: parts }],
systemInstruction: { parts: [{ text: systemInstructionText }] }
}),
muteHttpExceptions: true
});
const json = JSON.parse(response.getContentText());
if (json.candidates && json.candidates[0]) {
return json.candidates[0].content.parts[0].text.replace(/```json/g, '').replace(/```/g, '').trim();
}
return "APIエラー: " + JSON.stringify(json);
} catch (e) {
return "APIエラー例外: " + e.toString();
}
}
function executeParallelSpecialists(contextText, systemInstructionText, fileDataArray) {
const props = PropertiesService.getScriptProperties();
const apiKey = props.getProperty('GEMINI_API_KEY');
const model = props.getProperty('GEMINI_MODEL');
const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`;
const domains = [
{ name: "テクニカル分析", focus: "偏差値・人気比較・難易度数値の正確な読み取り。" },
{ name: "リスク評価", focus: "懸念点・取りこぼしリスク・上限点数とのバランスの厳密な評価。" },
{ name: "戦略・シナリオ", focus: "指定された券種・フォーメーションに基づく具体的な買い目戦略。" }
];
const requests = domains.map(domain => {
let parts = [{ text: `あなたは「${domain.name}」の専門家です(専門: ${domain.focus})。以下の定量計算結果に基づき専門的な分析のみを簡潔に出力してください:\n\n${contextText}` }];
if (fileDataArray && Array.isArray(fileDataArray)) {
fileDataArray.forEach(file => {
parts.push({ inlineData: { mimeType: file.type || "image/jpeg", data: file.base64 } });
});
}
return {
url: url,
method: 'post',
contentType: 'application/json',
payload: JSON.stringify({
contents: [{ parts: parts }],
systemInstruction: { parts: [{ text: systemInstructionText }] }
}),
muteHttpExceptions: true
};
});
const responses = UrlFetchApp.fetchAll(requests);
return responses.map((res, index) => {
try {
const json = JSON.parse(res.getContentText());
let text = json.candidates && json.candidates[0] ? json.candidates[0].content.parts[0].text : "出力なし";
return { domain: domains[index].name, result: text.replace(/```json/g, '').replace(/```/g, '').trim() };
} catch (e) {
return { domain: domains[index].name, result: "処理エラー" };
}
});
}
function integrateResults(specialistResults) {
return specialistResults.map(s => `[${s.domain}]\n${s.result}`).join("\n\n--------------------\n\n");
}
【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>競馬分析コントロール</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
margin: 0;
padding: 16px;
background: #f4f6f9;
color: #1f2937;
}
.container {
max-width: 960px;
margin: 0 auto;
background: #ffffff;
border-radius: 12px;
padding: 20px;
box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}
h1 {
font-size: 1.25rem;
margin: 0 0 16px;
}
.section {
margin-bottom: 14px;
padding: 12px;
border: 1px solid #e5e7eb;
border-radius: 8px;
background: #fafafa;
}
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
gap: 8px;
flex-wrap: wrap;
}
.section-title {
font-weight: 700;
font-size: 0.95rem;
}
.btn-row {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
}
.bet-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
gap: 8px;
margin-top: 8px;
}
button {
padding: 10px 14px;
border: none;
border-radius: 8px;
font-size: 0.9rem;
font-weight: 600;
cursor: pointer;
}
.btn-select { background: #e0e7ff; color: #1e3a8a; }
.btn-bet { background: #2563eb; color: #ffffff; }
.btn-bet.active { background: #1d4ed8; outline: 2px solid #93c5fd; }
.btn-auto { background: #059669; color: #ffffff; }
.btn-clear { background: #e5e7eb; color: #374151; padding: 6px 10px; font-size: 0.82rem; }
.progress-wrap {
background: #ffffff;
border: 1px solid #d1d5db;
border-radius: 8px;
padding: 12px;
margin-bottom: 14px;
}
.progress-top {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 0.9rem;
font-weight: 700;
margin-bottom: 8px;
}
.progress-track {
width: 100%;
height: 16px;
background: #e5e7eb;
border-radius: 999px;
overflow: hidden;
}
.progress-fill {
height: 100%;
width: 0%;
background: #2563eb;
transition: width 0.35s ease, background-color 0.25s ease;
}
.progress-fill.done { background: #059669; }
.progress-fill.stopped { background: #dc2626; }
.mode-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.mode-card {
background: #ffffff;
border: 1px solid #d1d5db;
border-radius: 8px;
padding: 10px;
font-size: 0.88rem;
cursor: pointer;
display: flex;
align-items: center;
gap: 6px;
}
.limit-row {
display: flex;
flex-wrap: wrap;
gap: 16px;
align-items: center;
}
.limit-item {
display: flex;
align-items: center;
gap: 6px;
font-size: 0.9rem;
}
input[type="number"] {
width: 72px;
padding: 6px 8px;
border: 1px solid #d1d5db;
border-radius: 6px;
font-size: 0.9rem;
}
.file-list {
font-size: 0.84rem;
color: #4b5563;
max-height: 110px;
overflow-y: auto;
white-space: pre-line;
margin-top: 8px;
}
.log-box {
width: 100%;
min-height: 340px;
background: #111827;
color: #f9fafb;
padding: 14px;
border-radius: 8px;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.85rem;
white-space: pre-wrap;
overflow-y: auto;
box-sizing: border-box;
}
input[type="file"] { display: none; }
</style>
</head>
<body>
<div class="container">
<h1>競馬分析コントロール</h1>
<div class="progress-wrap">
<div class="progress-top">
<span id="progressStatusText">待機中</span>
<span id="progressPercentText">0%</span>
</div>
<div class="progress-track">
<div id="progressBarFill" class="progress-fill"></div>
</div>
</div>
<div class="section">
<div class="section-header">
<div class="section-title">出馬表と騎手リーディングと調教師リーディングの撮影画像</div>
<button type="button" class="btn-clear" onclick="clearFiles()">選択クリア</button>
</div>
<div class="btn-row">
<button type="button" class="btn-select" onclick="document.getElementById('imageInput').click()">画像選択(複数選択可)</button>
</div>
<input type="file" id="imageInput" accept="image/*" multiple onchange="handleFilesSelected(this.files)" />
<div id="fileListDisplay" class="file-list">選択中の画像: 0件</div>
</div>
<div class="section">
<div class="section-header">
<div class="section-title">プロトタイプ判定モード</div>
<button type="button" class="btn-clear" onclick="resetModeAndLimits()">条件クリア</button>
</div>
<div class="mode-grid">
<label class="mode-card">
<input type="radio" name="protoMode" value="ignore" checked />
<span>①オッズ人気無視(偏差値のみ)</span>
</label>
<label class="mode-card">
<input type="radio" name="protoMode" value="use" />
<span>②オッズ人気重視(直前予想向け)</span>
</label>
<label class="mode-card">
<input type="radio" name="protoMode" value="compare" />
<span>③オッズ人気比較(あり/なし判定)</span>
</label>
</div>
<div class="limit-row" style="margin-top:10px;">
<div class="limit-item">
<label for="maxHorses">対象頭数上限:</label>
<input type="number" id="maxHorses" min="0" max="18" placeholder="未指定" />
<span>頭以内</span>
</div>
<div class="limit-item">
<label for="maxPoints">買い目点数上限:</label>
<input type="number" id="maxPoints" min="0" max="500" placeholder="未指定" />
<span>点以内</span>
</div>
</div>
</div>
<div class="section">
<div class="section-header">
<div class="section-title">券種・フォーメーション</div>
<div class="btn-row">
<button type="button" class="btn-auto" onclick="runAutoSuggest()">提案型(自動選択で実行)</button>
<button type="button" class="btn-clear" onclick="clearAllBetTypes()">全項目クリア</button>
</div>
</div>
<div class="bet-grid">
<button type="button" class="btn-bet" data-bet="単勝" onclick="runBetType('単勝', this)">単勝</button>
<button type="button" class="btn-bet" data-bet="複勝" onclick="runBetType('複勝', this)">複勝</button>
<button type="button" class="btn-bet" data-bet="ワイド" onclick="runBetType('ワイド', this)">ワイド</button>
<button type="button" class="btn-bet" data-bet="馬連" onclick="runBetType('馬連', this)">馬連</button>
<button type="button" class="btn-bet" data-bet="馬単" onclick="runBetType('馬単', this)">馬単</button>
<button type="button" class="btn-bet" data-bet="3連複フォーメーション" onclick="runBetType('3連複フォーメーション', this)">3連複フォーメーション</button>
<button type="button" class="btn-bet" data-bet="3連単フォーメーション" onclick="runBetType('3連単フォーメーション', this)">3連単フォーメーション</button>
</div>
</div>
<div class="section">
<div class="section-title" style="margin-bottom:8px;">実行ログ・算出結果</div>
<div id="logOutput" class="log-box">待機中...</div>
</div>
</div>
<script>
let selectedFiles = [];
let selectedBetTypes = [];
let activeBetType = "3連複フォーメーション";
let progressTimer = null;
function updateProgressMeter(percent, label, state) {
const clamped = Math.max(0, Math.min(100, Number(percent) || 0));
const fill = document.getElementById("progressBarFill");
const statusText = document.getElementById("progressStatusText");
const percentText = document.getElementById("progressPercentText");
fill.style.width = clamped + "%";
fill.classList.remove("done", "stopped");
if (state === "done") fill.classList.add("done");
if (state === "stopped") fill.classList.add("stopped");
statusText.textContent = label || "";
percentText.textContent = clamped + "%";
}
function startSimulatedProgress(initialLabel) {
stopSimulatedProgress();
let current = 15;
updateProgressMeter(current, initialLabel, "running");
progressTimer = setInterval(() => {
if (current < 85) {
current += 7;
const phaseLabel =
current < 40 ? "撮影画像読み取り・偏差値算出中..." :
"各視点から並列分析中...";
updateProgressMeter(current, phaseLabel, "running");
}
}, 600);
}
function stopSimulatedProgress() {
if (progressTimer) {
clearInterval(progressTimer);
progressTimer = null;
}
}
function handleFilesSelected(fileList) {
if (!fileList || fileList.length === 0) return;
const readers = Array.from(fileList).map(file => {
return new Promise(resolve => {
const reader = new FileReader();
reader.onload = () => {
const result = reader.result || "";
const base64Part = typeof result === "string" && result.includes(",") ? result.split(",")[1] : "";
resolve({
name: file.webkitRelativePath || file.name,
type: file.type || "application/octet-stream",
base64: base64Part
});
};
reader.onerror = () => resolve(null);
reader.readAsDataURL(file);
});
});
Promise.all(readers).then(items => {
selectedFiles = selectedFiles.concat(items.filter(Boolean));
renderFileList();
});
}
function clearFiles() {
selectedFiles = [];
document.getElementById("imageInput").value = "";
renderFileList();
}
function renderFileList() {
const el = document.getElementById("fileListDisplay");
if (selectedFiles.length === 0) {
el.textContent = "選択中の画像: 0件";
return;
}
el.textContent = `選択中の画像: ${selectedFiles.length}件\n` + selectedFiles.map(f => "・" + f.name).join("\n");
}
function resetModeAndLimits() {
document.querySelector('input[name="protoMode"][value="ignore"]').checked = true;
document.getElementById("maxHorses").value = "";
document.getElementById("maxPoints").value = "";
}
function clearAllBetTypes() {
selectedBetTypes = [];
document.querySelectorAll(".btn-bet").forEach(btn => btn.classList.remove("active"));
}
function collectUiConfig(isAutoSuggest, betTypeOverride) {
const modeEl = document.querySelector('input[name="protoMode"]:checked');
return {
mode: modeEl ? modeEl.value : "ignore",
autoSuggest: Boolean(isAutoSuggest),
betType: betTypeOverride || activeBetType,
selectedBetTypes: selectedBetTypes.slice(),
maxHorses: parseInt(document.getElementById("maxHorses").value, 10) || 0,
maxPoints: parseInt(document.getElementById("maxPoints").value, 10) || 0,
leg1: ["A"],
leg2: ["A", "B"],
leg3: ["A", "B", "C"]
};
}
function setBetButtonsDisabled(disabled) {
document.querySelectorAll(".btn-bet, .btn-auto").forEach(btn => {
btn.disabled = disabled;
});
}
function runAutoSuggest() {
runAnalysis(false, true, "提案型(自動選択)");
}
function runBetType(betType, btnEl) {
activeBetType = betType;
if (!selectedBetTypes.includes(betType)) {
selectedBetTypes.push(betType);
}
if (btnEl) {
btnEl.classList.add("active");
}
runAnalysis(false, false, betType);
}
function runAnalysis(isContinue, isAutoSuggest, labelName) {
const uiConfig = collectUiConfig(isAutoSuggest, labelName);
const logBox = document.getElementById("logOutput");
setBetButtonsDisabled(true);
const startLabel = isAutoSuggest
? "提案型(自動選択)で分析を実行中..."
: `${labelName || activeBetType} の分析を実行中...`;
logBox.textContent = startLabel;
startSimulatedProgress(startLabel);
google.script.run
.withSuccessHandler(res => {
stopSimulatedProgress();
setBetButtonsDisabled(false);
const finalPercent = (res && typeof res.progressPercent === "number") ? res.progressPercent : 100;
const finalLabel = (res && res.progressLabel) ? res.progressLabel : "分析完了";
updateProgressMeter(finalPercent, finalLabel, finalLabel === "停止済み" ? "stopped" : "done");
logBox.textContent = (res && res.message) ? res.message : "完了しました。";
})
.withFailureHandler(err => {
stopSimulatedProgress();
setBetButtonsDisabled(false);
updateProgressMeter(100, "エラー発生", "stopped");
logBox.textContent = "エラーが発生しました:\n" + (err && err.message ? err.message : err);
})
.executePipeline("", selectedFiles, isContinue, uiConfig);
}
</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回目以降のデプロイはデプロイを管理からペンマークを選んで新バージョンを選択する。
〔参考〕



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