AniseF commited on
Commit
2fb8b3f
·
verified ·
1 Parent(s): eaae64d

Create formatting.py

Browse files
Files changed (1) hide show
  1. ddpg/formatting.py +69 -0
ddpg/formatting.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ddgp/formatting.py
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Funções de formatação de texto para o Dicionário.
5
+ """
6
+ import re
7
+ import os
8
+ import json
9
+
10
+ BASE_DIR = os.path.dirname(__file__)
11
+ DDGP_DATA_DIR = os.path.join(BASE_DIR, "data")
12
+
13
+ # --- Carregamento de Abreviaturas ---
14
+ try:
15
+ with open(os.path.join(DDGP_DATA_DIR, "abrev.json"), "r", encoding="utf-8") as f:
16
+ ABREV = json.load(f)
17
+ except FileNotFoundError:
18
+ print("ATENÇÃO: Arquivo abrev.json não encontrado. A formatação de abreviaturas será desativada.")
19
+ ABREV = {}
20
+
21
+ # --- Lógica de Abreviaturas ---
22
+ def _escape_for_regex(s: str) -> str:
23
+ return re.escape(s)
24
+
25
+ _abbrev_list_sorted = sorted(list(ABREV.keys()), key=lambda x: -len(x))
26
+ _abbrev_patterns = [r"(?<!\w)" + _escape_for_regex(a) + r"(?!\w)" for a in _abbrev_list_sorted]
27
+ ABREV_REGEX = re.compile(r"(" + r"|".join(_abbrev_patterns) + r")") if _abbrev_patterns else None
28
+
29
+ def format_abrevs(texto: str) -> str:
30
+ """Substitui abreviaturas por spans com classes e tooltip."""
31
+ if not texto or not ABREV_REGEX:
32
+ return texto
33
+
34
+ def _repl(m):
35
+ ab = m.group(0)
36
+ info = ABREV.get(ab, {}) if ABREV else {}
37
+ desc = info.get("descricao", "") if isinstance(info, dict) else ""
38
+ tipo = info.get("tipo", "") if isinstance(info, dict) else ""
39
+
40
+ # Lógica de classificação
41
+ cls = "abrev"
42
+ if ("Autor" in tipo or "Obras" in tipo or "Nome" in tipo or "Cultural" in tipo):
43
+ cls = "autor-sc"
44
+
45
+ title = desc.replace('"', '&quot;')
46
+ return f'<span class="{cls}" title="{title}">{ab}</span>'
47
+
48
+ return ABREV_REGEX.sub(_repl, texto)
49
+
50
+ # --- Formatação de Parágrafos de Descrição ---
51
+ def format_pdesc(pdesc: str) -> str:
52
+ """Formata texto de descrição, tratando quebras de linha e aplicando formatação de abreviaturas."""
53
+ if not pdesc:
54
+ return ""
55
+
56
+ # Normalize line endings
57
+ p = pdesc.replace('\r\n', '\n').replace('\r', '\n')
58
+
59
+ # 1. Substitui '♦ ' por <br> e span com classe ddgp-sec (para quebra de linha após o diamante)
60
+ # Garante que '♦ label' fique na mesma linha usando um espaço após o <br>
61
+ p = re.sub(r'♦\s+', '<br><span class="ddgp-sec">♦</span> ', p)
62
+
63
+ # 2. Aplica formatação de abreviaturas
64
+ p = format_abrevs(p)
65
+
66
+ # 3. Preserva newlines simples como <br/>
67
+ p = p.replace('\n', '<br/>')
68
+
69
+ return p