Judge every article locally: serious cases by keywords, tone grade and importance (refs #57)
This is the first judgement of SPEC 10.2 point 4, without a language model. - Serious cases: cyberattack, suspension, fraud, bankruptcy, investigation and delisting are found by whole-word phrases in English and Italian, so an Italian headline still counts. - Tone: the five tone grades follow the bounds of the specification. - Importance: 4 for a serious case, 3 for a negative tone, 2 when the article is linked to an instrument, otherwise 1. - Classifier: it sits behind IToneClassifier and is asked only for English titles. The ONNX model plugs in there; without it the tone stays unknown and everything else works. Every article stores its score, case and importance. Each story keeps the mean score, the case and the highest importance. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f1ba452aba
commit
9ee2367693
5 files changed
+259
-12
No files matched your search
@@ -23,7 +23,9 @@ CREATE TABLE news_sources (
|
||||
){strict};
|
||||
|
||||
-- One story, told by one or more articles. sources counts the independent publishers (two feeds of the same
|
||||
-- newspaper count once); trusted says whether at least one article came from a trusted source.
|
||||
-- newspaper count once); trusted says whether at least one article came from a trusted source. score, severe and
|
||||
-- importance sum up the first judgement of its articles (10.2 point 4): the mean score, a serious case if any
|
||||
-- article names one, the highest importance.
|
||||
CREATE TABLE news_stories (
|
||||
id {uuid} PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
@@ -33,6 +35,9 @@ CREATE TABLE news_stories (
|
||||
last_seen_at {timestamp} NOT NULL,
|
||||
sources INTEGER NOT NULL,
|
||||
trusted {bool} NOT NULL,
|
||||
score {float},
|
||||
severe TEXT,
|
||||
importance INTEGER NOT NULL,
|
||||
created_at {timestamp} NOT NULL,
|
||||
updated_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
@@ -40,7 +45,8 @@ CREATE TABLE news_stories (
|
||||
CREATE INDEX news_stories_published ON news_stories (published_at);
|
||||
|
||||
-- One article. url_key is the address without tracking parameters, fragments and the other differences that do
|
||||
-- not change the article: the same article is never stored twice.
|
||||
-- not change the article: the same article is never stored twice. score is the tone of the local classifier, from
|
||||
-- -1 to +1, for English titles only (null otherwise); severe the serious case found by the keywords; importance 1 to 4.
|
||||
CREATE TABLE news_items (
|
||||
id {uuid} PRIMARY KEY,
|
||||
story_id {uuid} NOT NULL REFERENCES news_stories (id),
|
||||
@@ -52,6 +58,9 @@ CREATE TABLE news_items (
|
||||
summary TEXT,
|
||||
language TEXT NOT NULL,
|
||||
published_at {timestamp} NOT NULL,
|
||||
score {float},
|
||||
severe TEXT,
|
||||
importance INTEGER NOT NULL,
|
||||
created_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Anubis.News;
|
||||
|
||||
/// <summary>The serious cases of SPEC 10.2 point 4, found by keywords in English and in Italian.</summary>
|
||||
public static class SevereKinds
|
||||
{
|
||||
public const string Cyberattack = "cyberattack";
|
||||
public const string Suspension = "suspension";
|
||||
public const string Fraud = "fraud";
|
||||
public const string Bankruptcy = "bankruptcy";
|
||||
public const string Investigation = "investigation";
|
||||
public const string Delisting = "delisting";
|
||||
}
|
||||
|
||||
/// <summary>The five grades of tone of SPEC 10.2 point 4.</summary>
|
||||
public enum Tone
|
||||
{
|
||||
Negative = -2,
|
||||
SlightlyNegative = -1,
|
||||
Neutral = 0,
|
||||
SlightlyPositive = 1,
|
||||
Positive = 2,
|
||||
}
|
||||
|
||||
/// <summary>What the local classifier says of an English text: the probabilities of its three classes.</summary>
|
||||
public sealed record ToneScore(double Positive, double Negative, double Neutral)
|
||||
{
|
||||
/// <summary>The score of 10.2: probability of positive minus probability of negative, from −1 to +1.</summary>
|
||||
public double Score => Positive - Negative;
|
||||
}
|
||||
|
||||
/// <summary>The local classifier of SPEC 4.5. It reads only English; for other texts the caller does not ask.</summary>
|
||||
public interface IToneClassifier
|
||||
{
|
||||
ToneScore Classify(string text);
|
||||
}
|
||||
|
||||
/// <summary>The first judgement of an article: tone, serious case and importance, all without a language model.</summary>
|
||||
public sealed record NewsJudgement(double? Score, string? Severe, int Importance)
|
||||
{
|
||||
public Tone? Tone => Score is { } s ? NewsJudge.Grade(s) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The first judgement of SPEC 10.2 point 4, local and free. The tone comes from the classifier for English texts;
|
||||
/// the serious cases from keywords in two languages, so an Italian title of a fraud is still a serious case.
|
||||
/// Importance: 4 to the serious cases, 3 to a negative article (score up to −0.6), 2 to the others linked to an
|
||||
/// instrument, 1 to the rest. The 5 is given only by the language model (#58); a calendar event (3) arrives with #59.
|
||||
/// </summary>
|
||||
public static partial class NewsJudge
|
||||
{
|
||||
// Lower case, words separated by single spaces. A phrase matches whole words only: "hacked" is not "hack".
|
||||
private static readonly (string Kind, string[] Phrases)[] Keywords =
|
||||
[
|
||||
(SevereKinds.Cyberattack,
|
||||
[
|
||||
"hack", "hacked", "hacker", "hackers", "hacking", "cyberattack", "cyber attack", "cyberattacks", "ransomware", "data breach", "security breach",
|
||||
"exploit", "exploited", "drained", "attacco informatico", "attacchi informatici", "attacco hacker", "violazione dei dati",
|
||||
]),
|
||||
(SevereKinds.Suspension,
|
||||
[
|
||||
"trading halt", "trading halted", "halts trading", "halted trading", "suspends trading", "trading suspended", "suspended from trading",
|
||||
"halts withdrawals", "halted withdrawals", "suspends withdrawals", "withdrawals halted", "withdrawals suspended", "pauses withdrawals",
|
||||
"sospeso dalle negoziazioni", "sospensione delle negoziazioni", "sospende le negoziazioni", "titolo sospeso", "sospende i prelievi",
|
||||
"sospensione dei prelievi", "blocca i prelievi",
|
||||
]),
|
||||
(SevereKinds.Fraud,
|
||||
[
|
||||
"fraud", "frauds", "fraudulent", "ponzi", "embezzlement", "accounting irregularities", "frode", "frodi", "truffa", "falso in bilancio",
|
||||
"irregolarità contabili",
|
||||
]),
|
||||
(SevereKinds.Bankruptcy,
|
||||
[
|
||||
"bankruptcy", "bankrupt", "chapter 11", "insolvency", "insolvent", "files for bankruptcy", "fallimento", "bancarotta", "insolvenza",
|
||||
"insolvente", "concordato preventivo", "amministrazione straordinaria",
|
||||
]),
|
||||
(SevereKinds.Investigation,
|
||||
[
|
||||
"investigation", "investigations", "probe", "probes", "subpoena", "subpoenaed", "indicted", "indictment", "charged with", "sec charges",
|
||||
"raided", "indagine", "indagini", "indagato", "indagati", "inchiesta", "perquisizione", "perquisizioni",
|
||||
]),
|
||||
(SevereKinds.Delisting,
|
||||
[
|
||||
"delist", "delisted", "delisting", "delistings", "revoca dalla quotazione", "esclusione dalle negoziazioni",
|
||||
]),
|
||||
];
|
||||
|
||||
/// <summary>The grade of a score, with the bounds of 10.2: up to −0.6, −0.2, +0.2, +0.6, then positive.</summary>
|
||||
public static Tone Grade(double score) => score switch
|
||||
{
|
||||
<= -0.6 => Tone.Negative,
|
||||
<= -0.2 => Tone.SlightlyNegative,
|
||||
<= 0.2 => Tone.Neutral,
|
||||
<= 0.6 => Tone.SlightlyPositive,
|
||||
_ => Tone.Positive,
|
||||
};
|
||||
|
||||
/// <summary>The first serious case named by the text, in the order of 10.2, or null.</summary>
|
||||
public static string? Severe(string title, string? summary)
|
||||
{
|
||||
var text = " " + Spaces().Replace(NonWord().Replace((title + " " + summary).ToLowerInvariant().Replace('’', '\''), " "), " ") + " ";
|
||||
foreach (var (kind, phrases) in Keywords)
|
||||
{
|
||||
if (phrases.Any(p => text.Contains(" " + p + " ", StringComparison.Ordinal)))
|
||||
{
|
||||
return kind;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The judgement of one article. The classifier is asked only for English and only when it exists.</summary>
|
||||
public static NewsJudgement Judge(string title, string? summary, string language, bool linkedToInstrument, IToneClassifier? classifier)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(title);
|
||||
double? score = classifier is not null && language == "en" ? Math.Clamp(classifier.Classify(title).Score, -1, 1) : null;
|
||||
var severe = Severe(title, summary);
|
||||
var importance = severe is not null ? 4 : score <= -0.6 ? 3 : linkedToInstrument ? 2 : 1;
|
||||
return new NewsJudgement(score, severe, importance);
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"[^\p{L}\p{N}']+")]
|
||||
private static partial Regex NonWord();
|
||||
|
||||
[GeneratedRegex(@"\s+")]
|
||||
private static partial Regex Spaces();
|
||||
}
|
||||
@@ -35,6 +35,9 @@ public sealed partial class NewsCollector(HttpClient http, Database db, IClock c
|
||||
|
||||
public NewsStore Store => _store;
|
||||
|
||||
/// <summary>The local classifier of SPEC 4.5; without it the tone is unknown and only the keywords judge.</summary>
|
||||
public IToneClassifier? Classifier { get; init; }
|
||||
|
||||
public ScheduledJob Job() => new(JobName, "Lettura delle notizie", Schedule.Every(Interval), RunOnceAsync) { MaxLateness = Interval };
|
||||
|
||||
/// <summary>One round over the sources that are due.</summary>
|
||||
@@ -107,7 +110,7 @@ public sealed partial class NewsCollector(HttpClient http, Database db, IClock c
|
||||
|
||||
var content = await ReadLimitedAsync(response.Content, timeout.Token).ConfigureAwait(false);
|
||||
var items = FeedParser.Parse(content);
|
||||
var result = await _store.IngestAsync(source, items, dictionary, cancellationToken).ConfigureAwait(false);
|
||||
var result = await _store.IngestAsync(source, items, dictionary, cancellationToken, Classifier).ConfigureAwait(false);
|
||||
await _store.RecordCheckAsync(source, ok: true, response.Headers.ETag?.ToString(), response.Content.Headers.LastModified?.ToString("R"), null, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (result.Added > 0)
|
||||
|
||||
@@ -104,7 +104,8 @@ public sealed class NewsStore(Database db, IClock clock)
|
||||
/// story whose title it retells, within two days, or starts a new one. The story counts again its independent
|
||||
/// publishers and whether a trusted source told it.
|
||||
/// </summary>
|
||||
public async Task<IngestResult> IngestAsync(NewsSource source, IReadOnlyList<FeedItem> items, NewsLinker dictionary, CancellationToken cancellationToken)
|
||||
public async Task<IngestResult> IngestAsync(
|
||||
NewsSource source, IReadOnlyList<FeedItem> items, NewsLinker dictionary, CancellationToken cancellationToken, IToneClassifier? classifier = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
ArgumentNullException.ThrowIfNull(items);
|
||||
@@ -140,20 +141,23 @@ public sealed class NewsStore(Database db, IClock clock)
|
||||
{
|
||||
story = Ids.NewId(clock);
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO news_stories (id, title, title_key, published_at, first_seen_at, last_seen_at, sources, trusted, created_at, updated_at) " +
|
||||
"VALUES (@id, @title, @key, @p, @now, @now, 1, @trusted, @now, @now)", cancellationToken,
|
||||
"INSERT INTO news_stories (id, title, title_key, published_at, first_seen_at, last_seen_at, sources, trusted, importance, created_at, updated_at) " +
|
||||
"VALUES (@id, @title, @key, @p, @now, @now, 1, @trusted, 1, @now, @now)", cancellationToken,
|
||||
("id", story), ("title", item.Title), ("key", NewsMatching.TitleKey(item.Title)), ("p", published), ("now", now), ("trusted", source.Trusted))
|
||||
.ConfigureAwait(false);
|
||||
stories.Add((story.Value, words, published));
|
||||
}
|
||||
|
||||
var language = item.Language ?? Languages.Guess(item.Title + " " + item.Summary);
|
||||
var links = dictionary.Link(item.Title, item.Summary, item.Symbols, source.Topic);
|
||||
var judgement = NewsJudge.Judge(item.Title, item.Summary, language, links.Any(l => l.Scope == LinkScopes.Instrument), classifier);
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO news_items (id, story_id, source_id, url, url_key, publisher, title, summary, language, published_at, created_at) " +
|
||||
"VALUES (@id, @story, @source, @url, @key, @pub, @title, @summary, @lang, @p, @now)", cancellationToken,
|
||||
"INSERT INTO news_items (id, story_id, source_id, url, url_key, publisher, title, summary, language, published_at, score, severe, importance, created_at) " +
|
||||
"VALUES (@id, @story, @source, @url, @key, @pub, @title, @summary, @lang, @p, @score, @severe, @importance, @now)", cancellationToken,
|
||||
("id", Ids.NewId(clock)), ("story", story), ("source", source.Id), ("url", item.Link), ("key", key), ("pub", NewsMatching.Publisher(item.Link)),
|
||||
("title", item.Title), ("summary", item.Summary), ("lang", item.Language ?? Languages.Guess(item.Title + " " + item.Summary)), ("p", published),
|
||||
("now", now)).ConfigureAwait(false);
|
||||
foreach (var link in dictionary.Link(item.Title, item.Summary, item.Symbols, source.Topic))
|
||||
("title", item.Title), ("summary", item.Summary), ("lang", language), ("p", published), ("score", judgement.Score), ("severe", judgement.Severe),
|
||||
("importance", judgement.Importance), ("now", now)).ConfigureAwait(false);
|
||||
foreach (var link in links)
|
||||
{
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO news_links (id, story_id, scope, target, via, created_at) VALUES (@id, @story, @scope, @target, @via, @now) " +
|
||||
@@ -170,7 +174,10 @@ public sealed class NewsStore(Database db, IClock clock)
|
||||
await s.ExecuteAsync(
|
||||
"UPDATE news_stories SET last_seen_at = @now, updated_at = @now, " +
|
||||
"sources = (SELECT COUNT(DISTINCT publisher) FROM news_items WHERE story_id = @id), " +
|
||||
"trusted = (SELECT COUNT(*) FROM news_items i JOIN news_sources so ON so.id = i.source_id WHERE i.story_id = @id AND so.trusted = @yes) > 0 " +
|
||||
"trusted = (SELECT COUNT(*) FROM news_items i JOIN news_sources so ON so.id = i.source_id WHERE i.story_id = @id AND so.trusted = @yes) > 0, " +
|
||||
"score = (SELECT AVG(score) FROM news_items WHERE story_id = @id), " +
|
||||
"severe = (SELECT MIN(severe) FROM news_items WHERE story_id = @id), " +
|
||||
"importance = (SELECT MAX(importance) FROM news_items WHERE story_id = @id) " +
|
||||
"WHERE id = @id", cancellationToken, ("now", now), ("id", id), ("yes", true)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user