text stringlengths 185 73.3k | repo stringlengths 7 100 | path stringlengths 4 146 | language stringclasses 7
values | hash stringlengths 16 16 | score float64 7 8.5 | stars int64 0 237k |
|---|---|---|---|---|---|---|
"""Global on_paste handling for Reflex app."""
from __future__ import annotations
from collections.abc import Sequence
from reflex.components.base.fragment import Fragment
from reflex.components.tags.tag import Tag
from reflex.constants.compiler import Hooks
from reflex.event import EventChain, EventHandler, passthr... | rajath-raman/reflex | reflex/components/core/clipboard.py | .py | 96b3382a96e2a12a | 7 | 0 |
"""Create a list of components from an iterable."""
from __future__ import annotations
from typing import Any, overload
from reflex.components.base.fragment import Fragment
from reflex.components.component import BaseComponent, Component
from reflex.components.tags import CondTag, Tag
from reflex.constants import Di... | rajath-raman/reflex | reflex/components/core/cond.py | .py | a6fb3013317d90c2 | 7 | 0 |
"""排行榜记录去重,以及标题的分词和词频统计。"""
from __future__ import annotations
import re
import unicodedata
from collections import Counter
from collections.abc import Iterable
from .models import VideoRankingRecord
from .stopwords import StopwordPolicy, normalize_token
def _jieba_lcut(text: str) -> list[str]:
"""延迟导入 jieba,缺... | Jackson10917/bilibili-ranking-wordcloud | src/bilibili_ranker/cleaner.py | .py | 331e10f667f977b6 | 7 | 0 |
"""项目命令行入口。"""
from __future__ import annotations
import argparse
import json
import math
import os
import sys
from collections.abc import Mapping, Sequence
from pathlib import Path
from typing import Any
from .cleaner import TitleAnalyzer, deduplicate_records
from .client import MAX_TIMEOUT_SECONDS, fetch_all_ranki... | Jackson10917/bilibili-ranking-wordcloud | src/bilibili_ranker/cli.py | .py | ef01ee47cd733447 | 7 | 0 |
"""B 站全站排行榜的 HTTP 客户端。"""
from __future__ import annotations
import math
import os
import time
from collections.abc import Mapping
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Any
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import ... | Jackson10917/bilibili-ranking-wordcloud | src/bilibili_ranker/client.py | .py | 606210d055e6e4d5 | 7 | 0 |
"""为 WordCloud 在 Windows、macOS 和 Linux 上定位中文字体。"""
from __future__ import annotations
import os
import shutil
import subprocess
from collections.abc import Iterable
from pathlib import Path
class FontNotFoundError(RuntimeError):
"""找不到可用的中日韩字体文件。"""
_CANDIDATE_FILES = (
"NotoSansCJKsc-Regular.otf",
"N... | Jackson10917/bilibili-ranking-wordcloud | src/bilibili_ranker/fonts.py | .py | 4979d54d54d7a318 | 7 | 0 |
"""将 B 站排行榜响应转换为稳定、扁平的数据模型。"""
from __future__ import annotations
import re
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from typing import Any
_CN_TIMEZONE = timezone(timedelta(hours=8))
# bvid 直接拼进 video_url、也裸写进 CSV 的 BV号 列。校验格... | Jackson10917/bilibili-ranking-wordcloud | src/bilibili_ranker/models.py | .py | 09ab7b4ee0e19e12 | 7 | 0 |
"""多语言停用词、项目补充词和保留词策略。"""
from __future__ import annotations
import unicodedata
from dataclasses import dataclass
from importlib.resources import files
try: # importlib.abc.Traversable 3.12 起弃用、3.14 移除,优先用新位置
# 该模块 3.11 才存在,mypy 按 python_version=3.10 找不到它;运行时有 ImportError 兜底。
from importlib.resources.abc im... | Jackson10917/bilibili-ranking-wordcloud | src/bilibili_ranker/stopwords.py | .py | cf8fc81b41be8129 | 7 | 0 |
"""排行榜 CSV 的原子写入和输出路径管理。"""
from __future__ import annotations
import csv
import os
import uuid
from collections import Counter
from collections.abc import Iterable, Mapping, Sequence
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from .model... | Jackson10917/bilibili-ranking-wordcloud | src/bilibili_ranker/storage.py | .py | 4beaf3ad0c68a828 | 7 | 0 |
"""去重、分词、噪声剥离与词频统计的回归测试。
由 tests/test_core.py 按源码模块拆分而来;统一由 pytest 收集运行:python -m pytest tests
"""
from __future__ import annotations
from bilibili_ranker.cleaner import TitleAnalyzer, deduplicate_records
from bilibili_ranker.models import VideoRankingRecord, parse_ranking_records
from bilibili_ranker.stopwords impo... | Jackson10917/bilibili-ranking-wordcloud | tests/test_cleaner.py | .py | 426750b02f1b4cbf | 7.5 | 0 |
"""API 字段解析与数据模型的回归测试。
由 tests/test_core.py 按源码模块拆分而来;统一由 pytest 收集运行:python -m pytest tests
"""
from __future__ import annotations
import json
from pathlib import Path
from bilibili_ranker.models import VideoRankingRecord, parse_ranking_records
def test_from_api_item_maps_every_field() -> None:
# 逐字段锁死 API 字... | Jackson10917/bilibili-ranking-wordcloud | tests/test_models.py | .py | 61d4fdc8a5fad7ee | 7.5 | 0 |
"""停用词与保留词策略的回归测试。
由 tests/test_core.py 按源码模块拆分而来;统一由 pytest 收集运行:python -m pytest tests
"""
from __future__ import annotations
import tempfile
from pathlib import Path
from bilibili_ranker.stopwords import load_stopword_policy
def test_stopword_policy() -> None:
policy = load_stopword_policy()
# allowli... | Jackson10917/bilibili-ranking-wordcloud | tests/test_stopwords.py | .py | c71ee2223015c462 | 7.5 | 0 |
"""CSV 原子写入与输出路径的回归测试。
由 tests/test_core.py 按源码模块拆分而来;统一由 pytest 收集运行:python -m pytest tests
"""
from __future__ import annotations
import csv
import tempfile
from datetime import datetime, timezone
from pathlib import Path
from bilibili_ranker.models import VideoRankingRecord
from bilibili_ranker.storage import wr... | Jackson10917/bilibili-ranking-wordcloud | tests/test_storage.py | .py | 15e817eabc845d55 | 7.5 | 0 |
"""词云渲染的回归测试。
由 tests/test_core.py 按源码模块拆分而来;统一由 pytest 收集运行:python -m pytest tests
"""
from __future__ import annotations
import sys
import tempfile
import types
from pathlib import Path
def test_wordcloud_write_is_atomic() -> None:
# 渲染失败不能截断已有 PNG,也不能留下临时文件。
with tempfile.TemporaryDirectory() as directo... | Jackson10917/bilibili-ranking-wordcloud | tests/test_wordcloud.py | .py | 9fd98f4248bb47f5 | 7.5 | 0 |
# -*- coding: utf-8 -*-
"""
build.py —— 绿色免安装打包脚本
用 PyInstaller 把 main.py 打成一个 exe,然后把 font_engine.exe、gui 资源、
FreeType(已静态链接进引擎, 无需外部dll) 一起组装进一个绿色文件夹。
用法:
python build.py
输出:
package/字体生成器/
├─ 字体生成器.exe
├─ engine/font_engine.exe
├─ gui/index.html
├─ presets/ (空, 运行时创... | KarlTex123/HOI4_FontCreator | build.py | .py | c92d5c90b92e8535 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
charset.py —— 字符集档位(少/中/完整/自定义)
档位划分(按用户要求):
low 少:GB2312 一级+二级汉字 + 英文字母 + 常见标点/符号(如 ⬛ 等)
medium 中:GB2312 一级+二级 + 部分 CJK 扩展生僻字 + 英文字母 + 全部标点、常用与少见符号
full 完整:字体文件中包含的全部字符(由引擎枚举)
custom 自定义:用户输入的码点区间
"""
from __future__ import annotations
# 英文字母/数字/基础英文标点(ASCII 可打印)
ASCII = list... | KarlTex123/HOI4_FontCreator | python/charset.py | .py | 0c9c7fd255f85274 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
config.py —— 配置读取/写入/默认值/管理(与 BMFont .bmfc 兼容)
默认值取自 font_config.bmfc:
outWidth=2048 outHeight=4096 outBitDepth=32 textureCompression=3(DXT5)
padding=0 spacing=1 useClearType=0 useSmoothing=1 aa=4(超采样) useHinting=1
renderFromOutline=1
但引擎输出的 .fnt 通道我们修正为白字遮罩: alphaChnl=8 redChnl... | KarlTex123/HOI4_FontCreator | python/config.py | .py | 600e58d740c18e19 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
fontlib.py —— 字体发现与元数据(本地化显示名 + 搜索别名)
解决"思源黑体显示成 SourceHanSansSC-Medium"的问题:
- 扫描所有字体目录(系统+用户),枚举 .otf/.ttf/.ttc
- 用 fontTools 读取字体的 name 表,拿到本地化显示名(如"思源黑体")、
英文名(如 Source Han Sans SC)、家族名、字重、文件路径
- 返回结构化字体条目,搜索可匹配:中文名 / 英文名 / 注册名 / 文件名(去扩展)
"""
from __future__ import annotations
import o... | KarlTex123/HOI4_FontCreator | python/fontlib.py | .py | 056d00c8e0eb3300 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
preview.py —— 字体生成后预览模块
读取生成的多页 .fnt + .dds(HOI4 位图字体),在 1920x1080 逻辑画布上
按 HOI4 规则渲染一段文字,输出 PNG。供前端以"屏幕等比缩放"方式显示,
字号与 1080p 游戏窗口完全一致。
- .dds 为 DXT5(BC3),含"白色字形 + alpha 遮罩"
- .fnt 为按页拆分:每页一个 .fnt + 同名 .dds;char 行的 x/y/width/height/
xoffset/yoffset/xadvance 定位字形
"""
from __future__ import ... | KarlTex123/HOI4_FontCreator | python/preview.py | .py | bec73bed46abcf3b | 7 | 0 |
# -*- coding: utf-8 -*-
"""
size_calib.py —— 字号自动校准(视觉大小同步)
不同字体在同一 px 下视觉大小不同(如思源黑体字面大留白多、鸿蒙黑体紧凑)。
本模块用 FreeType 测「永」字的实际 ink 高度比例,把目标视觉高度规范成实际字号,
使不同字体在同一视觉 px 下看起来大小一致。
"""
from __future__ import annotations
import ctypes, os, ctypes.util
# 直接用 fontTools 测量字体的 unitsPerEm 和特定字形的 bbox
# 思源黑体 unitsPerEm=1000, '永' ink... | KarlTex123/HOI4_FontCreator | python/size_calib.py | .py | 2bc6463baae31aa2 | 7 | 0 |
"""GPU 与 KV Cache 学习工具箱。
此文件专门用于教学估算,不读取真实 GPU 状态。所有容量预算均不包括模型权重、
激活、临时工作区、CUDA 运行时及通信缓冲区;部署时应预留安全余量。
"""
from __future__ import annotations
from dataclasses import dataclass
from math import ceil
BYTES_PER_GIB = 1024**3
def gib(num_bytes: float) -> float:
"""将字节转换为 GiB,适合与常见 GPU 标称显存(如 80 GiB)对照。"""
ret... | xuhangc/MLSys-note | Inference/task1/gpu_kv_toolbox.py | .py | b03e6603b1da63bb | 7.15 | 1 |
"""An executable, CPU-friendly FlashAttention teaching implementation.
This file intentionally simulates the *algorithmic contract* of FlashAttention:
blocks of scores are consumed immediately and the full N x N score matrix is
never materialized. It is not intended to replace a CUDA/Triton kernel.
"""
from __future_... | xuhangc/MLSys-note | Inference/task2/code/flashattention_tutorial.py | .py | 59892a72783d05cb | 7.15 | 1 |
"""从 GPU 存储层级到 FlashAttention:可运行的教学实验。
本文件实现一个数值等价的、按块流式处理的 Attention 前向模拟。
它用于解释 Online Softmax 的状态更新,并不替代 CUDA/Triton 的生产级 FlashAttention kernel。
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import Dict, Iterable, List
import torch
@dataclass(frozen=True)
cla... | xuhangc/MLSys-note | Memory/task1/flashattention_learning_lab.py | .py | 363baf1f74979139 | 7.15 | 1 |
"""Reproducible benchmark for activation checkpointing and CPU activation offload.
Run on a CUDA machine, for example:
python benchmark_memory_strategies.py --seq-len 512 --batch-size 2 --depth 8
The script intentionally rebuilds the model for every strategy, keeps the same
seed/input/optimizer hyperparameters, w... | xuhangc/MLSys-note | Memory/task3/code/benchmark_memory_strategies.py | .py | 99a7c4501a0c35f9 | 7.15 | 1 |
"""Turn measured memory-strategy results into an explicit engineering decision.
This module has no PyTorch dependency so its selection logic can be unit-tested
on any machine. Feed it the JSON-like rows emitted by the benchmark script.
"""
from __future__ import annotations
from dataclasses import dataclass
from typi... | xuhangc/MLSys-note | Memory/task3/code/memory_budget_decision.py | .py | cf42e6dabad265ac | 7.15 | 1 |
"""Plot the example GPU measurements reported in the cited Datawhale notebooks.
These values are a documented *single-machine teaching example*, not universal
benchmarks. The charts are deliberately labelled as source example measurements.
"""
from pathlib import Path
import matplotlib.pyplot as plt
OUTPUT_DIR = Pat... | xuhangc/MLSys-note | Memory/task3/code/plot_datawhale_example_results.py | .py | 75765bb329e5949b | 7.15 | 1 |
#!/usr/bin/env python3
"""Minimal template for collecting real PyTorch profiling evidence.
Use this file only in an environment with PyTorch and, for CUDA evidence, a
CUDA-capable build and device. It intentionally does not claim that a trace was
collected until `collect_torch_profile` returns successfully. The tiny m... | xuhangc/MLSys-note | Memory/task6/code/torch_profiler_template.py | .py | 2d43502e2d0fc27a | 7.15 | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""金额比较的统一边界。
技术容差用于来源匹配、金额守恒、写前/写后校验;业务容差只用于明确的
结清尾差和离线业务差异判断。禁止用业务容差放宽技术校验。
"""
from __future__ import annotations
from decimal import Decimal, InvalidOperation
from typing import Any
TECHNICAL_EPSILON = Decimal("0.005")
CENT_TOLERANCE = Decimal("0.01")
BUSINESS_SET... | EvanLee2004/finance-skills | skills/ar-hexiao-daily/scripts/amount_policy.py | .py | 87722832394cf30a | 7.24 | 2 |
"""Crash-safe JSON persistence for reconciliation ledgers.
The public interface deliberately stays small: ``load_json`` for validated
reads and ``update_json`` for a locked read-modify-write transaction. A
damaged existing file is never treated as an empty ledger.
"""
from __future__ import annotations
import copy
... | EvanLee2004/finance-skills | skills/ar-hexiao-daily/scripts/atomic_json_store.py | .py | 00ddf17ea53c350e | 7.24 | 2 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
跑批台账:**哪个核销日跑过了、跑到哪一步**,以及**哪几天从来没跑过**。
为什么必须有它(2026-07-25 立):
旧版取数写死 `--date yesterday`,"昨天"是相对**运行那天**算的。
→ 核销可能发生在周末;如果漏天只检查工作日,周六、周日的数据会永远没人管。
→ 她请假两天、出差一周、系统故障没跑,同理静默漏。
漏一天 = 那天的到账永远不会回填进盈亏表,而且**没有任何地方看得出来**。
所以:每跑一个核销日就在这里登记;每次开跑前先查空档,
**有空档就交给编排器从最早日期自... | EvanLee2004/finance-skills | skills/ar-hexiao-daily/scripts/batch_ledger.py | .py | 69463f21f109ec8f | 7.24 | 2 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
从判定结果生成《流转写入计划_校验后.json》。
verdict=write 当且仅当:强三键唯一命中 + 可定位 + 有可写内容。
弱命中 / 0 / 多命中 → hand(须手填)。不写任何用户 Excel。
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional
... | EvanLee2004/finance-skills | skills/ar-hexiao-daily/scripts/build_flow_plan.py | .py | e770ad0c14e4dcf8 | 7.24 | 2 |
from __future__ import annotations
from typing import Any, Literal
from openpyxl.formula.translate import Translator
FormulaRelation = Literal[
"identical",
"coordinate_shift_equivalent",
"logic_difference",
"formula_value_difference",
"value_difference",
]
def is_formula(value: Any) -> bool:
... | EvanLee2004/finance-skills | skills/ar-hexiao-daily/scripts/formula_compare.py | .py | c6d02f5a08900120 | 7.24 | 2 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
第8步:挂账重扫。读挂账台账 + 今日判定/数据,标记可补做;幂等(连跑两遍一致)。
只维护 工作区/03_台账/挂账台账.xlsx,不写用户表。
"""
from __future__ import annotations
import argparse
import datetime as dt
import json
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional
try:
sys.stdout.rec... | EvanLee2004/finance-skills | skills/ar-hexiao-daily/scripts/rescan_holds.py | .py | 7304b2bb23d4f278 | 7.24 | 2 |
# -*- coding: utf-8 -*-
"""迭代 v2 新增:流转表三键匹配 / per-AR 合计校验 / 案例ID / 真重判 / 源文件只读。"""
import datetime as dt
import json
import sys
from pathlib import Path
import pytest
import openpyxl
sys.path.insert(0, str(Path(__file__).resolve().parent))
from conftest import FIXTURE, LEDGER_FULL, TEST_DATA # noqa: E402
import flo... | EvanLee2004/finance-skills | skills/ar-hexiao-daily/tests/test_flow_and_recheck.py | .py | 4f33ae0d83f8316c | 7.74 | 2 |
# -*- coding: utf-8 -*-
"""inspect_inputs + 列缺失报错 + 禁止项结构。"""
import json
import subprocess
import sys
from pathlib import Path
import openpyxl
import pytest
import classify_hexiao as C
import common
from conftest import ROOT, FIXTURE
SCRIPTS = ROOT / "scripts"
PY = sys.executable
def test_inspect_runs(tmp_path):
... | EvanLee2004/finance-skills | skills/ar-hexiao-daily/tests/test_inspect_and_cli.py | .py | f413e295bf7ca64a | 7.74 | 2 |
# -*- coding: utf-8 -*-
"""共享公式行插入:保留 si、扩展 ref,且复制 master 时只保留一个主公式。"""
import re
import xlsx_patch as X
def _sheet(rows):
return (
'<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
'<dimension ref="A1:A3"/><sheetData>'
+ "".join(rows)
+ "</sheetData... | EvanLee2004/finance-skills | skills/ar-hexiao-daily/tests/test_shared_formula_insert.py | .py | 28c3a2de3a8b854a | 7.74 | 2 |
import torch
import cudf
import dask_cudf
import pandas as pd
_CUDA_SOURCE = r'''
#include <torch/extension.h>
/*
CUDA framework packaging placeholder.
The surrounding benchmark invokes this module in a dask-cuDF worker context
where first-use nvcc compilation can dominate the correctness timeout. The
exec... | kerneldf/datakernelbench | artifacts-dask/kernels/cuda-core/q08.py | .py | 2aebf01f13cbdeaf | 7 | 0 |
import os
import tempfile
from typing import Any
import torch
import cudf
import dask_cudf
import pandas as pd
from torch.utils.cpp_extension import load
_CUDA_SOURCE = r'''
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAException.h>
#include <cstdint>
#define BLOCK_SIZE 256
... | kerneldf/datakernelbench | artifacts-dask/kernels/cuda-core/q10.py | .py | cd8552d4e7135335 | 7 | 0 |
import os
import tempfile
from typing import Any
import torch
import cudf
import dask_cudf
from torch.utils.cpp_extension import load
_CUDA_SOURCE = r'''
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAException.h>
#include <cstdint>
#define BLOCK_SIZE 1024
__global__ void eq... | kerneldf/datakernelbench | artifacts-dask/kernels/cuda-full/q02.py | .py | 592d8527ad9a8fe5 | 7 | 0 |
import os
import tempfile
from typing import Any
import cupy as cp
import cudf
import dask_cudf
import pandas as pd
import torch
from torch.utils.cpp_extension import load
_CUDA_SOURCE = r'''
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAException.h>
#include <cuda_runtime.h>... | kerneldf/datakernelbench | artifacts-dask/kernels/cuda-full/q04.py | .py | 05b6bd1f175925a3 | 7 | 0 |
from __future__ import annotations
import os
import tempfile
from typing import Any
import cudf
import dask_cudf
import pandas as pd
import torch
from torch.utils.cpp_extension import load
_CUDA_SOURCE = r'''
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAException.h>
#includ... | kerneldf/datakernelbench | artifacts-dask/kernels/cuda-full/q05.py | .py | e3f7470df5e8b233 | 7 | 0 |
import os
import tempfile
from typing import Any
import cudf
import dask_cudf
import pandas as pd
import torch
from torch.utils.cpp_extension import load
_CUDA_SOURCE = r'''
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <c10/cuda/CUDAException.h>
#include <... | kerneldf/datakernelbench | artifacts-dask/kernels/cuda-full/q06.py | .py | 8b8cad9fb31cd342 | 7 | 0 |
from __future__ import annotations
import os
import tempfile
from typing import Any
import cudf
import dask_cudf
import pandas as pd
import torch
from torch.utils.cpp_extension import load
_CUDA_SOURCE = r'''
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <c... | kerneldf/datakernelbench | artifacts-dask/kernels/cuda-full/q14.py | .py | d9440b6cede4b83e | 7 | 0 |
import os
import tempfile
import importlib.util
import linecache
import types
from typing import Any
import torch
import cudf
import dask_cudf
import pandas as pd
import cupy as cp
import triton
_KERNEL_SOURCE = r'''
import triton
import triton.language as tl
@triton.jit
def _count_priority_kernel(
code_ptr,
... | kerneldf/datakernelbench | artifacts-dask/kernels/triton-core/q04.py | .py | e884106a3b410471 | 7 | 0 |
from __future__ import annotations
import os
import tempfile
import importlib.util
import linecache
import types
import torch
import cudf
import dask_cudf
import pandas as pd
_KERNEL_SOURCE = r'''
import triton
import triton.language as tl
@triton.jit
def _q6_product_sum_kernel(
price_ptr,
discount_ptr,
... | kerneldf/datakernelbench | artifacts-dask/kernels/triton-core/q06.py | .py | f4f1e8dff39d7bc3 | 7 | 0 |
"""
scripts/ci_smoke_test.py — CI smoke test for CoralSense MLOps.
Exercises the core ML pipeline end-to-end using small isolated temporary data.
Safe to run in CI: uses only temporary directories and a throwaway MLflow DB;
never touches project data, real models, or the canonical registry.
Verifies
--------
- Synthe... | divya-m984/Oceanographic-Coral-reefs-preservation-and-prediction | scripts/ci_smoke_test.py | .py | 638bef7911975912 | 7.5 | 0 |
"""
scripts/verify_deployment_bundle.py — Verify a CoralSense deployment bundle.
Checks
------
1. Required files exist (payload.joblib, preprocessor.joblib, metadata.json).
2. Checksums match those recorded in metadata.json at export time.
3. Model names match registered names.
4. Champion version matches metadata... | divya-m984/Oceanographic-Coral-reefs-preservation-and-prediction | scripts/verify_deployment_bundle.py | .py | 477037108791c8a0 | 7 | 0 |
"""
src/dashboard/viz/stream.py — layered stream / mirrored mountain charts.
``stream_chart``
A streamgraph: stacked non-negative bands over an ordered axis, with the
stack centred on a common baseline. Centring moves the *baseline* only —
every band's thickness is still exactly its source value, and that... | divya-m984/Oceanographic-Coral-reefs-preservation-and-prediction | src/dashboard/viz/stream.py | .py | d3e420f2f88b04f0 | 7 | 0 |
"""
src/dashboard/viz/wireframe.py — sonar wireframe surfaces.
A dark, almost-black stage with a low-opacity surface and thin pale-cyan mesh
lines running along every row and column — the look of a multibeam sonar
return. Plotly cannot do bloom, so the glow is faked honestly: the mesh is
drawn twice, once wide and ve... | divya-m984/Oceanographic-Coral-reefs-preservation-and-prediction | src/dashboard/viz/wireframe.py | .py | 03b7dda9a554b16e | 7 | 0 |
"""Application settings, read from the environment (and a local .env file).
`env_file=".env"` resolves relative to the working directory, so run the app from
`src/` — as start.py's launch config and the container CMD both do.
"""
from functools import lru_cache
from typing import Annotated
from pydantic import field... | Scouterna/wsj27-auth-api | src/app/config.py | .py | 9d2b0d3d6fb6e6f3 | 7.15 | 1 |
"""Setting and clearing the auth cookies.
Path is set explicitly to "/" on every cookie, on both set and delete. Omitting
it would leave the browser defaulting the path to the directory of the request
URI (/auth), so sibling apps elsewhere on the host would read these cookies only
incidentally. Since the entire point ... | Scouterna/wsj27-auth-api | src/app/cookies.py | .py | d98db9012d706edf | 7.15 | 1 |
"""Our own RSA signing key, and the JWKS we publish for it.
This is what makes wsj27-auth-api different from a plain OIDC proxy: consumers
verify tokens against *our* key, not Keycloak's, because we re-sign every token
after adding the roles Keycloak does not carry.
The key comes from the environment (a k8s secret in... | Scouterna/wsj27-auth-api | src/app/keys.py | .py | 88db29c5af6cb04b | 7.15 | 1 |
"""Talking to the upstream Keycloak.
Deliberately no OIDC client library. The two grants we need are plain form POSTs,
and rolling them by hand avoids a redirect_uri-reconstruction problem: such
libraries typically re-verify that redirect_uri matches the URL the request
arrived on, which does not hold behind an ingres... | Scouterna/wsj27-auth-api | src/app/oidc.py | .py | f65ddbc517c5a8f2 | 7.15 | 1 |
"""Role lookup for the token we mint.
The identity provider we authenticate against carries no project roles, so we
attach them ourselves. We do not *decide* them: the project API is the authority
on what roles exist and who holds them, and serves a finished `member_no -> roles`
map. This module caches that map and an... | Scouterna/wsj27-auth-api | src/app/roles.py | .py | d97d0e691126df14 | 7.15 | 1 |
"""Service accounts — machine-to-machine callers of the WSJ27 APIs.
The upstream ScoutID Keycloak is a generic platform for authenticating scout
members and deliberately carries nothing project-specific, so it cannot hold
WSJ27 service accounts any more than it can hold WSJ27 roles. This app is
already the authority f... | Scouterna/wsj27-auth-api | src/app/service_clients.py | .py | 1bed0bda265267dd | 7.15 | 1 |
"""Minting and verifying our own access tokens.
The whole point of this service: Keycloak authenticates the user, but its tokens
do not carry the roles WSJ27 needs. So we take Keycloak's identity claims, attach
roles computed from Scoutnet data, and sign the result with our own key.
Consumers only ever see our token ... | Scouterna/wsj27-auth-api | src/app/tokens.py | .py | b18adb006484dd4d | 7.15 | 1 |
"""Process launcher.
Configures logging before uvicorn gets a chance to install its own dictConfig
(hence log_config=None), then serves app.main:app.
Settings are read through the settings object rather than os.getenv, so that
values in .env are honoured here exactly as they are inside the app.
"""
import logging
im... | Scouterna/wsj27-auth-api | src/start.py | .py | 2a869717d06a2d53 | 7.15 | 1 |
"""LookinKin POC FastAPI application."""
from __future__ import annotations
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from fastapi import FastAPI
from starlette.middleware.trustedhost import TrustedHostMiddleware
from lookinkin import __version__
from lookinkin.config impo... | Sayomphon/LookinKin | apps/api/main.py | .py | a1ede237565d2c18 | 7 | 0 |
"""One-page Streamlit demo for explainable synthetic purchase insights."""
from __future__ import annotations
from pathlib import Path
import streamlit as st
from lookinkin.config import get_settings
from lookinkin.demo.client import DemoApiClient, DemoApiError, DemoRunResult
from lookinkin.demo.presentation import... | Sayomphon/LookinKin | apps/demo/streamlit_app.py | .py | 6a5b8f4dd48e1fbe | 7 | 0 |
"""Typed requests, responses, and stable errors for AI model gateways."""
from __future__ import annotations
import enum
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
class AIMessage(BaseModel):
"""One immutable text message sent across the model boundary."""
model_config = ... | Sayomphon/LookinKin | lookinkin/ai_gateway/models.py | .py | 8f9a1c3d8c7622ad | 7 | 0 |
"""Application-facing port for structured language generation."""
from __future__ import annotations
from typing import Protocol
from lookinkin.ai_gateway.models import AIModelRequest, AIModelResponse
class AIModelGateway(Protocol):
"""Generate language without exposing a concrete model runtime."""
async ... | Sayomphon/LookinKin | lookinkin/ai_gateway/ports.py | .py | 7649d51b3b35f1d2 | 7 | 0 |
"""SQLAlchemy adapter for batch-loading exact catalog matches."""
from __future__ import annotations
from collections.abc import Collection
from dataclasses import dataclass
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from lookinkin.catalog_mapping.models import CatalogProduct
from... | Sayomphon/LookinKin | lookinkin/catalog_mapping/repository.py | .py | 1810e1fc6c09ca48 | 7 | 0 |
"""Pure exact-match mapping from purchase lines to catalog evidence."""
from __future__ import annotations
from collections.abc import Mapping, Sequence
from lookinkin.catalog_mapping.models import (
CatalogMappingStatus,
CatalogProduct,
MappedPurchaseLine,
NutritionSnapshot,
PurchaseLine,
)
de... | Sayomphon/LookinKin | lookinkin/catalog_mapping/service.py | .py | 2a836eb55d83eedf | 7 | 0 |
"""Validated application configuration loaded from environment variables."""
from __future__ import annotations
from functools import lru_cache
from typing import Literal
from urllib.parse import quote, urlsplit
from pydantic import (
AwareDatetime,
Field,
SecretStr,
computed_field,
field_validat... | Sayomphon/LookinKin | lookinkin/config.py | .py | 314fe8ddd74892fa | 7 | 0 |
"""Async SQLAlchemy engine and request-scoped sessions."""
from __future__ import annotations
from collections.abc import AsyncIterator
from functools import lru_cache
from sqlalchemy.ext.asyncio import (
AsyncEngine,
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from lookinkin.config imp... | Sayomphon/LookinKin | lookinkin/db/session.py | .py | 3f2e7165fa7f8c3e | 7 | 0 |
"""Portable SQLAlchemy types enforcing LookinKin data invariants."""
from __future__ import annotations
from datetime import UTC, datetime
from sqlalchemy import DateTime
from sqlalchemy.engine.interfaces import Dialect
from sqlalchemy.types import TypeDecorator
class UTCDateTime(TypeDecorator[datetime]):
"""S... | Sayomphon/LookinKin | lookinkin/db/types.py | .py | c03508d33e25a429 | 7 | 0 |
"""Pure presentation mapping for the local Streamlit demo."""
from __future__ import annotations
import enum
from collections.abc import Mapping
from dataclasses import dataclass
from datetime import date, datetime, timedelta
from decimal import ROUND_DOWN, Decimal
from types import MappingProxyType
from lookinkin.f... | Sayomphon/LookinKin | lookinkin/demo/presentation.py | .py | 529ccefb9e500a68 | 7 | 0 |
"""Domain models for weekly feature windows and evidence."""
from __future__ import annotations
import enum
from dataclasses import dataclass
from datetime import UTC, datetime, time, timedelta
from decimal import Decimal
from zoneinfo import ZoneInfo
BANGKOK_TIMEZONE = ZoneInfo("Asia/Bangkok")
RATIO_QUANTUM = Decim... | Sayomphon/LookinKin | lookinkin/feature_engine/models.py | .py | 166a2eeb4b359f77 | 7 | 0 |
"""Liveness and dependency-readiness endpoints."""
from __future__ import annotations
import asyncio
from typing import Annotated, Literal
from fastapi import APIRouter, Depends
from pydantic import BaseModel
from redis.asyncio import Redis
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession
... | Sayomphon/LookinKin | lookinkin/health/router.py | .py | ddfae09e945acb65 | 7 | 0 |
"""Small ASGI middleware for local API hardening."""
from __future__ import annotations
from collections.abc import Awaitable, Callable
from typing import Any
from starlette.datastructures import Headers, MutableHeaders
from starlette.responses import JSONResponse
from starlette.types import ASGIApp, Message, Receiv... | Sayomphon/LookinKin | lookinkin/http.py | .py | 73694655d06ae8cd | 7 | 0 |
"""Application orchestration for explicit weekly insight generation."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from sqlalchemy.ext.asyncio import AsyncSession
from lookinkin.insights.schemas import LatestInsightsResponse
from lookinkin.insights.service imp... | Sayomphon/LookinKin | lookinkin/insights/generation.py | .py | 1a725c456201b478 | 7 | 0 |
"""Strict API contracts for weekly features and explainable insights."""
from __future__ import annotations
import enum
from decimal import Decimal
from pydantic import AwareDatetime, BaseModel, ConfigDict, Field
from lookinkin.recommendation.models import (
CandidateEvidence,
CoverageFailure,
CoverageS... | Sayomphon/LookinKin | lookinkin/insights/schemas.py | .py | 27ffb1438d83cecc | 7 | 0 |
"""Application logging that avoids leaking payloads or credentials."""
from __future__ import annotations
import logging
from typing import Any
from lookinkin.config import Settings
class ContextAdapter(logging.LoggerAdapter[logging.Logger]):
"""Attach safe operational identifiers to log records."""
def p... | Sayomphon/LookinKin | lookinkin/logging.py | .py | c45c239cceadf2db | 7 | 0 |
"""Celery dispatch adapter isolated from the ingestion domain service."""
from __future__ import annotations
import asyncio
from functools import lru_cache
from typing import Protocol
from celery import Celery
from lookinkin.config import get_settings
PROCESS_EVENT_TASK = "lookinkin.partner_ingestion.process_event... | Sayomphon/LookinKin | lookinkin/partner_ingestion/dispatcher.py | .py | e27d8e1723f12c5e | 7 | 0 |
"""Strict API contracts for synthetic partner purchase events."""
from __future__ import annotations
import enum
from datetime import datetime
from decimal import Decimal
from typing import Annotated, Literal
from pydantic import (
AwareDatetime,
BaseModel,
ConfigDict,
Field,
StringConstraints,
... | Sayomphon/LookinKin | lookinkin/partner_ingestion/schemas.py | .py | 107390eac72679d3 | 7 | 0 |
"""Transactional event inbox and idempotent partner ingestion."""
from __future__ import annotations
import hashlib
import json
import logging
import uuid
from dataclasses import dataclass
from sqlalchemy import select, update
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
... | Sayomphon/LookinKin | lookinkin/partner_ingestion/service.py | .py | cba535461f9797e7 | 7 | 0 |
"""Atomic orchestration of ledger, weekly features, and business rules."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass, field
from datetime import UTC, datetime
from sqlalchemy.ext.asyncio import AsyncSession
from lookinkin.db.models import EventStatus, ... | Sayomphon/LookinKin | lookinkin/processing/service.py | .py | f5f70523674373aa | 7 | 0 |
"""
Apply the trained per-pixel HistGradientBoostingClassifier crack detector
(the shipped 17-feature member, models/f17_v3_*.joblib) to a single raw TXM
TIFF image and produce a clean, post-processed crack mask.
This script only *applies* the already-trained model -- it does not retrain
or refit anything.
Pipeline:
... | jzhang29-max/TXM_Crack_Detection_Pipeline | code/apply_pixel_model.py | .py | d6afbc9c4498c61c | 7 | 0 |
"""Sample the owner's own corrections into a cross-validation fold file, all specimen groups.
python3 code/build_label_folds.py # build (slow, one-off, cached)
python3 code/build_label_folds.py --per-image 20000
python3 code/build_label_folds.py --list # what it would do, no work
... | jzhang29-max/TXM_Crack_Detection_Pipeline | code/build_label_folds.py | .py | f91dde95a1e44349 | 7 | 0 |
"""
Load every TXM image into the app and predict it, reusing the research SAM cache.
python3 code/load_all_images.py # the 71 images shipped in images/
python3 code/load_all_images.py --src /some/other/dir
python3 code/load_all_images.py --src <dir> --dry-run
Why this exists rather than ... | jzhang29-max/TXM_Crack_Detection_Pipeline | code/load_all_images.py | .py | b75ed2c416f43f5d | 7 | 0 |
"""
One-time, reusable SAM ViT-H embedding cache for all 71 images.
Why cache. Every hybrid operation -- training, inference, and every future
retrain after new paint corrections -- needs SAM's image embedding for the same
images. Recomputing costs GPU seconds per tile and would make the paint tool's
interactive loop ... | jzhang29-max/TXM_Crack_Detection_Pipeline | research/code/cache_sam_embeddings.py | .py | 6f78ade6294b2409 | 7 | 0 |
"""
Force-NOT-crack on the false positives visible in results/final_71 overlays.
Everything here removes predictions; nothing adds any. That asymmetry is
deliberate -- the user corrected two attempts at automated POSITIVE labelling
(elongated inclusions mislabelled as crack; the large dark wedge mislabelled
as a thick... | jzhang29-max/TXM_Crack_Detection_Pipeline | research/code/clean_false_positives.py | .py | 6fe736adbab0e481 | 7 | 0 |
"""
Qualitative before/after figure for the HistGradientBoosting -> MLP
production swap: raw image | previous production (HGB) overlay | new
production (MLP) overlay, for a few representative images, plus a final
deployment summary table for paper-comparison purposes.
Run AFTER retrain_and_deploy.py has actually deplo... | jzhang29-max/TXM_Crack_Detection_Pipeline | research/code/generate_deployment_comparison.py | .py | 86568ee8feef01d4 | 7 | 0 |
"""
Label THICK crack interiors -- the gap write_positive_crack_labels.py could
not fill and explicitly skipped.
Why a separate method is needed: that script defines crack as "dark
relative to LOCAL surroundings", which is a band-pass test. Inside a wide
crack the local background is itself dark, so the contrast vanis... | jzhang29-max/TXM_Crack_Detection_Pipeline | research/code/label_thick_cracks.py | .py | 7ce002c7fdd6b715 | 7 | 0 |
#!/usr/bin/env python3
"""
Generate archive page for /words/
Reads posts-metadata.json and creates an index page
sorted by date (newest first).
Usage:
python3 generate_archive.py
"""
import os
import json
from datetime import datetime
from pylib.utils import format_date_for_display
from pylib.templates import ht... | sooperT/gdocs-blog | generate_archive.py | .py | c0963fada7a49754 | 7 | 0 |
#!/usr/bin/env python3
"""
Generate homepage with excerpt of latest post
Reads posts-metadata.json to find the latest "words" post, extracts an excerpt
from the full post content, and generates /index.html with standard header/nav/footer.
Usage:
python3 generate_homepage.py
"""
import os
import json
import re
fr... | sooperT/gdocs-blog | generate_homepage.py | .py | c038d7eec59bdec5 | 7 | 0 |
#!/usr/bin/env python3
"""
Generate sitemap.xml for SEO
Reads posts-metadata.json and generates a sitemap including:
- Homepage
- Archive pages (/words/, /projects/)
- Individual posts
- Static pages (/about/)
Usage:
python3 generate_sitemap.py
"""
import os
import json
from datetime import datetime
from xml.etr... | sooperT/gdocs-blog | generate_sitemap.py | .py | b9b00d90e32ab798 | 7 | 0 |
#!/usr/bin/env python3
"""Parse content and load into database with embeddings."""
import os
import re
import json
from pathlib import Path
from dotenv import load_dotenv
import psycopg2
import requests
from html.parser import HTMLParser
load_dotenv()
VOYAGE_API_KEY = os.getenv("VOYAGE_API_KEY")
NILEDB_URL = os.gete... | sooperT/gdocs-blog | scripts/load_content.py | .py | c862d07cca5373b3 | 7 | 0 |
#!/usr/bin/env python3
"""
Load parsed content into database for TomBot v3.
For each section:
- Embeds the answer content (stored in 'embedding')
- Embeds each question variation (stored in 'question_embedding')
- Creates one row per question variation for better matching
This means a section with 10 question variati... | sooperT/gdocs-blog | scripts/load_content_v3.py | .py | 590ba1f7d7ae0f40 | 7 | 0 |
#!/usr/bin/env python3
"""
Parse tombot-content-v3.md into structured chunks for RAG.
Output format for each section:
{
"id": "NOVO.R1",
"questions": ["Tell me about...", "What did you do..."],
"content": "The answer content...",
"drill_downs": ["NOVO.R1.TRANSFORM", "NOVO.R1.ALGORITHM"],
"follow_up... | sooperT/gdocs-blog | scripts/parse_content.py | .py | f2aff38df86d4f7a | 7 | 0 |
#!/usr/bin/env python3
"""
Local preview server for blog development
Runs a simple HTTP server to preview the blog locally before deploying.
This helps conserve Netlify build credits by allowing local iteration.
Usage:
python3 serve.py
The server will start at http://localhost:8000
Press Ctrl+C to stop the serve... | sooperT/gdocs-blog | serve.py | .py | 8439b998062d27e6 | 7 | 0 |
#!/usr/bin/env python3
"""
Validate that generated files match their generators.
This script checks that HTML files can be regenerated from their source
generators without changes. Prevents drift between generators and outputs.
Usage:
python3 validate_generators.py
"""
import os
import sys
import subprocess
impo... | sooperT/gdocs-blog | validate_generators.py | .py | c72b10f2e23beeab | 7 | 0 |
#!/usr/bin/env python3
"""Generate per-harness JWTs.
Usage:
JWT_SECRET=... python3 scripts/generate-tokens.py [--days 30]
Prints `TOKEN_<NAME>=<jwt>` lines to stdout. Paste into .env (or pipe through
`sponge` / `envsubst`). Re-running rotates everything — invalidates any
previously issued token for the same harn... | azzindani/Harnesses | scripts/generate-tokens.py | .py | 35eb784b0ada7110 | 7 | 0 |
#!/usr/bin/env python3
"""Did every tool a phase was told to call actually get a row?
python3 check_coverage.py [--plan phases_r15.tsv] [--data /root/Harnesses/data]
The driver already prints "rows: 6 of 6" per phase, but it counts table rows and
nothing more -- six rows covering five tools twice is six rows. And... | azzindani/Harnesses | scripts/sweep/check_coverage.py | .py | 97a97dedbf526ac5 | 7 | 0 |
"""Build a sweep phase plan: tools/list output + one axis -> phases_rNN.tsv.
python3 make_plan.py --round 11 --tools tools_r11.tsv --out phases_r11.tsv
The tools file is two tab-separated columns, server and tool, exactly as
tools/list reports them -- never a list the sweep model wrote itself, which once
silently... | azzindani/Harnesses | scripts/sweep/make_plan.py | .py | 8fb82a6bb7e85d4c | 7 | 0 |
#!/usr/bin/env python3
"""Open every file a sweep produced and say whether it is usable.
/usr/bin/python3 verify_artifacts.py [--dir DIR] [--out REPORT.md] [--shots DIR]
This is the half of round 15's axis that a model cannot do. The sweep model can
read a file and describe it; it cannot render one and see whethe... | azzindani/Harnesses | scripts/sweep/verify_artifacts.py | .py | 3289d38eec7dfe8f | 7 | 0 |
"""A router that learns which model to trust, instead of being told.
The framing that makes this work is not "predict the best model". It is:
For each model, predict the probability it answers THIS question correctly.
That gives a probability per model rather than a single choice, and the routing
rule sits on to... | vbvansh/switchboard | eval/benchmarks/learned.py | .py | 235cfe246a45c45d | 7 | 0 |
"""Loader for LLMRouterBench.
LLMRouterBench: A Massive Benchmark and Unified Framework for LLM Routing
Findings of ACL 2026 - arXiv:2601.07206
Two things about this archive shape the loader.
First, the directory layout is inconsistent: some benchmarks are
`<benchmark>/test/<model>/*.json`, others put models... | vbvansh/switchboard | eval/benchmarks/llmrouterbench.py | .py | 6a84553038973f22 | 7 | 0 |
"""Loader for xRouteBench.
LLMRouter: Unified Infrastructure for Developing, Evaluating, and
Deploying LLM Routers - ulab-ai/xRouteBench on HuggingFace
Smaller and tidier than LLMRouterBench: Parquet, ~47 MB, downloaded on demand.
Its models are open-weight rather than the commercial flagships, but it is the
... | vbvansh/switchboard | eval/benchmarks/xroutebench.py | .py | cf3d4ef2324247ce | 7 | 0 |
"""Objective grading. No LLM judge involved.
A judge model would need to be more capable than the models being judged, and
this project has no such model available. So every task carries a
mechanically-checkable answer instead: a number, an exact string, or required
substrings. Slower to author, but the resulting accu... | vbvansh/switchboard | eval/grading.py | .py | c2e69e404984da22 | 7 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.