文件
fenleixinxi/tmp_img/gen_poll.php
MiAn 133d425ec0 feat: 新增阿里云OSS适配器及分类图标优化
- 新增阿里云OSS SDK核心类库文件
- 新增OSS插件配置文件及钩子监听
- 新增分类图标SVG资源并优化为轻量化格式
- 替换定位接口为天地图逆地理编码接口
- 新增OSS图片缩略处理工具方法
2026-11-20 11:11:03 +08:00

233 行
8.1 KiB
PHP

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

<?php
/**
* Pollinations.ai 图片批量生成脚本(PHP 版)
*
* 特性:
* 1. 用 Pollinations 免费 API(公开,无需认证)
* 2. 只重跑占位图(176626 字节)或坏图
* 3. 带 402 限流重试(指数退避)
* 4. 用 PHP GD 裁掉右下角 pollinations.ai 水印
* 5. 每请求 sleep 1.2s 避免触发限流
*
* 用法: php tmp_img/gen_poll.php
*/
$Error = 0; $OK = 0; $SKIP = 0;
$PH = 176626; // Trae 占位图大小
$MIN_SIZE = 50000; // 真实图下限
$root = __DIR__ . '/..';
$srcFile = __DIR__ . '/categories.txt';
$outDir = __DIR__ . '/downloaded';
$idxFile = __DIR__ . '/gen_index.json';
$mapFile = __DIR__ . '/map.json';
@mkdir($outDir, 0755, true);
// ---- 加载辅助数据 ----
$map = json_decode(file_get_contents($mapFile), true);
$hint = $map['vege_en_hint'] ?? [];
$animals = $map['live_animal_map'] ?? [];
$eggs = $map['egg_list'] ?? [];
$waters = $map['water_list'] ?? [];
$processed = [];
if (file_exists($idxFile)) {
$raw = file_get_contents($idxFile);
if ($raw && $raw !== '{}') {
$decoded = json_decode($raw, true);
if (is_array($decoded)) $processed = $decoded;
}
}
function vegeEn($name) { global $hint; return $hint[$name] ?? $name; }
function liveAnimalEn($name) { global $animals; return $animals[$name] ?? null; }
/**
* prompt 完全照搬 generate_images.ps1 原始 Trae prompt
* 关键要素:竹筐+种植场景+薄荷绿氛围+真实摄影+13个负面词
*/
define('NO_TEXT', ', no text, no watermark, no logo, no signature, no artist tag, no caption, no brand mark, no subtitle, no embedded letters, no corner badge, no AI generated label, no copyright mark, no overlay text');
function buildPollPrompt($name, $kind) {
global $eggs, $waters;
$en = preg_replace('/[^a-zA-Z\s]/', '', vegeEn($name));
if ($kind === 'farm') {
// 蔬菜/水果
return "a bamboo basket full of fresh $en, placed on the soil of a $en farm or orchard field, background with rows of naturally growing $en plants or trees, natural daylight, bright fresh mint green mood, realistic photography style, close-up composition, 1:1 square" . NO_TEXT;
}
// general: 肉蛋家禽
$animalEn = liveAnimalEn($name);
if ($animalEn) {
$e = preg_replace('/[^a-zA-Z\s]/', '', $animalEn);
// 活畜
return "a herd of $e grazing or standing naturally on a green grass pasture or farmhouse courtyard, background with distant hills and blue sky, natural daylight, bright fresh mint green mood, realistic photography style, wide shot, 1:1 square composition" . NO_TEXT;
}
if (in_array($name, $eggs)) {
// 蛋类
return "a bamboo basket full of fresh $en with some green plants and straw decoration, placed on a rustic wooden table in a sunny farmhouse courtyard, natural daylight, warm pastoral mood with fresh mint green undertone, realistic photography, 1:1 square" . NO_TEXT;
}
if (in_array($name, $waters)) {
// 水产
return "a natural fish pond with various live fish swimming in clear blue water, surrounded by green grass and reed, natural daylight, fresh mint green mood, realistic photography, 1:1 square composition" . NO_TEXT;
}
// 默认(加工制品)
return "fresh $en arranged nicely on a rustic wooden table, background with farmhouse kitchen or market stall setting, natural daylight, fresh mint green mood, realistic photography style, close-up, 1:1 square" . NO_TEXT;
}
/**
* 下载 + 去水印(裁剪右下角 30x30 像素)
*/
function downloadAndCrop($prompt, $outFile) {
global $MIN_SIZE;
$url = "https://image.pollinations.ai/prompt/" . rawurlencode($prompt)
. "?width=1024&height=1024&nologo=true&enhance=true&seed=" . crc32($prompt);
$delays = [1, 3, 6, 12, 20];
foreach ($delays as $attempt => $wait) {
if ($attempt > 0) { echo " backoff {$wait}s...\n"; sleep($wait); }
@unlink($outFile);
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_FILE => fopen($outFile, 'wb'),
CURLOPT_TIMEOUT => 180,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => '',
]);
curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http === 402) { continue; }
if ($http !== 200) { echo " HTTP $http\n"; continue; }
$sz = filesize($outFile);
if ($sz < $MIN_SIZE) { echo " too small $sz\n"; continue; }
// 成功,尝试裁水印
try {
cropBottomRight($outFile, 30);
} catch (\Exception $e) {
// 裁不了就算了,保留原图
}
return $sz;
}
return false;
}
/** 裁掉右下角 $px 像素的水印 */
function cropBottomRight($file, $px = 30) {
$info = @getimagesize($file);
if (!$info) return;
[$w, $h, $type] = $info;
$newW = $w - $px;
$newH = $h - $px;
if ($newW <= 0 || $newH <= 0) return;
switch ($type) {
case IMAGETYPE_JPEG: $src = @imagecreatefromjpeg($file); break;
case IMAGETYPE_PNG: $src = @imagecreatefrompng($file); break;
case IMAGETYPE_WEBP: $src = @imagecreatefromwebp($file); break;
default: return;
}
if (!$src) return;
$dst = imagecreatetruecolor($newW, $newH);
imagecopy($dst, $src, 0, 0, 0, 0, $newW, $newH);
imagedestroy($src);
switch ($type) {
case IMAGETYPE_JPEG: imagejpeg($dst, $file, 85); break;
case IMAGETYPE_PNG: imagepng($dst, $file, 8); break;
case IMAGETYPE_WEBP: imagewebp($dst, $file, 85); break;
}
imagedestroy($dst);
}
// ---- 解析 categories.txt ----
$lines = file($srcFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$cats = [];
foreach ($lines as $line) {
if (!preg_match('/^\d+\t/', $line)) continue;
$parts = explode("\t", $line);
if (count($parts) < 4) continue;
$id = (int)$parts[0];
$pid = (int)$parts[1];
if ($pid === 0) continue;
$cats[$id] = [
'id' => $id,
'pid' => $pid,
'name' => trim($parts[2]),
'kind' => trim($parts[3]),
];
}
$total = count($cats);
echo "POLLINATIONS GENERATOR\n";
echo "Total secondary categories: $total\n\n";
// ---- 主循环 ----
$t0 = microtime(true);
foreach ($cats as $id => $cat) {
$outFile = "$outDir/$id.jpg";
// 判定是否需要重跑
$needGen = true;
if (file_exists($outFile)) {
$sz = filesize($outFile);
if ($sz > $MIN_SIZE && $sz !== $PH) {
// 真实图,跳过
$needGen = false;
} elseif ($sz === $PH || $sz < 10000) {
// 占位图或空文件,需要重跑
@unlink($outFile);
}
}
if (!$needGen) { $SKIP++; continue; }
$prompt = buildPollPrompt($cat['name'], $cat['kind']);
echo "GEN #$id {$cat['name']}... ";
flush();
$sz = downloadAndCrop($prompt, $outFile);
if ($sz === false || $sz < $MIN_SIZE) {
echo "FAIL\n";
$Error++;
} else {
$elapsed = round(microtime(true) - $t0, 0);
$remain = $total - $SKIP - $OK - 1;
$eta = $OK > 0 ? round(($elapsed / $OK) * $remain / 60, 1) : '?';
echo "OK $sz (ok=$OK skip=$SKIP fail=$Error eta~{$eta}min)\n";
$processed[(string)$id] = [
'name' => $cat['name'], 'pid' => $cat['pid'],
'file' => $outFile, 'size' => $sz,
];
// 每 5 个存一次 idx
if (($OK + 1) % 5 === 0) {
file_put_contents($idxFile, json_encode($processed, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
}
$OK++;
}
// 避免限流
usleep(1200000); // 1.2s
}
// 最终存 idx
file_put_contents($idxFile, json_encode($processed, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
echo "\n=== DONE ===\n";
echo "OK=$OK SKIP=$SKIP FAIL=$Error TOTAL=$total\n";
echo "总耗时: " . round(microtime(true) - $t0, 0) . "s\n";
// 最终校验
$all = glob("$outDir/*.jpg");
$phCount = 0;
foreach ($all as $f) if (filesize($f) === $PH) $phCount++;
$badCount = 0;
foreach ($all as $f) if (filesize($f) < $MIN_SIZE) $badCount++;
echo "最终校验: 总=" . count($all) . " 占位图=$phCount 坏图=$badCount\n";