// Perception — construire les cinq segments et déduire leur forme
// Représentation commune, réutilisée de Compression-07b : identifiant stable,
// octets, genre et lien vers l'origine. Une racine a un parent vide.
record Segment(string Id, byte[] Data, string Genre = "brut", string Parent = "", int Profondeur = 0);
record Structure(int Octets, bool Texte, bool Csv, int BlocsMd, bool Json, bool JsonObj);
static class Perception
{
public static readonly UTF8Encoding Utf8 = new UTF8Encoding(false, true);
public static readonly Regex EntetesMarkdown = new Regex("^##? ", RegexOptions.Multiline | RegexOptions.CultureInvariant);
private static readonly JsonSerializerOptions JsonIndente = new JsonSerializerOptions
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
// Le format Python utilise deux espaces d'indentation et des fins de ligne LF.
// Normaliser les fins de ligne du sérialiseur pour le corpus et le recollage JSON.
public static string SerialiserJson<T>(T valeur) =>
JsonSerializer.Serialize(valeur, JsonIndente).Replace("\r\n", "\n", StringComparison.Ordinal);
// Comme splitlines() suivi du filtre des lignes vides dans le Python.
public static string[] LignesNonVides(string texte) =>
Regex.Split(texte, @"\r\n|[\n\r\v\f\x1C-\x1E\u0085\u2028\u2029]")
.Where(ligne => ligne.Length != 0).ToArray();
// La structure est déduite du contenu : un nom de fichier ne suffit pas.
public static Structure StructureInterne(Segment seg)
{
int octets = seg.Data.Length;
string texte;
try
{
texte = Utf8.GetString(seg.Data);
}
catch (DecoderFallbackException)
{
return new Structure(octets, false, false, 0, false, false);
}
string debut = texte.TrimStart();
if (debut.Length > 0 && (debut[0] == '{' || debut[0] == '['))
{
try
{
using var document = JsonDocument.Parse(texte);
bool objet = document.RootElement.ValueKind == JsonValueKind.Object;
return new Structure(octets, true, false, 0, true, objet);
}
catch (JsonException)
{
// Le préfixe ne suffit pas : essayer les autres formes textuelles.
}
}
var lignes = LignesNonVides(texte);
int virgules = lignes.Length == 0 ? 0 : lignes[0].Count(c => c == ',');
bool csv = virgules > 0 && lignes.All(ligne => ligne.Count(c => c == ',') == virgules);
return new Structure(octets, true, csv, EntetesMarkdown.Matches(texte).Count, false, false);
}
// Distinguer l'objet JSON découpable par clés du tableau JSON compressé tel quel.
public static string Signature(Structure s)
{
if (s.Json) return s.JsonObj ? "json_obj" : "json";
if (s.Csv) return "csv";
if (s.BlocsMd > 0) return "markdown";
return s.Texte ? "texte" : "binaire";
}
public static Dictionary<string, Segment> CorpusDemo()
{
var ventes = Utf8.GetBytes("nom,quantite,prix\ncafe,10,2.50\nthe,20,1.80\nsucre,5,0.90\n" +
"lait,8,1.10\npain,12,0.80\n");
var clients = Utf8.GetBytes(SerialiserJson(new
{
id = 7,
panier = new[] { new { sku = "cafe", q = 10 }, new { sku = "the", q = 20 } }
}) + "\n");
var notes = Utf8.GetBytes("# Rapport\n\n## Chiffre\n12 kEUR, en hausse.\n\n" +
"## Risque\nFournisseur unique, lead time 6 semaines.\n");
var journal = Utf8.GetBytes(string.Concat(Enumerable.Range(0, 40).Select(i =>
FormattableString.Invariant($"10:{i:00}:00 INFO requete {i} ok\n"))));
var binaire = Enumerable.Range(0, 1024).Select(i => (byte)(i % 256)).ToArray();
return new Dictionary<string, Segment>(StringComparer.Ordinal)
{
["ventes.csv#0"] = new Segment("ventes.csv#0", ventes, "donnees/csv"),
["clients.json#0"] = new Segment("clients.json#0", clients, "donnees/json"),
["notes.md#0"] = new Segment("notes.md#0", notes, "texte/markdown"),
["journal.log#0"] = new Segment("journal.log#0", journal, "texte/log"),
["brut.bin#0"] = new Segment("brut.bin#0", binaire, "binaire")
};
}
}
// Sortie Python citée, cellule 4 : une référence par ligne, dans l'ordre affiché.
var referencePerception = new (string Id, int Octets, string Forme, bool Json, bool Csv, int BlocsMd, bool Texte)[]
{
("ventes.csv#0", 81, "csv", false, true, 0, true),
("clients.json#0", 127, "json_obj", true, false, 0, true),
("notes.md#0", 95, "markdown", false, false, 3, true),
("journal.log#0", 1110, "texte", false, false, 0, true),
("brut.bin#0", 1024, "binaire", false, false, 0, false)
};
// Démonstration de la perception : pour chaque segment du corpus, on lit sa forme
// interne déduite du contenu (StructureInterne) puis sa classe de forme
// (Signature) — sans aucune étiquette, seulement à partir des octets.
var segments = Perception.CorpusDemo();
var lignesPercues = segments.Select(entree =>
{
var structure = Perception.StructureInterne(entree.Value);
return (Id: entree.Value.Id, structure.Octets, Forme: Perception.Signature(structure),
structure.Json, structure.Csv, structure.BlocsMd, structure.Texte);
}).ToArray();
int formesDistinctes = lignesPercues.Select(ligne => ligne.Forme).Distinct(StringComparer.Ordinal).Count();
foreach (var ligne in lignesPercues)
Ecrire($" {ligne.Id,-16} {ligne.Octets,5} o forme={ligne.Forme,-9} json={ligne.Json} csv={ligne.Csv} blocs_md={ligne.BlocsMd} texte={ligne.Texte}");
Ecrire($"\ncorpus percu : {segments.Count} segments heterogenes, {formesDistinctes} formes distinctes");
Egal("Perception", "nombre de segments", segments.Count, 5);
Egal("Perception", "nombre de formes distinctes", formesDistinctes, 5);
for (int i = 0; i < referencePerception.Length; i++)
{
var mesure = lignesPercues[i];
var attendu = referencePerception[i];
Egal("Perception", $"{attendu.Id} : identifiant, octets, forme et indicateurs", mesure, attendu);
}