humanize

package
v1.6.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 12, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CountWords

func CountWords(s string) int

func CyrillicShare

func CyrillicShare(text string) float64

func FillLines

func FillLines(text string, hits []Hit)

func MarkerVerdict

func MarkerVerdict(rs *RuleSet, hits []Hit, words int) string

MarkerVerdict - плотность маркеров, а не вердикт об авторстве: абсолютный счёт на длинном тексте всегда давал "AI". Полосы здесь свои, не измеренные.

func StripMarkup added in v1.1.0

func StripMarkup(text string) string

StripMarkup гасит разметку пробелами: длина и переводы строк сохраняются, поэтому номера строк и позиции находок остаются верными.

func ToSet

func ToSet(items []string) map[string]bool

func Words

func Words(s string) []string

Words - слова текста, буквы и цифры. Нужен пакету code, чтобы сравнивать слова комментария с именем в коде тем же способом, что и тут.

Types

type Category

type Category struct {
	Name  string
	Fix   string
	Lift  float64
	Rules []Rule
}

type CategorySpec

type CategorySpec struct {
	Name  string     `yaml:"name"`
	Fix   string     `yaml:"fix"`
	Lift  float64    `yaml:"lift,omitempty"`
	Rules []RuleSpec `yaml:"rules"`
}

type GenreSpec

type GenreSpec struct {
	MuteBans       []string `yaml:"mute_bans"`
	MuteCategories []string `yaml:"mute_categories"`
	// CVHumanTarget - свой порог рваности ритма для этого регистра. Технический
	// текст ровнее разговорного, и один порог на всех наказывал документацию.
	CVHumanTarget *float64 `yaml:"cv_human_target,omitempty"`
}

type Hit

type Hit struct {
	Category  string  `json:"category"`
	Marker    string  `json:"marker"`
	Fix       string  `json:"fix,omitempty"`
	Lift      float64 `json:"lift,omitempty"`
	Count     int     `json:"count"`
	Positions []int   `json:"-"`
	Lines     []int   `json:"lines"`
}

Hit — попадание одного правила.

func EffectiveHardBans

func EffectiveHardBans(rs *RuleSet, hits []Hit, words int) []Hit

EffectiveHardBans: частотные баны остаются банами только выше плотности 1/N слов.

func MuteByCategory

func MuteByCategory(hits []Hit, muted map[string]bool) []Hit

func MuteByName

func MuteByName(hits []Hit, muted map[string]bool) []Hit

func ScanHardBans

func ScanHardBans(rs *RuleSet, text string) []Hit

func ScanMarkers

func ScanMarkers(rs *RuleSet, text string) []Hit

type Morph

type Morph struct {
	Nominalizations int     `json:"nominalizations"`
	Per100          float64 `json:"per_100_words"`
	VerbForms       int     `json:"verb_forms"`
}

Morph - номинальность. Суффиксная эвристика вместо pymorphy3: не отличает «решение задачи» от «решение принято», апгрейд - морфоанализатор.

type Penalty

type Penalty struct {
	Reason string `json:"reason"`
	Points int    `json:"points"`
}

type Repeat added in v1.1.0

type Repeat struct {
	Phrase string `json:"phrase"`
	Count  int    `json:"count"`
}

Repeat - трёхсловие, повторённое в тексте. Повтор одной и той же формулировки три раза и больше - дефект письма независимо от того, кто писал.

type Report

type Report struct {
	Genre      string    `json:"genre"`
	HardBans   []Hit     `json:"hard_bans"`
	Markers    []Hit     `json:"markers"`
	Rhythm     Rhythm    `json:"rhythm"`
	Morph      Morph     `json:"morph"`
	Structure  Structure `json:"structure"`
	Score      Score     `json:"score"`
	MutedBans  int       `json:"muted_bans"`
	MutedSoft  int       `json:"muted_markers"`
	NotRussian bool      `json:"not_russian"`
}

Report — всё, что посчитано по тексту.

func Analyze

func Analyze(rs *RuleSet, text, genre string) Report

type Rhythm

