Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

refactor: deduplicate citation formatter logic (#1969)

LearningCircuit752a2b68fd63
diff --git a/src/local_deep_research/text_optimization/citation_formatter.py b/src/local_deep_research/text_optimization/citation_formatter.py
index c5f5d25178..1ad86cecf9 100644
--- a/src/local_deep_research/text_optimization/citation_formatter.py
+++ b/src/local_deep_research/text_optimization/citation_formatter.py
@@ -5,6 +5,29 @@ from enum import Enum
from typing import Dict, Tuple
from urllib.parse import urlparse
+_SOURCES_SECTION_PATTERNS = [
+ re.compile(
+ r"^#{1,3}\s*(?:Sources|References|Bibliography|Citations)",
+ re.MULTILINE | re.IGNORECASE,
+ ),
+ re.compile(
+ r"^(?:Sources|References|Bibliography|Citations):?\s*$",
+ re.MULTILINE | re.IGNORECASE,
+ ),
+]
+
+
+def find_sources_section(content: str) -> int:
+ """Find the start position of the sources/references section in *content*.
+
+ Returns -1 if no section is found.
+ """
+ for pattern in _SOURCES_SECTION_PATTERNS:
+ match = pattern.search(content)
+ if match:
+ return match.start()
+ return -1
+
class CitationMode(Enum):
"""Available citation formatting modes."""
@@ -75,6 +98,27 @@ class CitationFormatter:
return formatter
+ def _replace_comma_citations(self, content, lookup, format_one):
+ """Replace comma-separated citations like [1, 2, 3] using *lookup* and *format_one*.
+
+ Args:
+ content: Text to process
+ lookup: Dict mapping citation number (str) to data
+ format_one: ``(num, data) -> str`` callback that formats a single citation
+ """
+
+ def _replacer(match):
+ nums = [n.strip() for n in match.group(1).split(",")]
+ parts = []
+ for num in nums:
+ if num in lookup:
+ parts.append(format_one(num, lookup[num]))
+ else:
+ parts.append(f"[{num}]")
+ return "".join(parts)
+
+ return self.comma_citation_pattern.sub(_replacer, content)
+
def format_document(self, content: str) -> str:
"""
Format citations in the document according to the selected mode.
@@ -124,17 +168,7 @@ class CitationFormatter:
def _find_sources_section(self, content: str) -> int:
"""Find the start of the sources/references section."""
- patterns = [
- r"^#{1,3}\s*(?:Sources|References|Bibliography|Citations)",
- r"^(?:Sources|References|Bibliography|Citations):?\s*$",
- ]
-
- for pattern in patterns:
- match = re.search(pattern, content, re.MULTILINE | re.IGNORECASE)
- if match:
- return match.start()
-
- return -1
+ return find_sources_section(content)
def _parse_sources(
self, sources_content: str
@@ -169,27 +203,6 @@ class CitationFormatter:
self, content: str, sources: Dict[str, Tuple[str, str]]
) -> str:
"""Replace [1] with hyperlinked version where only the number is linked."""
-
- # First handle comma-separated citations like [1, 2, 3]
- def replace_comma_citations(match):
- citation_nums = match.group(1)
- # Split by comma and strip whitespace
- nums = [num.strip() for num in citation_nums.split(",")]
- formatted_citations = []
-
- for num in nums:
- if num in sources and sources[num][1]:
- url = sources[num][1]
- formatted_citations.append(f"[[{num}]]({url})")
- else:
- formatted_citations.append(f"[{num}]")
-
- return "".join(formatted_citations)
-
- content = self.comma_citation_pattern.sub(
- replace_comma_citations, content
- )
-
# Filter sources that have URLs
url_sources = {
num: (title, url) for num, (title, url) in sources.items() if url
@@ -200,6 +213,11 @@ class CitationFormatter:
_, url = data
return f"[[{citation_num}]]({url})"
+ # Handle comma-separated citations like [1, 2, 3]
+ content = self._replace_comma_citations(
+ content, url_sources, format_number_link
+ )
+
formatter = self._create_citation_formatter(
url_sources, format_number_link
)
@@ -224,27 +242,6 @@ class CitationFormatter:
) -> str:
"""Replace [1] with [domain.com] hyperlinked version."""
- # First handle comma-separated citations like [1, 2, 3]
- def replace_comma_citations(match):
- citation_nums = match.group(1)
- # Split by comma and strip whitespace
- nums = [num.strip() for num in citation_nums.split(",")]
- formatted_citations = []
-
- for num in nums:
- if num in sources and sources[num][1]:
- url = sources[num][1]
- domain = self._extract_domain(url)
- formatted_citations.append(f"[[{domain}]]({url})")
- else:
- formatted_citations.append(f"[{num}]")
-
- return "".join(formatted_citations)
-
- content = self.comma_citation_pattern.sub(
- replace_comma_citations, content
- )
-
# Filter sources that have URLs
url_sources = {
num: (title, url) for num, (title, url) in sources.items() if url
@@ -256,6 +253,11 @@ class CitationFormatter:
domain = self._extract_domain(url)
return f"[[{domain}]]({url})"
+ # Handle comma-separated citations like [1, 2, 3]
+ content = self._replace_comma_citations(
+ content, url_sources, format_domain_link
+ )
+
formatter = self._create_citation_formatter(
url_sources, format_domain_link
)
@@ -304,30 +306,16 @@ class CitationFormatter:
citation_num, url = citations[0]
citation_to_domain_id[citation_num] = (domain, url)
- # First handle comma-separated citations
- def replace_comma_citations(match):
- citation_nums = match.group(1)
- nums = [num.strip() for num in citation_nums.split(",")]
- formatted_citations = []
-
- for num in nums:
- if num in citation_to_domain_id:
- domain_id, url = citation_to_domain_id[num]
- formatted_citations.append(f"[[{domain_id}]]({url})")
- else:
- formatted_citations.append(f"[{num}]")
-
- return "".join(formatted_citations)
-
- content = self.comma_citation_pattern.sub(
- replace_comma_citations, content
- )
-
# Create formatter for citations with domain_id hyperlinks
def format_domain_id_link(citation_num, data):
domain_id, url = data
return f"[[{domain_id}]]({url})"
+ # Handle comma-separated citations
+ content = self._replace_comma_citations(
+ content, citation_to_domain_id, format_domain_id_link
+ )
+
formatter = self._create_citation_formatter(
citation_to_domain_id, format_domain_id_link
)
@@ -368,30 +356,16 @@ class CitationFormatter:
for idx, (citation_num, url) in enumerate(citations, 1):
citation_to_domain_id[citation_num] = (f"{domain}-{idx}", url)
- # First handle comma-separated citations
- def replace_comma_citations(match):
- citation_nums = match.group(1)
- nums = [num.strip() for num in citation_nums.split(",")]
- formatted_citations = []
-
- for num in nums:
- if num in citation_to_domain_id:
- domain_id, url = citation_to_domain_id[num]
- formatted_citations.append(f"[[{domain_id}]]({url})")
- else:
- formatted_citations.append(f"[{num}]")
-
- return "".join(formatted_citations)
-
- content = self.comma_citation_pattern.sub(
- replace_comma_citations, content
- )
-
# Create formatter for citations with domain_id hyperlinks
def format_domain_id_link(citation_num, data):
domain_id, url = data
return f"[[{domain_id}]]({url})"
+ # Handle comma-separated citations
+ content = self._replace_comma_citations(
+ content, citation_to_domain_id, format_domain_id_link
+ )
+
formatter = self._create_citation_formatter(
citation_to_domain_id, format_domain_id_link
)
@@ -595,14 +569,7 @@ class RISExporter:
RIS formatted references
"""
# Find sources section
- sources_start = content.find("## Sources")
- if sources_start == -1:
- sources_start = content.find("## References")
- if sources_start == -1:
- sources_start = content.find("### Sources")
- if sources_start == -1:
- sources_start = content.find("### SOURCES")
-
+ sources_start = find_sources_section(content)
if sources_start == -1:
return ""
@@ -977,10 +944,7 @@ class LaTeXExporter:
def _create_bibliography(self, content: str) -> str:
"""Extract sources and create LaTeX bibliography."""
- sources_start = content.find("## Sources")
- if sources_start == -1:
- sources_start = content.find("## References")
-
+ sources_start = find_sources_section(content)
if sources_start == -1:
return ""
diff --git a/tests/text_optimization/test_citation_formatter.py b/tests/text_optimization/test_citation_formatter.py
index 33e686792a..9753baefb6 100644
--- a/tests/text_optimization/test_citation_formatter.py
+++ b/tests/text_optimization/test_citation_formatter.py
@@ -1222,3 +1222,347 @@ Consecutive lenticular【1】【2】【3】citations.
assert "[@ref1]" in result
assert "[@ref2]" in result
assert "[@ref3]" in result
+
+
+class TestFindSourcesSection:
+ """Test cases for the find_sources_section module-level function."""
+
+ def test_find_h2_sources_header(self):
+ """Test finding ## Sources header."""
+ from local_deep_research.text_optimization.citation_formatter import (
+ find_sources_section,
+ )
+
+ content = """# Report
+
+Some content here.
+
+## Sources
+
+[1] First source
+"""
+ result = find_sources_section(content)
+ assert result == content.index("## Sources")
+
+ def test_find_h2_references_header(self):
+ """Test finding ## References header."""
+ from local_deep_research.text_optimization.citation_formatter import (
+ find_sources_section,
+ )
+
+ content = """# Report
+
+Some content here.
+
+## References
+
+[1] First reference
+"""
+ result = find_sources_section(content)
+ assert result == content.index("## References")
+
+ def test_find_h2_bibliography_header(self):
+ """Test finding ## Bibliography header."""
+ from local_deep_research.text_optimization.citation_formatter import (
+ find_sources_section,
+ )
+
+ content = """# Report
+
+Some content here.
+
+## Bibliography
+
+[1] First entry
+"""
+ result = find_sources_section(content)
+ assert result == content.index("## Bibliography")
+
+ def test_find_h2_citations_header(self):
+ """Test finding ## Citations header."""
+ from local_deep_research.text_optimization.citation_formatter import (
+ find_sources_section,
+ )
+
+ content = """# Report
+
+Some content here.
+
+## Citations
+
+[1] First citation
+"""
+ result = find_sources_section(content)
+ assert result == content.index("## Citations")
+
+ def test_find_h3_sources_header(self):
+ """Test finding ### Sources header."""
+ from local_deep_research.text_optimization.citation_formatter import (
+ find_sources_section,
+ )
+
+ content = """# Report
+
+## Section
+
+### Sources
+
+[1] First source
+"""
+ result = find_sources_section(content)
+ assert result == content.index("### Sources")
+
+ def test_find_h1_sources_header(self):
+ """Test finding # Sources header."""
+ from local_deep_research.text_optimization.citation_formatter import (
+ find_sources_section,
+ )
+
+ content = """# Report
+
+Some content.
+
+# Sources
+
+[1] First source
+"""
+ result = find_sources_section(content)
+ assert result == content.index("# Sources")
+
+ def test_case_insensitivity(self):
+ """Test that header detection is case insensitive."""
+ from local_deep_research.text_optimization.citation_formatter import (
+ find_sources_section,
+ )
+
+ content_lower = """## sources
+
+[1] First
+"""
+ content_upper = """## SOURCES
+
+[1] First
+"""
+ content_mixed = """## SoUrCeS
+
+[1] First
+"""
+ assert find_sources_section(content_lower) == 0
+ assert find_sources_section(content_upper) == 0
+ assert find_sources_section(content_mixed) == 0
+
+ def test_no_sources_section_returns_negative_one(self):
+ """Test that -1 is returned when no sources section exists."""
+ from local_deep_research.text_optimization.citation_formatter import (
+ find_sources_section,
+ )
+
+ content = """# Report
+
+Some content with [1] citation but no sources section.
+
+## Conclusion
+
+The end.
+"""
+ result = find_sources_section(content)
+ assert result == -1
+
+ def test_empty_content_returns_negative_one(self):
+ """Test that empty content returns -1."""
+ from local_deep_research.text_optimization.citation_formatter import (
+ find_sources_section,
+ )
+
+ assert find_sources_section("") == -1
+
+ def test_plain_sources_colon_format(self):
+ """Test finding 'Sources:' format without markdown headers."""
+ from local_deep_research.text_optimization.citation_formatter import (
+ find_sources_section,
+ )
+
+ content = """Report content.
+
+Sources:
+[1] First source
+"""
+ result = find_sources_section(content)
+ assert result == content.index("Sources:")
+
+ def test_references_without_colon(self):
+ """Test finding 'References' without colon."""
+ from local_deep_research.text_optimization.citation_formatter import (
+ find_sources_section,
+ )
+
+ content = """Report content.
+
+References
+[1] First reference
+"""
+ result = find_sources_section(content)
+ assert result == content.index("References")
+
+
+class TestReplaceCommaCitations:
+ """Test cases for the _replace_comma_citations method."""
+
+ def test_basic_comma_separated_citations(self):
+ """Test replacement of basic comma-separated citations."""
+ formatter = CitationFormatter(CitationMode.NUMBER_HYPERLINKS)
+
+ content = "See citations [1, 2, 3] for more info."
+ lookup = {
+ "1": ("Title 1", "https://example.com/1"),
+ "2": ("Title 2", "https://example.com/2"),
+ "3": ("Title 3", "https://example.com/3"),
+ }
+
+ def format_one(num, data):
+ _, url = data
+ return f"[[{num}]]({url})"
+
+ result = formatter._replace_comma_citations(content, lookup, format_one)
+ assert "[[1]](https://example.com/1)" in result
+ assert "[[2]](https://example.com/2)" in result
+ assert "[[3]](https://example.com/3)" in result
+ assert "[1, 2, 3]" not in result
+
+ def test_missing_citation_in_lookup(self):
+ """Test that missing citations fall back to plain format."""
+ formatter = CitationFormatter(CitationMode.NUMBER_HYPERLINKS)
+
+ content = "See citations [1, 2, 3] for more info."
+ lookup = {
+ "1": ("Title 1", "https://example.com/1"),
+ # "2" is missing
+ "3": ("Title 3", "https://example.com/3"),
+ }
+
+ def format_one(num, data):
+ _, url = data
+ return f"[[{num}]]({url})"
+
+ result = formatter._replace_comma_citations(content, lookup, format_one)
+ assert "[[1]](https://example.com/1)" in result
+ assert "[2]" in result # Falls back to plain format
+ assert "[[3]](https://example.com/3)" in result
+
+ def test_no_spaces_after_commas(self):
+ """Test citations without spaces after commas."""
+ formatter = CitationFormatter(CitationMode.NUMBER_HYPERLINKS)
+
+ content = "See citations [1,2,3] for more info."
+ lookup = {
+ "1": ("Title 1", "https://example.com/1"),
+ "2": ("Title 2", "https://example.com/2"),
+ "3": ("Title 3", "https://example.com/3"),
+ }
+
+ def format_one(num, data):
+ _, url = data
+ return f"[[{num}]]({url})"
+
+ result = formatter._replace_comma_citations(content, lookup, format_one)
+ assert "[[1]](https://example.com/1)" in result
+ assert "[[2]](https://example.com/2)" in result
+ assert "[[3]](https://example.com/3)" in result
+
+ def test_two_citations_only(self):
+ """Test with only two comma-separated citations."""
+ formatter = CitationFormatter(CitationMode.NUMBER_HYPERLINKS)
+
+ content = "See [1, 2] for details."
+ lookup = {
+ "1": ("Title 1", "https://example.com/1"),
+ "2": ("Title 2", "https://example.com/2"),
+ }
+
+ def format_one(num, data):
+ _, url = data
+ return f"[[{num}]]({url})"
+
+ result = formatter._replace_comma_citations(content, lookup, format_one)
+ assert (
+ "[[1]](https://example.com/1)[[2]](https://example.com/2)" in result
+ )
+
+ def test_domain_format_callback(self):
+ """Test with domain-style formatting callback."""
+ formatter = CitationFormatter(CitationMode.DOMAIN_HYPERLINKS)
+
+ content = "See citations [1, 2] for more info."
+ lookup = {
+ "1": ("arxiv.org", "https://arxiv.org/abs/123"),
+ "2": ("github.com", "https://github.com/repo"),
+ }
+
+ def format_one(num, data):
+ domain, url = data
+ return f"[[{domain}]]({url})"
+
+ result = formatter._replace_comma_citations(content, lookup, format_one)
+ assert "[[arxiv.org]](https://arxiv.org/abs/123)" in result
+ assert "[[github.com]](https://github.com/repo)" in result
+
+ def test_multiple_comma_groups_in_content(self):
+ """Test multiple comma-separated citation groups in content."""
+ formatter = CitationFormatter(CitationMode.NUMBER_HYPERLINKS)
+
+ content = "First group [1, 2] and second group [3, 4]."
+ lookup = {
+ "1": ("T1", "https://example.com/1"),
+ "2": ("T2", "https://example.com/2"),
+ "3": ("T3", "https://example.com/3"),
+ "4": ("T4", "https://example.com/4"),
+ }
+
+ def format_one(num, data):
+ _, url = data
+ return f"[[{num}]]({url})"
+
+ result = formatter._replace_comma_citations(content, lookup, format_one)
+ assert (
+ "[[1]](https://example.com/1)[[2]](https://example.com/2)" in result
+ )
+ assert (
+ "[[3]](https://example.com/3)[[4]](https://example.com/4)" in result
+ )
+
+ def test_unicode_lenticular_brackets(self):
+ """Test comma-separated citations with Unicode lenticular brackets."""
+ formatter = CitationFormatter(CitationMode.NUMBER_HYPERLINKS)
+
+ content = "See citations【1, 2, 3】for more info."
+ lookup = {
+ "1": ("Title 1", "https://example.com/1"),
+ "2": ("Title 2", "https://example.com/2"),
+ "3": ("Title 3", "https://example.com/3"),
+ }
+
+ def format_one(num, data):
+ _, url = data
+ return f"[[{num}]]({url})"
+
+ result = formatter._replace_comma_citations(content, lookup, format_one)
+ assert "[[1]](https://example.com/1)" in result
+ assert "[[2]](https://example.com/2)" in result
+ assert "[[3]](https://example.com/3)" in result
+
+ def test_empty_lookup_preserves_original(self):
+ """Test that empty lookup preserves original citation numbers."""
+ formatter = CitationFormatter(CitationMode.NUMBER_HYPERLINKS)
+
+ content = "See citations [1, 2, 3] for more info."
+ lookup = {}
+
+ def format_one(num, data):
+ _, url = data
+ return f"[[{num}]]({url})"
+
+ result = formatter._replace_comma_citations(content, lookup, format_one)
+ # All citations should fall back to plain format
+ assert "[1]" in result
+ assert "[2]" in result
+ assert "[3]" in result