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.

feat: Add RIS export and enhanced citation formatting (closes #219, #220, addresses #547)

LearningCircuit5c26e9bd4a27
diff --git a/.github/workflows/text-optimization-tests.yml b/.github/workflows/text-optimization-tests.yml
new file mode 100644
index 0000000000..a351e31176
--- /dev/null
+++ b/.github/workflows/text-optimization-tests.yml
@@ -0,0 +1,50 @@
+name: Text Optimization Tests
+
+on:
+ push:
+ paths:
+ - 'src/local_deep_research/text_optimization/**'
+ - 'tests/text_optimization/**'
+ - '.github/workflows/text-optimization-tests.yml'
+ pull_request:
+ types: [opened, synchronize, reopened]
+ paths:
+ - 'src/local_deep_research/text_optimization/**'
+ - 'tests/text_optimization/**'
+ workflow_dispatch:
+
+jobs:
+ test-text-optimization:
+ runs-on: ubuntu-latest
+ name: Text Optimization Module Tests
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: '3.11'
+
+ - name: Set up PDM
+ uses: pdm-project/setup-pdm@v4
+
+ - name: Install dependencies
+ run: |
+ pdm install
+ pdm install -d
+
+ - name: Run text optimization tests
+ run: |
+ pdm run pytest tests/text_optimization/ -v --tb=short
+
+ - name: Run coverage report
+ run: |
+ pdm run pytest tests/text_optimization/ --cov=src/local_deep_research/text_optimization --cov-report=xml --cov-report=term
+
+ - name: Upload coverage reports
+ uses: codecov/codecov-action@v3
+ with:
+ file: ./coverage.xml
+ flags: text-optimization
+ name: text-optimization-coverage
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index a80382baa3..be0bbaf685 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -458,6 +458,44 @@
"value": 2,
"visible": true
},
+ "report.citation_format": {
+ "category": "report_parameters",
+ "description": "Citation format style for reports",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Citation Format",
+ "options": [
+ {"value": "number_hyperlinks", "label": "Numbers with hyperlinks [1]"},
+ {"value": "domain_hyperlinks", "label": "Domain names with hyperlinks [arxiv.org]"},
+ {"value": "domain_id_hyperlinks", "label": "Domain with smart numbering [arxiv.org] or [arxiv.org-1]"},
+ {"value": "domain_id_always_hyperlinks", "label": "Domain with consistent numbering [arxiv.org-1]"},
+ {"value": "no_hyperlinks", "label": "Numbers without hyperlinks [1]"}
+ ],
+ "step": null,
+ "type": "REPORT",
+ "ui_element": "select",
+ "value": "domain_id_hyperlinks",
+ "visible": true
+ },
+ "report.export_formats": {
+ "category": "report_parameters",
+ "description": "Available export formats for reports",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Export Formats",
+ "options": [
+ {"value": "markdown", "label": "Markdown (.md)"},
+ {"value": "latex", "label": "LaTeX (.tex)"},
+ {"value": "quarto", "label": "Quarto (.qmd)"}
+ ],
+ "step": null,
+ "type": "REPORT",
+ "ui_element": "multiselect",
+ "value": ["markdown", "latex", "quarto", "ris"],
+ "visible": true
+ },
"search.iterations": {
"category": null,
"description": "Setting for search.iterations",
@@ -469,7 +507,7 @@
"step": null,
"type": "SEARCH",
"ui_element": "number",
- "value": 2,
+ "value": 1,
"visible": true
},
"search.max_filtered_results": {
@@ -539,7 +577,7 @@
"step": null,
"type": "SEARCH",
"ui_element": "number",
- "value": 2,
+ "value": 3,
"visible": true
},
"search.region": {
diff --git a/src/local_deep_research/text_optimization/README.md b/src/local_deep_research/text_optimization/README.md
new file mode 100644
index 0000000000..ec8d3aa41f
--- /dev/null
+++ b/src/local_deep_research/text_optimization/README.md
@@ -0,0 +1,86 @@
+# Text Optimization Module
+
+This module provides post-processing optimizations for research reports, with a focus on citation formatting and export capabilities.
+
+## Features
+
+### Citation Formatting
+
+The `CitationFormatter` class provides three modes for formatting citations:
+
+1. **Number Hyperlinks** (default): Converts `[1]` to `[[1]](url)` - clickable citation numbers
+2. **Domain Hyperlinks**: Converts `[1]` to `[[arxiv.org]](url)` - shows the source domain
+3. **No Hyperlinks**: Leaves citations as plain `[1]` without links
+
+Supports multiple citation formats:
+- Individual citations: `[1]`
+- Consecutive citations: `[1][2][3]`
+- Comma-separated citations: `[1, 2, 3]`
+
+### Export Formats
+
+#### LaTeX Export
+
+The `LaTeXExporter` class converts markdown reports to LaTeX format, including:
+- Proper heading conversion (`#` → `\section{}`)
+- Citation formatting (`[1]` → `\cite{ref1}`)
+- Bibliography generation
+- Basic formatting (bold, italic, code)
+
+#### Quarto Export
+
+The `QuartoExporter` class converts markdown reports to Quarto (.qmd) format:
+- YAML front matter with metadata
+- Citation conversion to Quarto format (`[1]` → `[@ref1]`)
+- BibTeX bibliography generation
+- Support for both HTML and PDF output formats
+- Automatic title extraction from markdown
+
+## Usage
+
+### In Research Service
+
+The module is integrated into the research service and automatically formats citations based on user settings:
+
+```python
+from local_deep_research.text_optimization import CitationFormatter, CitationMode
+
+# Get formatter with user settings
+formatter = get_citation_formatter()
+formatted_content = formatter.format_document(markdown_content)
+```
+
+### Settings
+
+Citation format can be configured via the settings UI or environment variable:
+- Setting key: `report.citation_format`
+- Environment variable: `LDR_REPORT_CITATION_FORMAT`
+- Options: `number_hyperlinks`, `domain_hyperlinks`, `no_hyperlinks`
+
+Export formats can be configured to automatically export reports in multiple formats:
+- Setting key: `report.export_formats`
+- Environment variable: `LDR_REPORT_EXPORT_FORMATS`
+- Options: `markdown`, `latex`, `quarto` (can select multiple)
+
+### Export Examples
+
+```python
+from local_deep_research.web.services.research_service import export_report_to_format, export_report_to_latex
+
+# Export to LaTeX
+latex_path = export_report_to_latex(report_path)
+
+# Export to Quarto
+quarto_path = export_report_to_format(report_path, "quarto")
+
+# Export to Quarto with custom title
+quarto_path = export_report_to_format(report_path, "quarto", "My Research Title")
+```
+
+## Testing
+
+Run the test script to see examples of all formatting modes:
+
+```bash
+python test_citation_formatter.py
+```
diff --git a/src/local_deep_research/text_optimization/__init__.py b/src/local_deep_research/text_optimization/__init__.py
new file mode 100644
index 0000000000..889cfa6359
--- /dev/null
+++ b/src/local_deep_research/text_optimization/__init__.py
@@ -0,0 +1,17 @@
+"""Text optimization module for enhancing research output formatting."""
+
+from .citation_formatter import (
+ CitationFormatter,
+ CitationMode,
+ LaTeXExporter,
+ QuartoExporter,
+ RISExporter,
+)
+
+__all__ = [
+ "CitationFormatter",
+ "CitationMode",
+ "LaTeXExporter",
+ "QuartoExporter",
+ "RISExporter",
+]
diff --git a/src/local_deep_research/text_optimization/citation_formatter.py b/src/local_deep_research/text_optimization/citation_formatter.py
new file mode 100644
index 0000000000..c6d7db97fc
--- /dev/null
+++ b/src/local_deep_research/text_optimization/citation_formatter.py
@@ -0,0 +1,722 @@
+"""Citation formatter for adding hyperlinks and alternative citation styles."""
+
+import re
+from enum import Enum
+from typing import Dict, Tuple
+from urllib.parse import urlparse
+
+
+class CitationMode(Enum):
+ """Available citation formatting modes."""
+
+ NUMBER_HYPERLINKS = "number_hyperlinks" # [1] with hyperlinks
+ DOMAIN_HYPERLINKS = "domain_hyperlinks" # [arxiv.org] with hyperlinks
+ DOMAIN_ID_HYPERLINKS = (
+ "domain_id_hyperlinks" # [arxiv.org] or [arxiv.org-1] with smart IDs
+ )
+ DOMAIN_ID_ALWAYS_HYPERLINKS = (
+ "domain_id_always_hyperlinks" # [arxiv.org-1] always with IDs
+ )
+ NO_HYPERLINKS = "no_hyperlinks" # [1] without hyperlinks
+
+
+class CitationFormatter:
+ """Formats citations in markdown documents with various styles."""
+
+ def __init__(self, mode: CitationMode = CitationMode.NUMBER_HYPERLINKS):
+ self.mode = mode
+ # Use negative lookbehind and lookahead to avoid matching already formatted citations
+ self.citation_pattern = re.compile(r"(?<!\[)\[(\d+)\](?!\])")
+ self.comma_citation_pattern = re.compile(r"\[(\d+(?:,\s*\d+)+)\]")
+ self.sources_pattern = re.compile(
+ r"^\[(\d+)\]\s*(.+?)(?:\n\s*URL:\s*(.+?))?$", re.MULTILINE
+ )
+
+ def format_document(self, content: str) -> str:
+ """
+ Format citations in the document according to the selected mode.
+
+ Args:
+ content: The markdown content to format
+
+ Returns:
+ Formatted markdown content
+ """
+ if self.mode == CitationMode.NO_HYPERLINKS:
+ return content
+
+ # Extract sources section
+ sources_start = self._find_sources_section(content)
+ if sources_start == -1:
+ return content
+
+ document_content = content[:sources_start]
+ sources_content = content[sources_start:]
+
+ # Parse sources
+ sources = self._parse_sources(sources_content)
+
+ # Format citations in document
+ if self.mode == CitationMode.NUMBER_HYPERLINKS:
+ formatted_content = self._format_number_hyperlinks(
+ document_content, sources
+ )
+ elif self.mode == CitationMode.DOMAIN_HYPERLINKS:
+ formatted_content = self._format_domain_hyperlinks(
+ document_content, sources
+ )
+ elif self.mode == CitationMode.DOMAIN_ID_HYPERLINKS:
+ formatted_content = self._format_domain_id_hyperlinks(
+ document_content, sources
+ )
+ elif self.mode == CitationMode.DOMAIN_ID_ALWAYS_HYPERLINKS:
+ formatted_content = self._format_domain_id_always_hyperlinks(
+ document_content, sources
+ )
+ else:
+ formatted_content = document_content
+
+ # Rebuild document
+ return formatted_content + sources_content
+
+ 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
+
+ def _parse_sources(
+ self, sources_content: str
+ ) -> Dict[str, Tuple[str, str]]:
+ """
+ Parse sources section to extract citation numbers, titles, and URLs.
+
+ Returns:
+ Dictionary mapping citation number to (title, url) tuple
+ """
+ sources = {}
+ matches = list(self.sources_pattern.finditer(sources_content))
+
+ for match in matches:
+ citation_num = match.group(1)
+ title = match.group(2).strip()
+ url = match.group(3).strip() if match.group(3) else ""
+ sources[citation_num] = (title, url)
+
+ return sources
+
+ def _format_number_hyperlinks(
+ 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
+ )
+
+ # Then handle individual citations
+ def replace_citation(match):
+ citation_num = match.group(1)
+ if citation_num in sources and sources[citation_num][1]:
+ url = sources[citation_num][1]
+ return f"[[{citation_num}]]({url})"
+ return match.group(0)
+
+ return self.citation_pattern.sub(replace_citation, content)
+
+ def _format_domain_hyperlinks(
+ self, content: str, sources: Dict[str, Tuple[str, str]]
+ ) -> 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
+ )
+
+ # Then handle individual citations
+ def replace_citation(match):
+ citation_num = match.group(1)
+ if citation_num in sources and sources[citation_num][1]:
+ url = sources[citation_num][1]
+ domain = self._extract_domain(url)
+ return f"[[{domain}]]({url})"
+ return match.group(0)
+
+ return self.citation_pattern.sub(replace_citation, content)
+
+ def _format_domain_id_hyperlinks(
+ self, content: str, sources: Dict[str, Tuple[str, str]]
+ ) -> str:
+ """Replace [1] with [domain.com-1] hyperlinked version with hyphen-separated IDs."""
+ # First, create a mapping of domains to their citation numbers
+ domain_citations = {}
+
+ for citation_num, (title, url) in sources.items():
+ if url:
+ domain = self._extract_domain(url)
+ if domain not in domain_citations:
+ domain_citations[domain] = []
+ domain_citations[domain].append((citation_num, url))
+
+ # Create a mapping from citation number to domain with ID
+ citation_to_domain_id = {}
+ for domain, citations in domain_citations.items():
+ if len(citations) > 1:
+ # Multiple citations from same domain - add hyphen and number
+ for idx, (citation_num, url) in enumerate(citations, 1):
+ citation_to_domain_id[citation_num] = (
+ f"{domain}-{idx}",
+ url,
+ )
+ else:
+ # Single citation from domain - no ID needed
+ 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
+ )
+
+ # Then handle individual citations
+ def replace_citation(match):
+ citation_num = match.group(1)
+ if citation_num in citation_to_domain_id:
+ domain_id, url = citation_to_domain_id[citation_num]
+ return f"[[{domain_id}]]({url})"
+ return match.group(0)
+
+ return self.citation_pattern.sub(replace_citation, content)
+
+ def _format_domain_id_always_hyperlinks(
+ self, content: str, sources: Dict[str, Tuple[str, str]]
+ ) -> str:
+ """Replace [1] with [domain.com-1] hyperlinked version, always with IDs."""
+ # First, create a mapping of domains to their citation numbers
+ domain_citations = {}
+
+ for citation_num, (title, url) in sources.items():
+ if url:
+ domain = self._extract_domain(url)
+ if domain not in domain_citations:
+ domain_citations[domain] = []
+ domain_citations[domain].append((citation_num, url))
+
+ # Create a mapping from citation number to domain with ID
+ citation_to_domain_id = {}
+ for domain, citations in domain_citations.items():
+ # Always add hyphen and number for consistency
+ 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
+ )
+
+ # Then handle individual citations
+ def replace_citation(match):
+ citation_num = match.group(1)
+ if citation_num in citation_to_domain_id:
+ domain_id, url = citation_to_domain_id[citation_num]
+ return f"[[{domain_id}]]({url})"
+ return match.group(0)
+
+ return self.citation_pattern.sub(replace_citation, content)
+
+ def _to_superscript(self, text: str) -> str:
+ """Convert text to Unicode superscript."""
+ superscript_map = {
+ "0": "⁰",
+ "1": "¹",
+ "2": "²",
+ "3": "³",
+ "4": "⁴",
+ "5": "⁵",
+ "6": "⁶",
+ "7": "⁷",
+ "8": "⁸",
+ "9": "⁹",
+ }
+ return "".join(superscript_map.get(c, c) for c in text)
+
+ def _extract_domain(self, url: str) -> str:
+ """Extract domain name from URL."""
+ try:
+ parsed = urlparse(url)
+ domain = parsed.netloc
+ # Remove www. prefix if present
+ if domain.startswith("www."):
+ domain = domain[4:]
+ # Keep known domains as-is
+ known_domains = {
+ "arxiv.org": "arxiv.org",
+ "github.com": "github.com",
+ "reddit.com": "reddit.com",
+ "youtube.com": "youtube.com",
+ "pypi.org": "pypi.org",
+ "milvus.io": "milvus.io",
+ "medium.com": "medium.com",
+ }
+
+ for known, display in known_domains.items():
+ if known in domain:
+ return display
+
+ # For other domains, extract main domain
+ parts = domain.split(".")
+ if len(parts) >= 2:
+ return ".".join(parts[-2:])
+ return domain
+ except:
+ return "source"
+
+
+class QuartoExporter:
+ """Export markdown documents to Quarto (.qmd) format."""
+
+ def __init__(self):
+ self.citation_pattern = re.compile(r"(?<!\[)\[(\d+)\](?!\])")
+ self.comma_citation_pattern = re.compile(r"\[(\d+(?:,\s*\d+)+)\]")
+
+ def export_to_quarto(self, content: str, title: str = None) -> str:
+ """
+ Convert markdown document to Quarto format.
+
+ Args:
+ content: Markdown content
+ title: Document title (if None, will extract from content)
+
+ Returns:
+ Quarto formatted content
+ """
+ # Extract title from markdown if not provided
+ if not title:
+ title_match = re.search(r"^#\s+(.+)$", content, re.MULTILINE)
+ title = title_match.group(1) if title_match else "Research Report"
+
+ # Create Quarto YAML header
+ yaml_header = f"""---
+title: "{title}"
+author: "Local Deep Research"
+date: today
+format:
+ html:
+ toc: true
+ toc-depth: 3
+ number-sections: true
+ pdf:
+ toc: true
+ number-sections: true
+ colorlinks: true
+bibliography: references.bib
+csl: apa.csl
+---
+
+"""
+
+ # Process content
+ processed_content = content
+
+ # 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(",")]
+ refs = [f"@ref{num}" for num in nums]
+ return f"[{', '.join(refs)}]"
+
+ processed_content = self.comma_citation_pattern.sub(
+ replace_comma_citations, processed_content
+ )
+
+ # Then convert individual citations to Quarto format [@citation]
+ def replace_citation(match):
+ citation_num = match.group(1)
+ return f"[@ref{citation_num}]"
+
+ processed_content = self.citation_pattern.sub(
+ replace_citation, processed_content
+ )
+
+ # Generate bibliography file content
+ bib_content = self._generate_bibliography(content)
+
+ # Add note about bibliography file
+ bibliography_note = (
+ "\n\n::: {.callout-note}\n## Bibliography File Required\n\nThis document requires a `references.bib` file in the same directory with the following content:\n\n```bibtex\n"
+ + bib_content
+ + "\n```\n:::\n"
+ )
+
+ return yaml_header + processed_content + bibliography_note
+
+ def _generate_bibliography(self, content: str) -> str:
+ """Generate BibTeX bibliography from sources."""
+ sources_pattern = re.compile(
+ r"^\[(\d+)\]\s*(.+?)(?:\n\s*URL:\s*(.+?))?$", re.MULTILINE
+ )
+
+ bibliography = ""
+ matches = list(sources_pattern.finditer(content))
+
+ for match in matches:
+ citation_num = match.group(1)
+ title = match.group(2).strip()
+ url = match.group(3).strip() if match.group(3) else ""
+
+ # Generate BibTeX entry
+ bib_entry = f"@misc{{ref{citation_num},\n"
+ bib_entry += f' title = "{{{title}}}",\n'
+ if url:
+ bib_entry += f" url = {{{url}}},\n"
+ bib_entry += f' howpublished = "\\url{{{url}}}",\n'
+ bib_entry += f" year = {{{2024}}},\n"
+ bib_entry += ' note = "Accessed: \\today"\n'
+ bib_entry += "}\n"
+
+ bibliography += bib_entry + "\n"
+
+ return bibliography.strip()
+
+
+class RISExporter:
+ """Export references to RIS format for reference managers like Zotero."""
+
+ def __init__(self):
+ self.sources_pattern = re.compile(
+ r"^\[(\d+)\]\s*(.+?)(?:\n\s*URL:\s*(.+?))?$", re.MULTILINE
+ )
+
+ def export_to_ris(self, content: str) -> str:
+ """
+ Extract references from markdown and convert to RIS format.
+
+ Args:
+ content: Markdown content with sources
+
+ Returns:
+ 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")
+
+ if sources_start == -1:
+ return ""
+
+ # Find the end of the first sources section (before any other major section)
+ sources_content = content[sources_start:]
+
+ # Look for the next major section to avoid duplicates
+ next_section_markers = [
+ "\n## ALL SOURCES",
+ "\n### ALL SOURCES",
+ "\n## Research Metrics",
+ "\n### Research Metrics",
+ "\n## SEARCH QUESTIONS",
+ "\n### SEARCH QUESTIONS",
+ "\n## DETAILED FINDINGS",
+ "\n### DETAILED FINDINGS",
+ "\n---", # Horizontal rule often separates sections
+ ]
+
+ sources_end = len(sources_content)
+ for marker in next_section_markers:
+ pos = sources_content.find(marker)
+ if pos != -1 and pos < sources_end:
+ sources_end = pos
+
+ sources_content = sources_content[:sources_end]
+
+ # Parse sources and generate RIS entries
+ ris_entries = []
+ seen_refs = set() # Track which references we've already processed
+ matches = list(self.sources_pattern.finditer(sources_content))
+
+ for match in matches:
+ citation_num = match.group(1)
+ title = match.group(2).strip()
+ url = match.group(3).strip() if match.group(3) else ""
+
+ # Create a unique key to avoid duplicates
+ ref_key = (citation_num, title, url)
+ if ref_key not in seen_refs:
+ seen_refs.add(ref_key)
+ # Create RIS entry
+ ris_entry = self._create_ris_entry(citation_num, title, url)
+ ris_entries.append(ris_entry)
+
+ return "\n".join(ris_entries)
+
+ def _create_ris_entry(self, ref_id: str, title: str, url: str = "") -> str:
+ """Create a single RIS entry."""
+ lines = []
+
+ # TY - Type of reference (ELEC for electronic source/website)
+ lines.append("TY - ELEC")
+
+ # ID - Reference ID
+ lines.append(f"ID - ref{ref_id}")
+
+ # TI - Title
+ lines.append(f"TI - {title}")
+
+ # UR - URL
+ if url:
+ lines.append(f"UR - {url}")
+
+ # Try to extract domain as publisher
+ try:
+ from urllib.parse import urlparse
+
+ parsed = urlparse(url)
+ domain = parsed.netloc
+ if domain.startswith("www."):
+ domain = domain[4:]
+ # Extract readable publisher name from domain
+ if "github.com" in domain:
+ lines.append("PB - GitHub")
+ elif "arxiv.org" in domain:
+ lines.append("PB - arXiv")
+ elif "reddit.com" in domain:
+ lines.append("PB - Reddit")
+ elif "youtube.com" in domain or "m.youtube.com" in domain:
+ lines.append("PB - YouTube")
+ elif "medium.com" in domain:
+ lines.append("PB - Medium")
+ elif "pypi.org" in domain:
+ lines.append("PB - Python Package Index (PyPI)")
+ else:
+ # Use domain as publisher
+ lines.append(f"PB - {domain}")
+ except:
+ pass
+
+ # Y1 - Year accessed (current year)
+ from datetime import datetime
+
+ current_year = datetime.now().year
+ lines.append(f"Y1 - {current_year}")
+
+ # DA - Date accessed
+ current_date = datetime.now().strftime("%Y/%m/%d")
+ lines.append(f"DA - {current_date}")
+
+ # LA - Language
+ lines.append("LA - en")
+
+ # ER - End of reference
+ lines.append("ER - ")
+
+ return "\n".join(lines)
+
+
+class LaTeXExporter:
+ """Export markdown documents to LaTeX format."""
+
+ def __init__(self):
+ self.citation_pattern = re.compile(r"\[(\d+)\]")
+ self.heading_patterns = [
+ (re.compile(r"^# (.+)$", re.MULTILINE), r"\\section{\1}"),
+ (re.compile(r"^## (.+)$", re.MULTILINE), r"\\subsection{\1}"),
+ (re.compile(r"^### (.+)$", re.MULTILINE), r"\\subsubsection{\1}"),
+ ]
+ self.emphasis_patterns = [
+ (re.compile(r"\*\*(.+?)\*\*"), r"\\textbf{\1}"),
+ (re.compile(r"\*(.+?)\*"), r"\\textit{\1}"),
+ (re.compile(r"`(.+?)`"), r"\\texttt{\1}"),
+ ]
+
+ def export_to_latex(self, content: str) -> str:
+ """
+ Convert markdown document to LaTeX format.
+
+ Args:
+ content: Markdown content
+
+ Returns:
+ LaTeX formatted content
+ """
+ latex_content = self._create_latex_header()
+
+ # Convert markdown to LaTeX
+ body_content = content
+
+ # Convert headings
+ for pattern, replacement in self.heading_patterns:
+ body_content = pattern.sub(replacement, body_content)
+
+ # Convert emphasis
+ for pattern, replacement in self.emphasis_patterns:
+ body_content = pattern.sub(replacement, body_content)
+
+ # Convert citations to LaTeX \cite{} format
+ body_content = self.citation_pattern.sub(r"\\cite{ref\1}", body_content)
+
+ # Convert lists
+ body_content = self._convert_lists(body_content)
+
+ # Add body content
+ latex_content += body_content
+
+ # Add bibliography section
+ latex_content += self._create_bibliography(content)
+
+ # Add footer
+ latex_content += self._create_latex_footer()
+
+ return latex_content
+
+ def _create_latex_header(self) -> str:
+ """Create LaTeX document header."""
+ return r"""\documentclass[12pt]{article}
+\usepackage[utf8]{inputenc}
+\usepackage{hyperref}
+\usepackage{cite}
+\usepackage{url}
+
+\title{Research Report}
+\date{\today}
+
+\begin{document}
+\maketitle
+
+"""
+
+ def _create_latex_footer(self) -> str:
+ """Create LaTeX document footer."""
+ return "\n\\end{document}\n"
+
+ def _convert_lists(self, content: str) -> str:
+ """Convert markdown lists to LaTeX format."""
+ # Simple conversion for bullet points
+ content = re.sub(r"^- (.+)$", r"\\item \1", content, flags=re.MULTILINE)
+
+ # Add itemize environment around list items
+ lines = content.split("\n")
+ result = []
+ in_list = False
+
+ for line in lines:
+ if line.strip().startswith("\\item"):
+ if not in_list:
+ result.append("\\begin{itemize}")
+ in_list = True
+ result.append(line)
+ else:
+ if in_list and line.strip():
+ result.append("\\end{itemize}")
+ in_list = False
+ result.append(line)
+
+ if in_list:
+ result.append("\\end{itemize}")
+
+ return "\n".join(result)
+
+ 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")
+
+ if sources_start == -1:
+ return ""
+
+ sources_content = content[sources_start:]
+ pattern = re.compile(
+ r"^\[(\d+)\]\s*(.+?)(?:\n\s*URL:\s*(.+?))?$", re.MULTILINE
+ )
+
+ bibliography = "\n\\begin{thebibliography}{99}\n"
+
+ for match in pattern.finditer(sources_content):
+ citation_num = match.group(1)
+ title = match.group(2).strip()
+ url = match.group(3).strip() if match.group(3) else ""
+
+ if url:
+ bibliography += (
+ f"\\bibitem{{ref{citation_num}}} {title}. \\url{{{url}}}\n"
+ )
+ else:
+ bibliography += f"\\bibitem{{ref{citation_num}}} {title}.\n"
+
+ bibliography += "\\end{thebibliography}\n"
+
+ return bibliography
diff --git a/src/local_deep_research/text_optimization/test_citation_formatter.py b/src/local_deep_research/text_optimization/test_citation_formatter.py
new file mode 100644
index 0000000000..d0536ab30a
--- /dev/null
+++ b/src/local_deep_research/text_optimization/test_citation_formatter.py
@@ -0,0 +1,69 @@
+"""Test script to demonstrate citation formatter functionality."""
+
+from citation_formatter import CitationFormatter, CitationMode, LaTeXExporter
+
+
+def test_citation_formatter():
+ """Test the citation formatter with different modes."""
+
+ # Sample markdown content with citations including multiple citations
+ sample_content = """# Research Report
+
+This is a research report about artificial intelligence [1]. Recent advances in
+machine learning [2] have shown significant progress. The work by researchers
+at DeepMind [3] has been particularly influential.
+
+## Key Findings
+
+The analysis reveals several important points:
+- Deep learning models are becoming more efficient [1]
+- Transfer learning enables better generalization [2]
+- Large language models show emergent capabilities [3]
+- Multiple studies confirm these findings [1][2][3]
+- Some research combines different approaches [2][3]
+- Comprehensive surveys cover all aspects [1, 2, 3]
+- Recent work builds on earlier findings [2, 3]
+
+## Sources
+
+[1] Understanding Deep Learning
+ URL: https://arxiv.org/abs/2104.12345
+
+[2] Transfer Learning: A Survey
+ URL: https://www.nature.com/articles/s41586-021-03819-2
+
+[3] Emergent Abilities of Large Language Models
+ URL: https://openai.com/research/emergent-abilities
+"""
+
+ print("Original content:")
+ print("-" * 50)
+ print(sample_content)
+ print("\n" + "=" * 70 + "\n")
+
+ # Test different citation modes
+ modes = [
+ (CitationMode.NUMBER_HYPERLINKS, "Numbers with hyperlinks"),
+ (CitationMode.DOMAIN_HYPERLINKS, "Domain names with hyperlinks"),
+ (CitationMode.NO_HYPERLINKS, "No hyperlinks"),
+ ]
+
+ for mode, description in modes:
+ formatter = CitationFormatter(mode=mode)
+ formatted = formatter.format_document(sample_content)
+
+ print(f"{description}:")
+ print("-" * 50)
+ print(formatted)
+ print("\n" + "=" * 70 + "\n")
+
+ # Test LaTeX export
+ print("LaTeX Export:")
+ print("-" * 50)
+ exporter = LaTeXExporter()
+ latex_content = exporter.export_to_latex(sample_content)
+ print(latex_content)
+
+
+if __name__ == "__main__":
+ test_citation_formatter()
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index 98d148f946..f7e51fbc16 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -11,6 +11,7 @@ from flask import (
redirect,
request,
send_from_directory,
+ send_file,
url_for,
)
from loguru import logger
@@ -22,6 +23,8 @@ from ..models.database import (
from ..services.research_service import (
run_research_process,
start_research_process,
+ export_report_to_format,
+ OUTPUT_DIR,
)
from ..utils.templates import render_template_with_defaults
from .globals import active_research, termination_flags
@@ -31,9 +34,6 @@ from ...utilities.db_utils import get_db_session
# Create a Blueprint for the research application
research_bp = Blueprint("research", __name__)
-# Output directory for research results
-OUTPUT_DIR = "research_outputs"
-
# Add the missing static file serving route
@research_bp.route("/static/<path:path>")
@@ -737,6 +737,64 @@ def get_research_report(research_id):
session.close()
+@research_bp.route(
+ "/api/v1/research/<research_id>/export/<format>", methods=["POST"]
+)
+def export_research_report(research_id, format):
+ """Export research report to different formats (LaTeX or Quarto)"""
+ try:
+ if format not in ["latex", "quarto", "ris"]:
+ return jsonify(
+ {"error": "Invalid format. Use 'latex', 'quarto', or 'ris'"}
+ ), 400
+
+ # Get research from database
+ session = get_db_session()
+ try:
+ research = (
+ session.query(ResearchHistory).filter_by(id=research_id).first()
+ )
+ if not research:
+ return jsonify({"error": "Research not found"}), 404
+
+ # Get the report path
+ if research.report_path:
+ report_path = OUTPUT_DIR / research.report_path
+ else:
+ # Try to construct the path
+ filename = f"research_{research.query[:50].replace(' ', '_').replace('/', '_')}_{research.created_at.strftime('%Y%m%d_%H%M%S')}.md"
+ report_path = OUTPUT_DIR / filename
+
+ if not report_path.exists():
+ return jsonify({"error": "Report file not found"}), 404
+
+ # Export to requested format
+ try:
+ export_path = export_report_to_format(report_path, format)
+
+ # Send the file
+ return send_file(
+ export_path,
+ as_attachment=True,
+ download_name=export_path.name,
+ mimetype="text/plain"
+ if format == "latex"
+ else "text/markdown",
+ )
+ except Exception as e:
+ logger.error(f"Error exporting report: {str(e)}")
+ return jsonify(
+ {"error": f"Failed to export to {format}: {str(e)}"}
+ ), 500
+
+ finally:
+ session.close()
+
+ except Exception as e:
+ logger.exception(f"Error in export endpoint: {str(e)}")
+ return jsonify({"error": "An internal error has occurred"}), 500
+
+
@research_bp.route("/api/research/<research_id>/status")
def get_research_status(research_id):
"""Get the status of a research process"""
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index 5945e45735..f20f6719d3 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -454,7 +454,7 @@ def save_all_settings():
)
-@settings_bp.route("/reset_to_defaults", methods=["GET"])
+@settings_bp.route("/reset_to_defaults", methods=["GET", "POST"])
def reset_to_defaults():
"""Reset all settings to their default values"""
db_session = get_db_session()
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 944813efca..28b0b88c16 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -1,4 +1,5 @@
import hashlib
+import re
import threading
from datetime import datetime
from pathlib import Path
@@ -18,12 +19,101 @@ from ..database.models import ResearchStrategy, ResearchHistory
from ..models.database import calculate_duration
from .socket_service import SocketIOService
from ...error_handling.report_generator import ErrorReportGenerator
+from ...text_optimization import CitationFormatter, CitationMode
+from ...utilities.db_utils import get_db_setting
# Output directory for research results
_PROJECT_ROOT = Path(__file__).parents[4]
OUTPUT_DIR = _PROJECT_ROOT / "research_outputs"
+def get_citation_formatter():
+ """Get citation formatter with settings from database."""
+ citation_format = get_db_setting(
+ "report.citation_format", "domain_id_hyperlinks"
+ )
+ mode_map = {
+ "number_hyperlinks": CitationMode.NUMBER_HYPERLINKS,
+ "domain_hyperlinks": CitationMode.DOMAIN_HYPERLINKS,
+ "domain_id_hyperlinks": CitationMode.DOMAIN_ID_HYPERLINKS,
+ "domain_id_always_hyperlinks": CitationMode.DOMAIN_ID_ALWAYS_HYPERLINKS,
+ "no_hyperlinks": CitationMode.NO_HYPERLINKS,
+ }
+ mode = mode_map.get(citation_format, CitationMode.DOMAIN_ID_HYPERLINKS)
+ return CitationFormatter(mode=mode)
+
+
+def export_report_to_format(report_path: Path, format: str, title: str = None):
+ """
+ Export a markdown report to different formats.
+
+ Args:
+ report_path: Path to the markdown report file
+ format: Export format ('latex' or 'quarto')
+ title: Optional title for the document
+
+ Returns:
+ Path to the generated file
+ """
+ # Read the markdown content
+ with report_path.open("r", encoding="utf-8") as f:
+ markdown_content = f.read()
+
+ if format == "latex":
+ from ...text_optimization.citation_formatter import LaTeXExporter
+
+ exporter = LaTeXExporter()
+ exported_content = exporter.export_to_latex(markdown_content)
+ export_path = report_path.with_suffix(".tex")
+ elif format == "quarto":
+ from ...text_optimization.citation_formatter import QuartoExporter
+
+ exporter = QuartoExporter()
+ # Extract title from markdown if not provided
+ if not title:
+ title_match = re.search(
+ r"^#\s+(.+)$", markdown_content, re.MULTILINE
+ )
+ title = title_match.group(1) if title_match else "Research Report"
+ exported_content = exporter.export_to_quarto(markdown_content, title)
+ export_path = report_path.with_suffix(".qmd")
+
+ # Also save the bibliography file for Quarto
+ bib_content = exporter._generate_bibliography(markdown_content)
+ bib_path = report_path.parent / "references.bib"
+ with bib_path.open("w", encoding="utf-8") as f:
+ f.write(bib_content)
+ logger.info(f"Created bibliography file: {bib_path}")
+ elif format == "ris":
+ from ...text_optimization.citation_formatter import RISExporter
+
+ exporter = RISExporter()
+ exported_content = exporter.export_to_ris(markdown_content)
+ export_path = report_path.with_suffix(".ris")
+ else:
+ raise ValueError(f"Unsupported export format: {format}")
+
+ # Save exported file
+ with export_path.open("w", encoding="utf-8") as f:
+ f.write(exported_content)
+
+ logger.info(f"Exported report to {format}: {export_path}")
+ return export_path
+
+
+def export_report_to_latex(report_path: Path):
+ """
+ Export a markdown report to LaTeX format.
+
+ Args:
+ report_path: Path to the markdown report file
+
+ Returns:
+ Path to the generated LaTeX file
+ """
+ return export_report_to_format(report_path, "latex")
+
+
def save_research_strategy(research_id, strategy_name):
"""
Save the strategy used for a research to the database.
@@ -726,10 +816,17 @@ def run_research_process(
)
logger.info("Writing report to: %s", report_path)
+
+ # Format citations in the markdown content
+ formatter = get_citation_formatter()
+ formatted_content = formatter.format_document(
+ clean_markdown
+ )
+
with report_path.open("w", encoding="utf-8") as f:
f.write("# Quick Research Summary\n\n")
f.write(f"Query: {query}\n\n")
- f.write(clean_markdown)
+ f.write(formatted_content)
f.write("\n\n## Research Metrics\n")
f.write(
f"- Search Iterations: {results['iterations']}\n"
@@ -738,10 +835,34 @@ def run_research_process(
f"- Generated at: {datetime.utcnow().isoformat()}\n"
)
+ # Export to additional formats if enabled
+ export_formats = get_db_setting(
+ "report.export_formats", ["markdown"]
+ )
+ if isinstance(export_formats, str):
+ export_formats = [export_formats]
+
+ export_paths = {"markdown": str(report_path)}
+ for format in export_formats:
+ if format != "markdown":
+ try:
+ export_path = export_report_to_format(
+ report_path, format
+ )
+ export_paths[format] = str(export_path)
+ logger.info(
+ f"Exported report to {format}: {export_path}"
+ )
+ except Exception as e:
+ logger.error(
+ f"Failed to export to {format}: {e}"
+ )
+
# Update database
metadata = {
"iterations": results["iterations"],
"generated_at": datetime.utcnow().isoformat(),
+ "export_paths": export_paths,
}
# Calculate duration in seconds - using UTC consistently
@@ -830,12 +951,40 @@ def run_research_process(
output_dir = report_path.parent
output_dir.mkdir(parents=True, exist_ok=True)
+ # Format citations in the report content
+ formatter = get_citation_formatter()
+ formatted_content = formatter.format_document(
+ final_report["content"]
+ )
+
with report_path.open("w", encoding="utf-8") as f:
- f.write(final_report["content"])
+ f.write(formatted_content)
+
+ # Export to additional formats if enabled
+ export_formats = get_db_setting(
+ "report.export_formats", ["markdown"]
+ )
+ if isinstance(export_formats, str):
+ export_formats = [export_formats]
+
+ export_paths = {"markdown": str(report_path)}
+ for format in export_formats:
+ if format != "markdown":
+ try:
+ export_path = export_report_to_format(
+ report_path, format
+ )
+ export_paths[format] = str(export_path)
+ logger.info(
+ f"Exported report to {format}: {export_path}"
+ )
+ except Exception as e:
+ logger.error(f"Failed to export to {format}: {e}")
# Update database
metadata = final_report["metadata"]
metadata["iterations"] = results["iterations"]
+ metadata["export_paths"] = export_paths
# Calculate duration in seconds - using UTC consistently
now = datetime.utcnow()
diff --git a/src/local_deep_research/web/static/js/components/results.js b/src/local_deep_research/web/static/js/components/results.js
index a8cca44349..4bbd1e6b44 100644
--- a/src/local_deep_research/web/static/js/components/results.js
+++ b/src/local_deep_research/web/static/js/components/results.js
@@ -69,6 +69,24 @@
pdfBtn.addEventListener('click', handlePdfExport);
}
+ // LaTeX export button
+ const latexBtn = document.getElementById('export-latex-btn');
+ if (latexBtn) {
+ latexBtn.addEventListener('click', () => handleFormatExport('latex'));
+ }
+
+ // Quarto export button
+ const quartoBtn = document.getElementById('export-quarto-btn');
+ if (quartoBtn) {
+ quartoBtn.addEventListener('click', () => handleFormatExport('quarto'));
+ }
+
+ // RIS export button (for Zotero)
+ const risBtn = document.getElementById('export-ris-btn');
+ if (risBtn) {
+ risBtn.addEventListener('click', () => handleFormatExport('ris'));
+ }
+
// Back to history button
const backBtn = document.getElementById('back-to-history');
if (backBtn) {
@@ -699,6 +717,59 @@
}
}
+ /**
+ * Handle export to specific format (LaTeX or Quarto)
+ * @param {string} format - Export format ('latex' or 'quarto')
+ */
+ async function handleFormatExport(format) {
+ try {
+ if (!researchId) {
+ throw new Error('No research ID available');
+ }
+
+ const formatName = format === 'latex' ? 'LaTeX' : format === 'quarto' ? 'Quarto' : 'RIS';
+ console.log(`Exporting to ${formatName}...`);
+
+ // Get CSRF token
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
+
+ // Call API to export the report
+ const response = await fetch(`/api/v1/research/${researchId}/export/${format}`, {
+ method: 'POST',
+ headers: {
+ 'X-CSRFToken': csrfToken
+ }
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || `Failed to export to ${formatName}`);
+ }
+
+ // Get the blob from response
+ const blob = await response.blob();
+
+ // Determine file extension
+ const extension = format === 'latex' ? 'tex' : format === 'quarto' ? 'qmd' : 'ris';
+
+ // Create download link
+ const link = document.createElement('a');
+ link.href = URL.createObjectURL(blob);
+ link.download = `research_${researchId}.${extension}`;
+
+ // Trigger download
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+
+ console.log(`Successfully exported to ${formatName}`);
+
+ } catch (error) {
+ console.error(`Error exporting to ${format}:`, error);
+ alert(`Failed to export to ${format}: ${error.message}`);
+ }
+ }
+
/**
* Handle PDF export button click
diff --git a/src/local_deep_research/web/templates/pages/results.html b/src/local_deep_research/web/templates/pages/results.html
index 4eae50a0ff..286e63d831 100644
--- a/src/local_deep_research/web/templates/pages/results.html
+++ b/src/local_deep_research/web/templates/pages/results.html
@@ -11,6 +11,9 @@
<button class="btn btn-outline" id="view-metrics-btn"><i class="fas fa-chart-bar"></i> View Metrics</button>
<button class="btn btn-outline" id="download-pdf-btn"><i class="fas fa-file-pdf"></i> Download PDF</button>
<button class="btn btn-outline" id="export-markdown-btn"><i class="fas fa-file-alt"></i> Export Markdown</button>
+ <button class="btn btn-outline" id="export-latex-btn"><i class="fas fa-file-code"></i> Export LaTeX</button>
+ <button class="btn btn-outline" id="export-quarto-btn"><i class="fas fa-file-code"></i> Export Quarto</button>
+ <button class="btn btn-outline" id="export-ris-btn"><i class="fas fa-file-export"></i> Export RIS (Zotero)</button>
<button class="btn btn-outline" id="back-to-history"><i class="fas fa-arrow-left"></i> Back to History</button>
</div>
</div>
diff --git a/tests/text_optimization/__init__.py b/tests/text_optimization/__init__.py
new file mode 100644
index 0000000000..775ec43d0c
--- /dev/null
+++ b/tests/text_optimization/__init__.py
@@ -0,0 +1 @@
+"""Tests for text optimization module."""
diff --git a/tests/text_optimization/test_citation_formatter.py b/tests/text_optimization/test_citation_formatter.py
new file mode 100644
index 0000000000..94b4af8268
--- /dev/null
+++ b/tests/text_optimization/test_citation_formatter.py
@@ -0,0 +1,674 @@
+"""Tests for citation formatter functionality."""
+
+import pytest
+from local_deep_research.text_optimization import (
+ CitationFormatter,
+ CitationMode,
+ LaTeXExporter,
+ QuartoExporter,
+ RISExporter,
+)
+
+
+class TestCitationFormatter:
+ """Test cases for CitationFormatter class."""
+
+ @pytest.fixture
+ def sample_content(self):
+ """Sample markdown content with citations."""
+ return """# Research Report
+
+This is a research report about artificial intelligence [1]. Recent advances in
+machine learning [2] have shown significant progress. The work by researchers
+at DeepMind [3] has been particularly influential.
+
+## Key Findings
+
+The analysis reveals several important points:
+- Deep learning models are becoming more efficient [1]
+- Transfer learning enables better generalization [2]
+- Large language models show emergent capabilities [3]
+- Multiple studies confirm these findings [1][2][3]
+- Some research combines different approaches [2][3]
+- Comprehensive surveys cover all aspects [1, 2, 3]
+- Recent work builds on earlier findings [2, 3]
+
+## Sources
+
+[1] Understanding Deep Learning
+ URL: https://arxiv.org/abs/2104.12345
+
+[2] Transfer Learning: A Survey
+ URL: https://www.nature.com/articles/s41586-021-03819-2
+
+[3] Emergent Abilities of Large Language Models
+ URL: https://openai.com/research/emergent-abilities
+"""
+
+ @pytest.fixture
+ def content_without_urls(self):
+ """Sample content with citations but no URLs."""
+ return """# Report
+
+Some findings [1] and more [2].
+
+## Sources
+
+[1] First Source
+[2] Second Source
+"""
+
+ def test_number_hyperlinks_mode(self, sample_content):
+ """Test citation formatting with number hyperlinks."""
+ formatter = CitationFormatter(CitationMode.NUMBER_HYPERLINKS)
+ result = formatter.format_document(sample_content)
+
+ # Check single citations are formatted correctly
+ assert "[[1]](https://arxiv.org/abs/2104.12345)" in result
+ assert (
+ "[[2]](https://www.nature.com/articles/s41586-021-03819-2)"
+ in result
+ )
+ assert "[[3]](https://openai.com/research/emergent-abilities)" in result
+
+ # Check multiple consecutive citations
+ assert (
+ "[[1]](https://arxiv.org/abs/2104.12345)[[2]](https://www.nature.com/articles/s41586-021-03819-2)[[3]](https://openai.com/research/emergent-abilities)"
+ in result
+ )
+
+ # Check comma-separated citations
+ assert (
+ "[[1]](https://arxiv.org/abs/2104.12345)[[2]](https://www.nature.com/articles/s41586-021-03819-2)[[3]](https://openai.com/research/emergent-abilities)"
+ in result
+ )
+
+ # Ensure sources section is unchanged
+ assert "## Sources" in result
+ assert "[1] Understanding Deep Learning" in result
+
+ def test_domain_hyperlinks_mode(self, sample_content):
+ """Test citation formatting with domain hyperlinks."""
+ formatter = CitationFormatter(CitationMode.DOMAIN_HYPERLINKS)
+ result = formatter.format_document(sample_content)
+
+ # Check domain formatting
+ assert "[[arxiv.org]](https://arxiv.org/abs/2104.12345)" in result
+ assert (
+ "[[nature.com]](https://www.nature.com/articles/s41586-021-03819-2)"
+ in result
+ )
+ assert (
+ "[[openai.com]](https://openai.com/research/emergent-abilities)"
+ in result
+ )
+
+ # Check multiple citations work
+ assert (
+ "[[arxiv.org]](https://arxiv.org/abs/2104.12345)[[nature.com]](https://www.nature.com/articles/s41586-021-03819-2)[[openai.com]](https://openai.com/research/emergent-abilities)"
+ in result
+ )
+
+ def test_no_hyperlinks_mode(self, sample_content):
+ """Test citation formatting with no hyperlinks."""
+ formatter = CitationFormatter(CitationMode.NO_HYPERLINKS)
+ result = formatter.format_document(sample_content)
+
+ # Content should be unchanged
+ assert result == sample_content
+ assert "[[1]]" not in result
+ assert "](https://" not in result
+
+ def test_citations_without_urls(self, content_without_urls):
+ """Test handling of citations without URLs."""
+ formatter = CitationFormatter(CitationMode.NUMBER_HYPERLINKS)
+ result = formatter.format_document(content_without_urls)
+
+ # Citations without URLs should remain unchanged
+ assert "[1]" in result
+ assert "[2]" in result
+ assert "[[1]]" not in result
+ assert "[[2]]" not in result
+
+ def test_no_sources_section(self):
+ """Test handling of content without sources section."""
+ content = "This is text with [1] citation but no sources."
+ formatter = CitationFormatter(CitationMode.NUMBER_HYPERLINKS)
+ result = formatter.format_document(content)
+
+ # Should return unchanged content
+ assert result == content
+
+ def test_mixed_citation_formats(self):
+ """Test handling of mixed citation formats."""
+ content = """Text with various formats:
+- Single: [1]
+- Multiple: [1][2]
+- Comma-separated: [1, 2, 3]
+- With spaces: [1,2,3] and [1, 2]
+
+## Sources
+
+[1] Source One
+ URL: https://example1.com
+[2] Source Two
+ URL: https://example2.com
+[3] Source Three
+ URL: https://example3.com
+"""
+ formatter = CitationFormatter(CitationMode.NUMBER_HYPERLINKS)
+ result = formatter.format_document(content)
+
+ # All formats should be converted
+ assert "[[1]](https://example1.com)" in result
+ assert (
+ "[[1]](https://example1.com)[[2]](https://example2.com)" in result
+ )
+ assert (
+ "[[1]](https://example1.com)[[2]](https://example2.com)[[3]](https://example3.com)"
+ in result
+ )
+
+ def test_domain_extraction(self):
+ """Test domain extraction from various URLs."""
+ formatter = CitationFormatter(CitationMode.DOMAIN_HYPERLINKS)
+
+ # Test various URL formats
+ test_cases = [
+ ("https://arxiv.org/abs/1234", "arxiv.org"),
+ ("https://www.nature.com/articles/123", "nature.com"),
+ ("https://github.com/user/repo", "github.com"),
+ ("https://subdomain.example.com/path", "example.com"),
+ ("https://example.co.uk/path", "co.uk"),
+ ]
+
+ for url, expected_domain in test_cases:
+ domain = formatter._extract_domain(url)
+ assert domain == expected_domain
+
+ def test_edge_cases(self):
+ """Test edge cases and malformed content."""
+ formatter = CitationFormatter(CitationMode.NUMBER_HYPERLINKS)
+
+ # Empty content
+ assert formatter.format_document("") == ""
+
+ # Content with only sources section
+ content = """## Sources
+[1] Test
+ URL: https://test.com
+"""
+ result = formatter.format_document(content)
+ assert result == content
+
+ # Malformed citations
+ content = """Text with [a] non-numeric [citation].
+
+## Sources
+[a] Invalid citation
+"""
+ result = formatter.format_document(content)
+ assert "[a]" in result # Should remain unchanged
+ assert "[citation]" in result
+
+ def test_domain_id_hyperlinks_mode(self, sample_content):
+ """Test citation formatting with domain IDs for repeated domains."""
+ # Add more sources from same domains to test ID functionality
+ content_with_repeated_domains = """# Research Report
+
+Citations from GitHub [1] and more from GitHub [2].
+ArXiv papers [3] and another ArXiv paper [4].
+A Nature article [5] and OpenAI research [6].
+
+## Sources
+
+[1] First GitHub Project
+ URL: https://github.com/user/project1
+
+[2] Second GitHub Project
+ URL: https://github.com/user/project2
+
+[3] First ArXiv Paper
+ URL: https://arxiv.org/abs/2024.1111
+
+[4] Second ArXiv Paper
+ URL: https://arxiv.org/abs/2024.2222
+
+[5] Nature Article
+ URL: https://www.nature.com/articles/s41586-024-1234
+
+[6] OpenAI Research
+ URL: https://openai.com/research/gpt4
+"""
+ formatter = CitationFormatter(CitationMode.DOMAIN_ID_HYPERLINKS)
+ result = formatter.format_document(content_with_repeated_domains)
+
+ # Check that repeated domains get hyphen-separated IDs
+ assert "[[github.com-1]](https://github.com/user/project1)" in result
+ assert "[[github.com-2]](https://github.com/user/project2)" in result
+ assert "[[arxiv.org-1]](https://arxiv.org/abs/2024.1111)" in result
+ assert "[[arxiv.org-2]](https://arxiv.org/abs/2024.2222)" in result
+
+ # Check that single domain citations don't get IDs
+ assert (
+ "[[nature.com]](https://www.nature.com/articles/s41586-024-1234)"
+ in result
+ )
+ assert "[[openai.com]](https://openai.com/research/gpt4)" in result
+
+ def test_real_world_example(self):
+ """Test with real-world example from Local Deep Research output."""
+ content = """# Quick Research Summary
+
+Query: local deep research
+
+Local Deep Research represents a new generation of AI-powered research assistants [1][3][11]. It utilizes any LLM hosted by either Ollama or LMStudio [2]. The concept was introduced as DeepSearcher [4] and further explained on Medium [7]. Web searches are conducted using DuckDuckGo [5], and the system incorporates tools like Milvus [6]. Updates were discussed on Reddit [10] and demonstrations on YouTube [8][12]. The Ollama variant [9] provides an alternative approach.
+
+## Sources
+
+[1] LearningCircuit/local-deep-research- GitHub
+ URL: https://github.com/LearningCircuit/local-deep-research
+
+[2] langchain-ai/local-deep-researcher - GitHub
+ URL: https://github.com/langchain-ai/local-deep-researcher
+
+[3] local-deep-research- PyPI
+ URL: https://pypi.org/project/local-deep-research/
+
+[4] Introducing DeepSearcher
+ URL: https://zilliz.com/blog/introduce-deepsearcher
+
+[5] A local LLM research assistant
+ URL: https://www.reddit.com/r/LocalLLaMA/comments/1ilkosp/
+
+[6] Introducing DeepSearcher - Milvus
+ URL: https://milvus.io/blog/introduce-deepsearcher.md
+
+[7] DeepSearcher on Medium
+ URL: https://milvusio.medium.com/deepsearcher
+
+[8] Private AI Deep Research - YouTube
+ URL: https://m.youtube.com/watch?v=4tDqV__jzKY
+
+[9] Ollama Deep Research
+ URL: https://apidog.com/blog/ollama-deep-research/
+
+[10] Local Deep Research Update
+ URL: https://www.reddit.com/r/LocalLLaMA/comments/1j79obx/
+
+[11] local-deep-research 0.3.3 - PyPI
+ URL: https://pypi.org/project/local-deep-research/0.3.3/
+
+[12] Building a local deep researcher - YouTube
+ URL: https://www.youtube.com/watch?v=sGUjmyfof4Q
+"""
+ formatter = CitationFormatter(CitationMode.DOMAIN_ID_HYPERLINKS)
+ result = formatter.format_document(content)
+
+ # Check multiple citations from same domain get IDs
+ assert (
+ "[[github.com-1]](https://github.com/LearningCircuit/local-deep-research)"
+ in result
+ )
+ assert (
+ "[[github.com-2]](https://github.com/langchain-ai/local-deep-researcher)"
+ in result
+ )
+ assert (
+ "[[pypi.org-1]](https://pypi.org/project/local-deep-research/)"
+ in result
+ )
+ assert (
+ "[[pypi.org-2]](https://pypi.org/project/local-deep-research/0.3.3/)"
+ in result
+ )
+ assert (
+ "[[reddit.com-1]](https://www.reddit.com/r/LocalLLaMA/comments/1ilkosp/)"
+ in result
+ )
+ assert (
+ "[[reddit.com-2]](https://www.reddit.com/r/LocalLLaMA/comments/1j79obx/)"
+ in result
+ )
+ assert (
+ "[[youtube.com-1]](https://m.youtube.com/watch?v=4tDqV__jzKY)"
+ in result
+ )
+ assert (
+ "[[youtube.com-2]](https://www.youtube.com/watch?v=sGUjmyfof4Q)"
+ in result
+ )
+
+ # Check single domain citations don't get IDs
+ assert (
+ "[[zilliz.com]](https://zilliz.com/blog/introduce-deepsearcher)"
+ in result
+ )
+ assert (
+ "[[milvus.io]](https://milvus.io/blog/introduce-deepsearcher.md)"
+ in result
+ )
+ assert (
+ "[[apidog.com]](https://apidog.com/blog/ollama-deep-research/)"
+ in result
+ )
+ assert (
+ "[[medium.com]](https://milvusio.medium.com/deepsearcher)" in result
+ )
+
+ def test_domain_id_always_hyperlinks_mode(self):
+ """Test citation formatting with domain IDs always added for consistency."""
+ # Use the same content as test_domain_id_hyperlinks_mode
+ content_with_repeated_domains = """# Research Report
+
+Citations from GitHub [1] and more from GitHub [2].
+ArXiv papers [3] and another ArXiv paper [4].
+A Nature article [5] and OpenAI research [6].
+
+## Sources
+
+[1] First GitHub Project
+ URL: https://github.com/user/project1
+
+[2] Second GitHub Project
+ URL: https://github.com/user/project2
+
+[3] First ArXiv Paper
+ URL: https://arxiv.org/abs/2024.1111
+
+[4] Second ArXiv Paper
+ URL: https://arxiv.org/abs/2024.2222
+
+[5] Nature Article
+ URL: https://www.nature.com/articles/s41586-024-1234
+
+[6] OpenAI Research
+ URL: https://openai.com/research/gpt4
+"""
+ formatter = CitationFormatter(CitationMode.DOMAIN_ID_ALWAYS_HYPERLINKS)
+ result = formatter.format_document(content_with_repeated_domains)
+
+ # Check that ALL domains get IDs, even single ones
+ assert "[[github.com-1]](https://github.com/user/project1)" in result
+ assert "[[github.com-2]](https://github.com/user/project2)" in result
+ assert "[[arxiv.org-1]](https://arxiv.org/abs/2024.1111)" in result
+ assert "[[arxiv.org-2]](https://arxiv.org/abs/2024.2222)" in result
+ assert (
+ "[[nature.com-1]](https://www.nature.com/articles/s41586-024-1234)"
+ in result
+ )
+ assert "[[openai.com-1]](https://openai.com/research/gpt4)" in result
+
+
+class TestLaTeXExporter:
+ """Test cases for LaTeX export functionality."""
+
+ @pytest.fixture
+ def sample_markdown(self):
+ """Sample markdown for LaTeX conversion."""
+ return """# Main Title
+
+## Introduction
+
+This is a **bold** statement with *italic* text and `code`.
+
+### Subsection
+
+- First item
+- Second item
+- Third item
+
+Text with citations [1] and [2].
+
+## Sources
+
+[1] First Source
+ URL: https://example.com
+[2] Second Source
+ URL: https://example2.com
+"""
+
+ def test_latex_export_basic(self, sample_markdown):
+ """Test basic LaTeX export functionality."""
+ exporter = LaTeXExporter()
+ result = exporter.export_to_latex(sample_markdown)
+
+ # Check header
+ assert r"\documentclass[12pt]{article}" in result
+ assert r"\begin{document}" in result
+ assert r"\end{document}" in result
+
+ # Check heading conversion
+ assert r"\section{Main Title}" in result
+ assert r"\subsection{Introduction}" in result
+ assert r"\subsubsection{Subsection}" in result
+
+ # Check emphasis conversion
+ assert r"\textbf{bold}" in result
+ assert r"\textit{italic}" in result
+ assert r"\texttt{code}" in result
+
+ # Check citation conversion
+ assert r"\cite{ref1}" in result
+ assert r"\cite{ref2}" in result
+
+ # Check bibliography
+ assert r"\begin{thebibliography}" in result
+ assert r"\bibitem{ref1}" in result
+
+ def test_latex_list_conversion(self, sample_markdown):
+ """Test list conversion to LaTeX."""
+ exporter = LaTeXExporter()
+ result = exporter.export_to_latex(sample_markdown)
+
+ # Check list conversion
+ assert r"\begin{itemize}" in result
+ assert r"\item First item" in result
+ assert r"\item Second item" in result
+ assert r"\item Third item" in result
+ assert r"\end{itemize}" in result
+
+ def test_latex_empty_content(self):
+ """Test LaTeX export with empty content."""
+ exporter = LaTeXExporter()
+ result = exporter.export_to_latex("")
+
+ assert r"\documentclass[12pt]{article}" in result
+ assert r"\begin{document}" in result
+ assert r"\end{document}" in result
+
+ def test_latex_no_sources(self):
+ """Test LaTeX export without sources section."""
+ content = "# Title\n\nSome text without citations."
+ exporter = LaTeXExporter()
+ result = exporter.export_to_latex(content)
+
+ # Should not include bibliography
+ assert r"\begin{thebibliography}" not in result
+
+
+class TestRISExporter:
+ """Test cases for RIS export functionality."""
+
+ @pytest.fixture
+ def sample_markdown(self):
+ """Sample markdown for RIS conversion."""
+ return """# Research Report
+
+This research explores various topics [1][2][3].
+
+## Sources
+
+[1] Understanding Deep Learning
+ URL: https://arxiv.org/abs/2104.12345
+
+[2] GitHub Project Documentation
+ URL: https://github.com/example/project
+
+[3] Reddit Discussion Thread
+ URL: https://www.reddit.com/r/example/comments/abc123
+
+[4] Local Resource Without URL
+"""
+
+ def test_ris_export_basic(self, sample_markdown):
+ """Test basic RIS export functionality."""
+ exporter = RISExporter()
+ result = exporter.export_to_ris(sample_markdown)
+
+ # Check that we have RIS entries
+ assert "TY - ELEC" in result
+ assert "ER - " in result
+
+ # Check specific entries
+ assert "ID - ref1" in result
+ assert "TI - Understanding Deep Learning" in result
+ assert "UR - https://arxiv.org/abs/2104.12345" in result
+ assert "PB - arXiv" in result
+
+ assert "ID - ref2" in result
+ assert "TI - GitHub Project Documentation" in result
+ assert "PB - GitHub" in result
+
+ assert "ID - ref3" in result
+ assert "TI - Reddit Discussion Thread" in result
+ assert "PB - Reddit" in result
+
+ # Check entry without URL
+ assert "ID - ref4" in result
+ assert "TI - Local Resource Without URL" in result
+
+ # Check date fields
+ assert "Y1 - " in result
+ assert "DA - " in result
+ assert "LA - en" in result
+
+ def test_ris_export_empty_content(self):
+ """Test RIS export with empty content."""
+ exporter = RISExporter()
+ result = exporter.export_to_ris("")
+ assert result == ""
+
+ def test_ris_export_no_sources(self):
+ """Test RIS export without sources section."""
+ content = "# Title\n\nSome text without sources."
+ exporter = RISExporter()
+ result = exporter.export_to_ris(content)
+ assert result == ""
+
+ def test_ris_publisher_extraction(self, sample_markdown):
+ """Test that publishers are correctly extracted from domains."""
+ exporter = RISExporter()
+ result = exporter.export_to_ris(sample_markdown)
+
+ # Check known publishers
+ assert "PB - arXiv" in result
+ assert "PB - GitHub" in result
+ assert "PB - Reddit" in result
+
+
+class TestQuartoExporter:
+ """Test cases for Quarto export functionality."""
+
+ @pytest.fixture
+ def sample_markdown(self):
+ """Sample markdown for Quarto conversion."""
+ return """# Research on AI Safety
+
+## Introduction
+
+This research explores **important** aspects of *AI safety* and `alignment`.
+
+### Current Approaches
+
+- Reinforcement learning from human feedback [1]
+- Constitutional AI [2]
+- Interpretability research [3]
+
+Multiple studies [1, 2, 3] have shown promising results.
+
+## Sources
+
+[1] RLHF: A Survey
+ URL: https://arxiv.org/abs/2023.1234
+[2] Constitutional AI
+ URL: https://anthropic.com/constitutional-ai
+[3] Mechanistic Interpretability
+ URL: https://distill.pub/2020/circuits
+"""
+
+ def test_quarto_export_basic(self, sample_markdown):
+ """Test basic Quarto export functionality."""
+ exporter = QuartoExporter()
+ result = exporter.export_to_quarto(
+ sample_markdown, "AI Safety Research"
+ )
+
+ # Check YAML header
+ assert "---" in result
+ assert 'title: "AI Safety Research"' in result
+ assert 'author: "Local Deep Research"' in result
+ assert "date: today" in result
+ assert "format:" in result
+ assert "bibliography: references.bib" in result
+
+ # Check citation conversion
+ assert "[@ref1]" in result
+ assert "[@ref2]" in result
+ assert "[@ref3]" in result
+ assert "[@ref1, @ref2, @ref3]" in result
+
+ # Check bibliography note
+ assert "Bibliography File Required" in result
+ assert "references.bib" in result
+ assert "@misc{ref1," in result
+
+ def test_quarto_title_extraction(self, sample_markdown):
+ """Test automatic title extraction from markdown."""
+ exporter = QuartoExporter()
+ # Don't provide title, should extract from markdown
+ result = exporter.export_to_quarto(sample_markdown)
+
+ assert 'title: "Research on AI Safety"' in result
+
+ def test_quarto_bibliography_generation(self, sample_markdown):
+ """Test BibTeX bibliography generation."""
+ exporter = QuartoExporter()
+ bib_content = exporter._generate_bibliography(sample_markdown)
+
+ # Check BibTeX entries
+ assert "@misc{ref1," in bib_content
+ assert 'title = "{RLHF: A Survey}"' in bib_content
+ assert "url = {https://arxiv.org/abs/2023.1234}" in bib_content
+ assert (
+ 'howpublished = "\\url{https://arxiv.org/abs/2023.1234}"'
+ in bib_content
+ )
+ assert "year = {2024}" in bib_content
+ assert 'note = "Accessed: \\today"' in bib_content
+
+ # Check all three entries
+ assert "@misc{ref2," in bib_content
+ assert "@misc{ref3," in bib_content
+
+ def test_quarto_empty_content(self):
+ """Test Quarto export with empty content."""
+ exporter = QuartoExporter()
+ result = exporter.export_to_quarto("", "Empty Report")
+
+ # Should still have YAML header
+ assert "---" in result
+ assert 'title: "Empty Report"' in result
+
+ def test_quarto_no_sources(self):
+ """Test Quarto export without sources section."""
+ content = "# Title\n\nSome text with citations [1] and [2]."
+ exporter = QuartoExporter()
+ result = exporter.export_to_quarto(content)
+
+ # Citations should still be converted
+ assert "[@ref1]" in result
+ assert "[@ref2]" in result
+
+ # Bibliography note should still appear but be empty
+ assert "Bibliography File Required" in result
diff --git a/tests/text_optimization/test_integration.py b/tests/text_optimization/test_integration.py
new file mode 100644
index 0000000000..5e393d095b
--- /dev/null
+++ b/tests/text_optimization/test_integration.py
@@ -0,0 +1,261 @@
+"""Integration tests for text optimization with the research service."""
+
+import pytest
+from pathlib import Path
+import tempfile
+from unittest.mock import patch
+
+from local_deep_research.web.services.research_service import (
+ get_citation_formatter,
+ export_report_to_latex,
+ export_report_to_format,
+)
+from local_deep_research.text_optimization import (
+ CitationFormatter,
+ CitationMode,
+)
+
+
+class TestResearchServiceIntegration:
+ """Test integration of text optimization with research service."""
+
+ @patch("local_deep_research.web.services.research_service.get_db_setting")
+ def test_get_citation_formatter_number_mode(self, mock_get_setting):
+ """Test getting formatter with number hyperlinks mode."""
+ mock_get_setting.return_value = "number_hyperlinks"
+
+ formatter = get_citation_formatter()
+ assert isinstance(formatter, CitationFormatter)
+ assert formatter.mode == CitationMode.NUMBER_HYPERLINKS
+
+ @patch("local_deep_research.web.services.research_service.get_db_setting")
+ def test_get_citation_formatter_domain_mode(self, mock_get_setting):
+ """Test getting formatter with domain hyperlinks mode."""
+ mock_get_setting.return_value = "domain_hyperlinks"
+
+ formatter = get_citation_formatter()
+ assert isinstance(formatter, CitationFormatter)
+ assert formatter.mode == CitationMode.DOMAIN_HYPERLINKS
+
+ @patch("local_deep_research.web.services.research_service.get_db_setting")
+ def test_get_citation_formatter_no_hyperlinks_mode(self, mock_get_setting):
+ """Test getting formatter with no hyperlinks mode."""
+ mock_get_setting.return_value = "no_hyperlinks"
+
+ formatter = get_citation_formatter()
+ assert isinstance(formatter, CitationFormatter)
+ assert formatter.mode == CitationMode.NO_HYPERLINKS
+
+ @patch("local_deep_research.web.services.research_service.get_db_setting")
+ def test_get_citation_formatter_invalid_mode(self, mock_get_setting):
+ """Test getting formatter with invalid mode falls back to default."""
+ mock_get_setting.return_value = "invalid_mode"
+
+ formatter = get_citation_formatter()
+ assert isinstance(formatter, CitationFormatter)
+ assert formatter.mode == CitationMode.DOMAIN_ID_HYPERLINKS # Default
+
+ def test_export_report_to_latex(self):
+ """Test LaTeX export functionality."""
+ # Create a temporary markdown file
+ with tempfile.NamedTemporaryFile(
+ mode="w", suffix=".md", delete=False
+ ) as f:
+ f.write("""# Test Report
+
+This is a test with citation [1].
+
+## Sources
+
+[1] Test Source
+ URL: https://example.com
+""")
+ markdown_path = Path(f.name)
+
+ try:
+ # Export to LaTeX
+ latex_path = export_report_to_latex(markdown_path)
+
+ # Check LaTeX file was created
+ assert latex_path.exists()
+ assert latex_path.suffix == ".tex"
+
+ # Check LaTeX content
+ with open(latex_path, "r") as f:
+ latex_content = f.read()
+
+ assert r"\documentclass[12pt]{article}" in latex_content
+ assert r"\section{Test Report}" in latex_content
+ assert r"\cite{ref1}" in latex_content
+ assert r"\bibitem{ref1}" in latex_content
+
+ # Clean up
+ latex_path.unlink()
+ finally:
+ markdown_path.unlink()
+
+ @patch("local_deep_research.web.services.research_service.get_db_setting")
+ def test_real_world_citation_formatting(self, mock_get_setting):
+ """Test citation formatting with real-world example."""
+ mock_get_setting.return_value = "number_hyperlinks"
+
+ # Simulate research report content
+ content = """# Deep Learning Research Summary
+
+Query: What are the latest advances in transformer architectures?
+
+## Executive Summary
+
+Recent advances in transformer architectures have focused on efficiency improvements [1],
+novel attention mechanisms [2], and scaling laws [3]. The field has seen rapid progress
+with models like GPT-4 [4] and Claude [5] demonstrating impressive capabilities.
+
+## Key Findings
+
+### Efficiency Improvements
+Multiple research groups have proposed methods to reduce computational complexity [1, 2, 3]:
+- Flash Attention reduces memory usage significantly [1]
+- Sparse transformers achieve O(n√n) complexity [2]
+- Linear attention approximations show promise [3]
+
+### Novel Architectures
+Recent architectural innovations include:
+- Mixture of Experts (MoE) models [4][5]
+- Retrieval-augmented generation [6]
+- Tool-use capabilities [7][8][9]
+
+## Sources
+
+[1] FlashAttention: Fast and Memory-Efficient Exact Attention
+ URL: https://arxiv.org/abs/2205.14135
+
+[2] Efficient Transformers: A Survey
+ URL: https://arxiv.org/abs/2009.06732
+
+[3] Linformer: Self-Attention with Linear Complexity
+ URL: https://arxiv.org/abs/2006.04768
+
+[4] Mixtral of Experts
+ URL: https://arxiv.org/abs/2401.04088
+
+[5] Switch Transformers
+ URL: https://arxiv.org/abs/2101.03961
+
+[6] Retrieval-Augmented Generation
+ URL: https://arxiv.org/abs/2005.11401
+
+[7] Toolformer: Language Models Can Teach Themselves
+ URL: https://arxiv.org/abs/2302.04761
+
+[8] WebGPT: Browser-assisted question-answering
+ URL: https://arxiv.org/abs/2112.09332
+
+[9] Constitutional AI: Harmlessness from AI Feedback
+ URL: https://arxiv.org/abs/2212.08073
+"""
+
+ formatter = get_citation_formatter()
+ result = formatter.format_document(content)
+
+ # Verify all citation formats are handled correctly
+ assert "[[1]](https://arxiv.org/abs/2205.14135)" in result
+ assert (
+ "[[1]](https://arxiv.org/abs/2205.14135)[[2]](https://arxiv.org/abs/2009.06732)[[3]](https://arxiv.org/abs/2006.04768)"
+ in result
+ )
+ assert (
+ "[[4]](https://arxiv.org/abs/2401.04088)[[5]](https://arxiv.org/abs/2101.03961)"
+ in result
+ )
+ assert (
+ "[[7]](https://arxiv.org/abs/2302.04761)[[8]](https://arxiv.org/abs/2112.09332)[[9]](https://arxiv.org/abs/2212.08073)"
+ in result
+ )
+
+ # Ensure sources section is preserved
+ assert "## Sources" in result
+ assert "[1] FlashAttention" in result
+
+ def test_export_report_to_quarto(self):
+ """Test Quarto export functionality."""
+ # Create a temporary markdown file
+ with tempfile.NamedTemporaryFile(
+ mode="w", suffix=".md", delete=False
+ ) as f:
+ f.write("""# AI Research Report
+
+This report discusses recent advances [1] and challenges [2].
+
+## Sources
+
+[1] Advances in AI
+ URL: https://arxiv.org/abs/2024.1234
+[2] AI Challenges
+ URL: https://example.com/challenges
+""")
+ markdown_path = Path(f.name)
+
+ try:
+ # Export to Quarto
+ quarto_path = export_report_to_format(
+ markdown_path, "quarto", "AI Research"
+ )
+
+ # Check Quarto file was created
+ assert quarto_path.exists()
+ assert quarto_path.suffix == ".qmd"
+
+ # Check Quarto content
+ with open(quarto_path, "r") as f:
+ quarto_content = f.read()
+
+ # Verify YAML header
+ assert 'title: "AI Research"' in quarto_content
+ assert "bibliography: references.bib" in quarto_content
+
+ # Verify citation conversion
+ assert "[@ref1]" in quarto_content
+ assert "[@ref2]" in quarto_content
+
+ # Check bibliography file was created
+ bib_path = markdown_path.parent / "references.bib"
+ assert bib_path.exists()
+
+ with open(bib_path, "r") as f:
+ bib_content = f.read()
+
+ assert "@misc{ref1," in bib_content
+ assert 'title = "{Advances in AI}"' in bib_content
+
+ # Clean up
+ quarto_path.unlink()
+ bib_path.unlink()
+ finally:
+ markdown_path.unlink()
+
+ def test_export_with_invalid_format(self):
+ """Test export with invalid format raises error."""
+ with tempfile.NamedTemporaryFile(
+ mode="w", suffix=".md", delete=False
+ ) as f:
+ f.write("# Test")
+ markdown_path = Path(f.name)
+
+ try:
+ with pytest.raises(ValueError, match="Unsupported export format"):
+ export_report_to_format(markdown_path, "invalid_format")
+ finally:
+ markdown_path.unlink()
+
+ @patch("local_deep_research.web.services.research_service.get_db_setting")
+ def test_automatic_export_formats(self, mock_get_setting):
+ """Test automatic export to multiple formats based on settings."""
+ # This would be called in the actual research service when saving reports
+ mock_get_setting.return_value = ["markdown", "latex", "quarto"]
+
+ # Simulate the export logic
+ export_formats = mock_get_setting("report.export_formats", ["markdown"])
+
+ assert "markdown" in export_formats
+ assert "latex" in export_formats
+ assert "quarto" in export_formats
diff --git a/tests/ui_tests/test_star_reviews_debug.js b/tests/ui_tests/test_star_reviews_debug.js
deleted file mode 100755
index ee374dce36..0000000000
--- a/tests/ui_tests/test_star_reviews_debug.js
+++ /dev/null
@@ -1,202 +0,0 @@
-#!/usr/bin/env node
-
-const puppeteer = require('puppeteer');
-
-async function debugStarReviews() {
- console.log('🚀 Starting star reviews debug test...');
-
- const browser = await puppeteer.launch({
- headless: false,
- args: [
- '--no-sandbox',
- '--disable-setuid-sandbox',
- '--disable-web-security',
- '--disable-features=VizDisplayCompositor'
- ],
- slowMo: 100 // Slow down for debugging
- });
-
- const page = await browser.newPage();
-
- // Enable console logging
- page.on('console', msg => {
- const type = msg.type();
- if (type === 'error') {
- console.log('❌ BROWSER ERROR:', msg.text());
- } else if (type === 'warn') {
- console.log('⚠️ BROWSER WARNING:', msg.text());
- } else {
- console.log('📝 BROWSER LOG:', msg.text());
- }
- });
-
- // Monitor network requests
- page.on('response', response => {
- const url = response.url();
- const status = response.status();
- if (url.includes('/metrics/api/star-reviews')) {
- console.log(`🌐 API Response: ${url} - Status: ${status}`);
- }
- });
-
- // Monitor request failures
- page.on('requestfailed', request => {
- console.log('❌ REQUEST FAILED:', request.url(), request.failure().errorText);
- });
-
- try {
- console.log('📄 Navigating to star reviews page...');
- await page.goto('http://localhost:5000/metrics/star-reviews', {
- waitUntil: 'networkidle2',
- timeout: 10000
- });
-
- // Wait for page to load
- await page.waitForSelector('body', { timeout: 5000 });
-
- console.log('🔍 Checking page title...');
- const title = await page.title();
- console.log('Page title:', title);
-
- // Check if main containers exist
- console.log('🏗️ Checking page structure...');
- const hasMainContainer = await page.$('.star-reviews-container') !== null;
- console.log('Main container exists:', hasMainContainer);
-
- const hasHeader = await page.$('h1') !== null;
- console.log('Header exists:', hasHeader);
-
- if (hasHeader) {
- const headerText = await page.$eval('h1', el => el.textContent);
- console.log('Header text:', headerText);
- }
-
- // Check for loading indicators
- console.log('⏳ Checking for loading states...');
- const loadingElements = await page.$$('.loading, .spinner, [data-loading]');
- console.log('Loading elements found:', loadingElements.length);
-
- // Wait for API call to complete
- console.log('🔄 Waiting for API data...');
- await new Promise(resolve => setTimeout(resolve, 3000));
-
- // Check API response manually
- console.log('📡 Testing API endpoint directly...');
- const apiResponse = await page.evaluate(async () => {
- try {
- const response = await fetch('/metrics/api/star-reviews');
- const data = await response.json();
- return { success: true, data, status: response.status };
- } catch (error) {
- return { success: false, error: error.message };
- }
- });
-
- console.log('API Response:', JSON.stringify(apiResponse, null, 2));
-
- // Check for chart canvases
- console.log('📊 Checking for chart elements...');
- const chartCanvases = await page.$$('canvas');
- console.log('Chart canvases found:', chartCanvases.length);
-
- for (let i = 0; i < chartCanvases.length; i++) {
- const canvasId = await chartCanvases[i].evaluate(el => el.id);
- const canvasVisible = await chartCanvases[i].isIntersectingViewport();
- console.log(`Canvas ${i}: ID="${canvasId}", Visible=${canvasVisible}`);
- }
-
- // Check for data display elements
- console.log('📋 Checking for data display elements...');
- const statsCards = await page.$$('.stat-card, .metric-card, .card');
- console.log('Stats cards found:', statsCards.length);
-
- // Check for error messages
- console.log('🚨 Checking for error messages...');
- const errorElements = await page.$$('.error, .alert-danger, [data-error]');
- console.log('Error elements found:', errorElements.length);
-
- for (let errorEl of errorElements) {
- const errorText = await errorEl.evaluate(el => el.textContent);
- console.log('Error message:', errorText);
- }
-
- // Check JavaScript execution
- console.log('🔧 Testing JavaScript functionality...');
- const jsTest = await page.evaluate(() => {
- // Check if Chart.js is loaded
- const chartJsLoaded = typeof Chart !== 'undefined';
-
- // Check if our custom functions exist
- const customFunctionsExist = typeof updateLLMChart === 'function' &&
- typeof updateSearchEngineChart === 'function';
-
- // Check if data loading function exists
- const dataLoadingExists = typeof loadStarReviews === 'function';
-
- return {
- chartJsLoaded,
- customFunctionsExist,
- dataLoadingExists,
- windowChart: !!window.Chart
- };
- });
-
- console.log('JavaScript test results:', jsTest);
-
- // Try to manually trigger data loading
- console.log('🎯 Attempting manual data loading...');
- const manualLoadResult = await page.evaluate(() => {
- if (typeof loadStarReviews === 'function') {
- try {
- loadStarReviews();
- return { success: true, message: 'Data loading triggered' };
- } catch (error) {
- return { success: false, error: error.message };
- }
- } else {
- return { success: false, error: 'loadStarReviews function not found' };
- }
- });
-
- console.log('Manual load result:', manualLoadResult);
-
- // Wait a bit more for any delayed rendering
- await new Promise(resolve => setTimeout(resolve, 2000));
-
- // Take a screenshot for visual debugging
- console.log('📸 Taking screenshot...');
- await page.screenshot({
- path: '/home/martin/code/LDR2/local-deep-research/star_reviews_debug.png',
- fullPage: true
- });
-
- // Final check of page content
- console.log('🏁 Final content check...');
- const pageContent = await page.evaluate(() => {
- const body = document.body;
- return {
- hasContent: body.children.length > 0,
- bodyText: body.innerText.length,
- innerHTML: body.innerHTML.length
- };
- });
-
- console.log('Page content:', pageContent);
-
- console.log('✅ Debug test completed successfully!');
-
- } catch (error) {
- console.error('❌ Test failed:', error.message);
- console.error('Stack trace:', error.stack);
- } finally {
- console.log('🔚 Closing browser...');
- await browser.close();
- }
-}
-
-// Run the test
-if (require.main === module) {
- debugStarReviews().catch(console.error);
-}
-
-module.exports = { debugStarReviews };