Files
2026-10-18 20:58:03 +07:00

417 lines
16 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// ui.cpp — прогресс-бар, спиннер, спарклайн, цвета.
#include "ui.h"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstring>
// ---------------------------------------------------------------------------
// Платформенная часть: tty-детект, ширина терминала, ANSI-цвета.
// Windows: _isatty + GetConsoleScreenBufferInfo; ANSI включается переводом
// консоли в режим ENABLE_VIRTUAL_TERMINAL_PROCESSING (Windows 10+).
// ---------------------------------------------------------------------------
#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# define NOMINMAX
# include <windows.h>
# include <io.h>
#else
# include <sys/ioctl.h>
# include <unistd.h>
#endif
namespace xt {
namespace {
bool g_color = true;
bool g_progress = true;
bool g_eta = true;
bool g_spark = true;
bool g_spinner = true;
int g_width = 32;
bool g_ascii = false;
bool g_checked_tty = false;
bool g_is_tty = false;
bool stdout_tty_raw() {
#ifdef _WIN32
return ::_isatty(::_fileno(stdout)) != 0;
#else
return ::isatty(STDOUT_FILENO) != 0;
#endif
}
#ifdef _WIN32
// Включаем обработку ANSI-escape-последовательностей в консоли Windows.
// Без этого цвета и курсорные движения печатались бы как мусор «\033[0m».
void enable_windows_vt() {
static bool done = false;
if (done) return;
done = true;
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
if (h == INVALID_HANDLE_VALUE || h == nullptr) return;
DWORD mode = 0;
if (!GetConsoleMode(h, &mode)) return;
constexpr DWORD kVT = 0x0004; // ENABLE_VIRTUAL_TERMINAL_PROCESSING
SetConsoleMode(h, mode | kVT);
}
#endif
bool use_color() {
if (!g_checked_tty) { g_is_tty = stdout_tty_raw(); g_checked_tty = true; }
#ifdef _WIN32
if (g_color && g_is_tty) enable_windows_vt();
#endif
return g_color && g_is_tty;
}
bool use_progress() {
if (!g_checked_tty) { g_is_tty = stdout_tty_raw(); g_checked_tty = true; }
return g_progress && g_is_tty;
}
} // namespace
void ui_configure(bool color, bool progress, bool eta, bool sparkline,
bool spinner, int bar_width, bool ascii_only) {
g_color = color;
g_progress = progress;
g_eta = eta;
g_spark = sparkline;
g_spinner = spinner;
g_width = bar_width > 4 ? bar_width : 4;
g_ascii = ascii_only;
}
int term_width() {
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO info{};
if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info)) {
const int w = info.srWindow.Right - info.srWindow.Left + 1;
if (w > 0) return w;
}
#else
struct winsize w{};
if (::ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) == 0 && w.ws_col > 0) return (int)w.ws_col;
#endif
if (const char* c = std::getenv("COLUMNS")) {
int v = std::atoi(c);
if (v > 0) return v;
}
return 80;
}
bool stdout_is_tty() {
if (!g_checked_tty) { g_is_tty = stdout_tty_raw(); g_checked_tty = true; }
return g_is_tty;
}
namespace col {
static const char* C(const char* code, const char* plain) { return use_color() ? code : plain; }
const char* reset() { return C("\033[0m", ""); }
const char* bold() { return C("\033[1m", ""); }
const char* dim() { return C("\033[2m", ""); }
const char* red() { return C("\033[31m", ""); }
const char* green() { return C("\033[32m", ""); }
const char* yellow() { return C("\033[33m", ""); }
const char* blue() { return C("\033[34m", ""); }
const char* magenta() { return C("\033[35m", ""); }
const char* cyan() { return C("\033[36m", ""); }
const char* grey() { return C("\033[90m", ""); }
} // namespace col
namespace sym {
const char* hbar() { return g_ascii ? "-" : "\xe2\x94\x80"; } // ─
const char* vbar() { return g_ascii ? "|" : "\xe2\x94\x82"; } // │
const char* corner() { return g_ascii ? "`-" : "\xe2\x95\xb0"; } // ╰
const char* check() { return g_ascii ? "+" : "\xe2\x9c\x93"; } // ✓
const char* cross() { return g_ascii ? "x" : "\xe2\x9c\x97"; } // ✗
const char* warn() { return g_ascii ? "!" : "\xe2\x9a\xa0"; } // ⚠
const char* arrow() { return g_ascii ? "->" : "\xe2\x86\x92"; } // →
const char* bullet() { return g_ascii ? "*" : "\xe2\x80\xa2"; } // •
} // namespace sym
// ---------------------------------------------------------------------------
std::string sparkline(const std::vector<float>& v, int max_points) {
if (v.empty()) return "";
static const char* blocks[] = {"\xe2\x96\x81","\xe2\x96\x82","\xe2\x96\x83","\xe2\x96\x84",
"\xe2\x96\x85","\xe2\x96\x86","\xe2\x96\x87","\xe2\x96\x88"};
const size_t n = v.size();
const size_t from = (n > (size_t)max_points) ? n - (size_t)max_points : 0;
float lo = v[from], hi = v[from];
for (size_t i = from; i < n; ++i) { lo = std::min(lo, v[i]); hi = std::max(hi, v[i]); }
std::string out;
if (g_ascii) {
// ASCII-вариант: .:-=+*#%@
static const char* asc = ".,:-=+*#%@";
const float span = std::max(hi - lo, 1e-6f);
for (size_t i = from; i < n; ++i) {
int k = (int)((v[i] - lo) / span * 9.0f);
k = std::max(0, std::min(9, k));
out += asc[k];
}
return out;
}
const float span = std::max(hi - lo, 1e-6f);
for (size_t i = from; i < n; ++i) {
int k = (int)((v[i] - lo) / span * 7.0f);
k = std::max(0, std::min(7, k));
out += blocks[k];
}
return out;
}
// ---------------------------------------------------------------------------
std::string fmt_eta(double sec) {
if (!(sec >= 0) || !std::isfinite(sec)) return "--";
if (sec < 1e-3) return "0с";
const long long s = (long long)std::llround(sec);
char buf[32];
if (s < 60) snprintf(buf, sizeof buf, "%lldс", s);
else if (s < 3600) snprintf(buf, sizeof buf, "%lldм %02lldс", s / 60, s % 60);
else if (s < 86400) snprintf(buf, sizeof buf, "%lldч %02lldм", s / 3600, (s % 3600) / 60);
else snprintf(buf, sizeof buf, "%lldд %02lldч", s / 86400, (s % 86400) / 3600);
return buf;
}
std::string fmt_dur_ns(int64_t ns) {
char buf[32];
if (ns < 1000) { snprintf(buf, sizeof buf, "%lldнс", (long long)ns); return buf; }
if (ns < 1000000) { snprintf(buf, sizeof buf, "%.1fмкс", ns / 1e3); return buf; }
if (ns < 1000000000LL) { snprintf(buf, sizeof buf, "%.1fмс", ns / 1e6); return buf; }
snprintf(buf, sizeof buf, "%.2fс", ns / 1e9);
return buf;
}
std::string fmt_number(double v, int prec) {
char buf[48];
const double a = std::fabs(v);
if (a >= 1e9) snprintf(buf, sizeof buf, "%.*fG", prec, v / 1e9);
else if (a >= 1e6) snprintf(buf, sizeof buf, "%.*fM", prec, v / 1e6);
else if (a >= 1e4) snprintf(buf, sizeof buf, "%.*fK", prec, v / 1e3);
else snprintf(buf, sizeof buf, "%.*f", prec, v);
return buf;
}
std::string fmt_bytes(uint64_t b) {
char buf[32];
const char* u = g_ascii ? "B" : "\xd0\x91"; // не используется, но оставляем нейтральным
(void)u;
if (b >= 1073741824ULL) snprintf(buf, sizeof buf, "%.2f GiB", b / 1073741824.0);
else if (b >= 1048576ULL) snprintf(buf, sizeof buf, "%.1f MiB", b / 1048576.0);
else if (b >= 1024ULL) snprintf(buf, sizeof buf, "%.1f KiB", b / 1024.0);
else snprintf(buf, sizeof buf, "%llu B", (unsigned long long)b);
return buf;
}
// ---------------------------------------------------------------------------
// Spinner
// ---------------------------------------------------------------------------
namespace {
void spinner_draw(const std::string& label, int frame) {
static const char* uni[] = {"\xe2\xa0\x8b","\xe2\xa0\x99","\xe2\xa0\xb9","\xe2\xa0\xb8",
"\xe2\xa0\xbc","\xe2\xa0\xb4","\xe2\xa0\xa6","\xe2\xa0\x87",
"\xe2\xa0\x8f","\xe2\xa0\x8b"};
static const char* asc[] = {"|","/","-","\\"};
const char* f = g_ascii ? asc[frame % 4] : uni[frame % 10];
printf("\r%s%s%s %s%s%s ", col::cyan(), f, col::reset(), col::dim(), label.c_str(), col::reset());
fflush(stdout);
}
} // namespace
Spinner::Spinner(std::string label) : label_(std::move(label)) {}
Spinner::~Spinner() {
if (running_.load() && !finished_) stop();
if (threaded_ && th_.joinable()) th_.join();
}
void Spinner::start() {
if (!g_spinner || !stdout_is_tty()) return;
finished_ = false;
frame_ = 0;
running_ = true;
// Анимация — в отдельном потоке: вызывающий код обычно заблокирован
// (ждёт сеть или диск) и сам tick() позвать не может.
threaded_ = true;
th_ = std::thread([this] { run(); });
}
void Spinner::run() {
while (running_.load()) {
spinner_draw(label_, frame_.fetch_add(1));
std::this_thread::sleep_for(std::chrono::milliseconds(90));
}
}
void Spinner::tick() {
if (!running_.load() || threaded_) return; // поток уже крутит сам
spinner_draw(label_, frame_.fetch_add(1));
}
void Spinner::stop(const std::string& final_label) {
if (!running_.load()) return;
running_ = false;
if (threaded_ && th_.joinable()) { th_.join(); threaded_ = false; }
finished_ = true;
if (!stdout_is_tty()) {
if (!final_label.empty()) printf("%s\n", final_label.c_str());
return;
}
printf("\r\033[2K"); // стереть строку
const std::string l = final_label.empty() ? label_ : final_label;
if (!l.empty()) printf("%s%s%s %s\n", col::green(), sym::check(), col::reset(), l.c_str());
fflush(stdout);
}
void Spinner::fail(const std::string& final_label) {
if (!running_.load()) return;
running_ = false;
if (threaded_ && th_.joinable()) { th_.join(); threaded_ = false; }
finished_ = true;
if (!stdout_is_tty()) {
if (!final_label.empty()) printf("%s\n", final_label.c_str());
return;
}
printf("\r\033[2K");
const std::string l = final_label.empty() ? label_ : final_label;
if (!l.empty()) printf("%s%s%s %s\n", col::red(), sym::cross(), col::reset(), l.c_str());
fflush(stdout);
}
// ---------------------------------------------------------------------------
// ProgressBar
// ---------------------------------------------------------------------------
void ProgressBar::start(int total, const std::string& title) {
total_ = total;
title_ = title;
losses_.clear();
last_pct_ = -1;
last_step_ = -1;
started_ = true;
enabled_ = use_progress();
if (!title_.empty()) printf("%s%s%s\n", col::bold(), title_.c_str(), col::reset());
if (enabled_) { std::printf("\n"); line_open_ = false; }
}
void ProgressBar::break_line() {
if (line_open_) { printf("\n"); line_open_ = false; fflush(stdout); }
}
void ProgressBar::note(const std::string& text) {
if (!started_) { printf("%s\n", text.c_str()); return; }
break_line();
printf("%s%s%s %s\n", col::grey(), sym::bullet(), col::reset(), text.c_str());
fflush(stdout);
}
void ProgressBar::tick(const TrainProgress& p) {
if (!started_) return;
if (std::isfinite(p.loss) && p.loss > 0) losses_.push_back(p.loss);
if (!enabled_) return;
// не перерисовываем чаще, чем изменился процент или шаг
const int pct = (total_ > 0) ? (int)((int64_t)p.step * 100 / total_) : -1;
if (pct == last_pct_ && p.step == last_step_) return;
last_pct_ = pct; last_step_ = p.step;
render(p, false);
}
void ProgressBar::render(const TrainProgress& p, bool final_line) {
const int tw = std::max(40, term_width());
int w = std::min(g_width, std::max(10, tw - 46));
char pctstr[16] = " -- ";
int filled = 0;
if (total_ > 0) {
const double fr = std::min(1.0, std::max(0.0, (double)p.step / (double)total_));
filled = (int)std::llround(fr * w);
snprintf(pctstr, sizeof pctstr, "%3d%%", (int)std::llround(fr * 100.0));
}
// ── собираем строку бара
std::string bar;
bar += "[";
for (int i = 0; i < w; ++i) {
if (total_ <= 0) bar += (i == 0) ? (g_ascii ? "?" : "\xe2\x89\x88") : " ";
else if (i < filled) bar += g_ascii ? "#" : "\xe2\x96\x88"; // █
else if (i == filled) bar += g_ascii ? ">" : "\xe2\x96\x92"; // ▒
else bar += g_ascii ? "." : "\xe2\x94\x80"; // ─
}
bar += "]";
// ── хвост: step/loss/ppl/lr/ток/с/eta/спарклайн
char tail[512];
int n = 0;
n += snprintf(tail + n, sizeof(tail) - n, " %s%s%s ", col::bold(), pctstr, col::reset());
n += snprintf(tail + n, sizeof(tail) - n, "%s%d/%d%s", col::grey(), p.step, total_, col::reset());
n += snprintf(tail + n, sizeof(tail) - n, " loss %s%.4f%s", col::yellow(), p.loss, col::reset());
if (p.val_loss > 0) n += snprintf(tail + n, sizeof(tail) - n, " val %.4f", p.val_loss);
n += snprintf(tail + n, sizeof(tail) - n, " ppl %s%.1f%s", col::magenta(), std::exp(std::min(p.loss, 30.0f)), col::reset());
n += snprintf(tail + n, sizeof(tail) - n, " lr %.1e", p.lr);
if (p.tokens_per_sec > 0)
n += snprintf(tail + n, sizeof(tail) - n, " %s%s%s/с", col::cyan(),
fmt_number(p.tokens_per_sec, 0).c_str(), col::reset());
if (g_eta && total_ > 0 && p.step > 0 && p.elapsed_sec > 0) {
const double eta = p.elapsed_sec / (double)p.step * (double)(total_ - p.step);
n += snprintf(tail + n, sizeof(tail) - n, " eta %s", fmt_eta(eta).c_str());
}
if (g_spark && !losses_.empty())
n += snprintf(tail + n, sizeof(tail) - n, " %s%s%s", col::green(),
sparkline(losses_, std::min(24, std::max(8, (tw - n) / 2))).c_str(), col::reset());
(void)n;
// ── влезает ли в ширину? если нет — режем спарклайн
std::string line = "\r" + bar + tail;
if (!final_line) line += "\033[0K"; // стереть хвост предыдущей, более длинной строки
// грубая оценка видимой длины (без ANSI)
size_t visible = 0;
for (size_t i = 0; i < line.size(); ++i) {
if (line[i] == '\033') { while (i < line.size() && line[i] != 'm') ++i; continue; }
if ((unsigned char)line[i] >= 0x80) {
// UTF-8: считаем начало символа; блоки спарклайна занимают 1 колонку
if ((unsigned char)line[i] >= 0xC0) ++visible;
continue;
}
++visible;
}
if ((int)visible > tw) {
// убираем спарклайн и перерисовываем
const bool had_spark = g_spark;
g_spark = false;
(void)had_spark;
std::string short_line = "\r" + bar;
char st[256];
snprintf(st, sizeof st, " %s%s%s %d/%d loss %.4f %s/с", col::bold(), pctstr, col::reset(),
p.step, total_, p.loss, fmt_number(p.tokens_per_sec, 0).c_str());
short_line += st;
if (!final_line) short_line += "\033[0K";
fputs(short_line.c_str(), stdout);
} else {
fputs(line.c_str(), stdout);
}
fflush(stdout);
line_open_ = !final_line;
}
void ProgressBar::finish(const std::string& summary) {
if (!started_) return;
if (enabled_) {
TrainProgress p;
p.step = total_ > 0 ? total_ : last_step_;
p.total = total_;
p.loss = losses_.empty() ? 0.0f : losses_.back();
render(p, true);
printf("\n");
line_open_ = false;
}
started_ = false;
if (!summary.empty())
printf("%s%s%s %s\n", col::green(), sym::check(), col::reset(), summary.c_str());
fflush(stdout);
}
} // namespace xt