type Rhythm struct {
	Sentences   int     `json:"sentences"`
	Words       int     `json:"words"`
	MeanLen     float64 `json:"mean_len"`
	CVLen       float64 `json:"cv_len"`
	MinLen      int     `json:"min_len"`
	MaxLen      int     `json:"max_len"`
	MeanWordLen float64 `json:"mean_word_len"`
	LongWords   float64 `json:"long_word_share"`
	EmDash      int     `json:"em_dash"`
	Ellipsis    int     `json:"ellipsis"`
	Parentheses int     `json:"parentheses"`
	Questions   int     `json:"questions"`
}

Rhythm — ритм предложений и типографика.

type Rule

type Rule struct {
	Name string
	Fix  string
	Lift float64
	// contains filtered or unexported fields
}

type RuleFile

type RuleFile struct {
	Version           int                  `yaml:"version"`
	Thresholds        Thresholds           `yaml:"thresholds"`
	FreqBans          map[string]int       `yaml:"freq_bans"`
	HardBans          []RuleSpec           `yaml:"hard_bans"`
	Categories        []CategorySpec       `yaml:"categories"`
	CopyPasteCategory string               `yaml:"copy_paste_category"`
	Genres            map[string]GenreSpec `yaml:"genres"`
}

type RuleSet

type RuleSet struct {
	Thresholds        Thresholds
	FreqBans          map[string]int
	HardBans          []Rule
	Categories        []Category
	CopyPasteCategory string
	Genres            []string
	// contains filtered or unexported fields
}

func LoadBuiltin

func LoadBuiltin(name string) (*RuleSet, error)

LoadBuiltin: вшитый набор по имени. "ru" - русская проза, "en" - английская, "code" - правила для комментариев и коммитов поверх языкового набора.

func LoadRules

func LoadRules(path string) (*RuleSet, error)

LoadRules читает набор правил. Пустой path — встроенный rules.yaml.

func (*RuleSet) CVTarget added in v1.1.0

func (rs *RuleSet) CVTarget(genre string) float64

CVTarget - порог рваности ритма для жанра, общий если своего нет.

func (*RuleSet) HasGenre

func (rs *RuleSet) HasGenre(name string) bool

func (*RuleSet) MutedBans

func (rs *RuleSet) MutedBans(genre string) map[string]bool

MutedBans и MutedCategories - что жанр снимает. Nil для неизвестного жанра: ничего не заглушено, это и есть строгий режим.

func (*RuleSet) MutedCategories

func (rs *RuleSet) MutedCategories(genre string) map[string]bool

type RuleSpec

type RuleSpec struct {
	Name    string  `yaml:"name"`
	Fix     string  `yaml:"fix"`
	Lift    float64 `yaml:"lift,omitempty"`
	Lit     string  `yaml:"lit"`
	Re      string  `yaml:"re"`
	WordRe  string  `yaml:"word_re"`
	Builtin string  `yaml:"builtin"`
}

type Score

type Score struct {
	Value     int       `json:"score"`
	Band      string    `json:"band"`
	Penalties []Penalty `json:"penalties"`
	Notes     []string  `json:"notes,omitempty"`
}

Score — чистота 0-100: не вероятность ИИ, а агрегат метрик для сравнения «было / стало». Веса перенесены из humanizer_metrics/score.py, кроме пункта 6.

type Structure

type Structure struct {
	Paragraphs      int      `json:"paragraphs"`
	ParaMeanSent    float64  `json:"para_mean_sent"`
	ParaCV          float64  `json:"para_cv"`
	ListItems       int      `json:"list_items"`
	ListicleShare   float64  `json:"listicle_share"`
	TitleCaseHeads  int      `json:"title_case_headings"`
	TruncatedEnding bool     `json:"truncated_ending"`
	RepeatPer1000   float64  `json:"repeat_per_1000"`
	Repeats         []Repeat `json:"repeats,omitempty"`
}

Structure — метрики уровня документа.

type Thresholds

type Thresholds struct {
	CVHumanTarget    float64 `yaml:"cv_human_target"`
	CVAIThreshold    float64 `yaml:"cv_ai_threshold"`
	NominalTarget    float64 `yaml:"nominal_target"`
	ParaCVAI         float64 `yaml:"para_cv_ai"`
	ParaMinCount     int     `yaml:"para_min_count"`
	ListicleShareAI  float64 `yaml:"listicle_share_ai"`
	ListicleMinItems int     `yaml:"listicle_min_items"`
	BandClean        int     `yaml:"band_clean"`
	BandEdit         int     `yaml:"band_edit"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL