#!/usr/bin/env python3 """ BibGuard Gradio Web Application A web interface for checking bibliography and LaTeX quality. """ import gradio as gr import tempfile import shutil from pathlib import Path from typing import Optional, Tuple import base64 from src.parsers import BibParser, TexParser from src.fetchers import ArxivFetcher, CrossRefFetcher, SemanticScholarFetcher, OpenAlexFetcher, DBLPFetcher from src.analyzers import MetadataComparator, UsageChecker, DuplicateDetector from src.report.generator import ReportGenerator, EntryReport from src.config.yaml_config import BibGuardConfig, FilesConfig, BibliographyConfig, SubmissionConfig, OutputConfig, WorkflowStep from src.config.workflow import WorkflowConfig, WorkflowStep as WFStep, get_default_workflow from src.checkers import CHECKER_REGISTRY from src.report.line_report import LineByLineReportGenerator from app_helper import fetch_and_compare_with_workflow # Custom CSS for better Markdown rendering CUSTOM_CSS = """ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap'); * { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; } """ WELCOME_HTML = """

👋 Welcome to BibGuard

Ensure your academic paper is flawless. Upload your .bib and .tex files on the left and click "Check Now".

⚠️ Metadata Check Defaults "🔍 Metadata" is disabled by default. It verifies your entries against ArXiv/DBLP/Crossref but takes time (1-3 mins) to fetch data. Enable it if you want strict verification.
🚀 Go Pro with Local Version LLM-based context relevance checking (is this citation actually relevant?) is excluded here. Clone the GitHub repo to use the full power with your API key.

📊 Understanding Your Reports

📚 Bibliography Validates metadata fields, detects duplicates, and checks citation counts.
📝 LaTeX Quality Syntax check, caption validation, acronym consistency, and style suggestions.
📋 Line-by-Line Maps every issue found directly to the line number in your source file.
""" CUSTOM_CSS += """ /* Global Reset */ body, gradio-app { overflow: hidden !important; /* Prevent double scrollbars on the page */ } .gradio-container { max-width: none !important; width: 100% !important; /* height: 100vh !important; <-- Removed to prevent iframe infinite loop */ padding: 0 !important; margin: 0 !important; } /* Header Styling */ .app-header { padding: 20px; background: white; border-bottom: 1px solid #e5e7eb; } /* Sidebar Styling */ .app-sidebar { height: auto !important; max-height: calc(100vh - 100px) !important; overflow-y: auto !important; padding: 20px !important; border-right: 1px solid #e5e7eb; } /* Main Content Area */ .app-content { height: auto !important; max-height: calc(100vh - 100px) !important; padding: 0 !important; } /* The Magic Scroll Container - Clean and Explicit */ .scrollable-report-area { /* Fixed height relative to viewport can cause loops in Spaces */ max-height: 800px !important; height: auto !important; min-height: 500px !important; overflow-y: auto !important; padding: 24px; background-color: #f9fafb; border: 1px solid #e5e7eb; border-radius: 8px; margin-top: 10px; } /* Report Card Styling */ .report-card { background: white; border-radius: 12px; padding: 24px; margin-bottom: 16px; /* Spacing between cards */ box-shadow: 0 1px 3px rgba(0,0,0,0.1); border: 1px solid #e5e7eb; transition: transform 0.2s, box-shadow 0.2s; } .report-card:hover { box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); transform: translateY(-2px); } /* Card Internals */ .card-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 16px; padding-bottom: 16px; border-bottom: 1px solid #f3f4f6; } .card-title { font-size: 1.1em; font-weight: 600; color: #111827; margin: 0 0 4px 0; } .card-subtitle { font-size: 0.9em; color: #6b7280; font-family: monospace; } .card-content { font-size: 0.95em; color: #374151; line-height: 1.5; } /* Badges */ .badge { display: inline-flex; align-items: center; padding: 4px 10px; border-radius: 9999px; font-size: 0.8em; font-weight: 500; } .badge-success { background-color: #dcfce7; color: #166534; } .badge-warning { background-color: #fef9c3; color: #854d0e; } .badge-error { background-color: #fee2e2; color: #991b1b; } .badge-info { background-color: #dbeafe; color: #1e40af; } .badge-neutral { background-color: #f3f4f6; color: #4b5563; } /* Stats Grid */ .stats-container { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 16px; margin-bottom: 24px; } .stat-card { padding: 16px; border-radius: 12px; color: white; text-align: center; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); } .stat-value { font-size: 1.8em; font-weight: 700; } .stat-label { font-size: 0.9em; opacity: 0.9; } /* Detail Grid - Flexbox for better filling */ .detail-grid { display: flex; flex-wrap: wrap; gap: 12px; margin-bottom: 16px; width: 100%; } .detail-item { background: #f9fafb; padding: 10px 12px; border-radius: 8px; border: 1px solid #f3f4f6; /* Flex sizing: grow, shrink, min-basis */ flex: 1 1 160px; min-width: 0; /* Important for word-break to work in flex children */ /* Layout control */ display: flex; flex-direction: column; /* Height constraint to prevent one huge card from stretching the row */ max-height: 100px; overflow-y: auto; } /* Custom scrollbar for detail items */ .detail-item::-webkit-scrollbar { width: 4px; } .detail-item::-webkit-scrollbar-thumb { background-color: #d1d5db; border-radius: 4px; } .detail-label { font-size: 0.75em; color: #6b7280; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 2px; position: sticky; top: 0; background: #f9fafb; /* Maintain bg on scroll */ z-index: 1; } .detail-value { font-weight: 500; color: #1f2937; font-size: 0.9em; line-height: 1.4; word-break: break-word; /* Fix overflow */ overflow-wrap: break-word; } border: 1px solid #e5e7eb; transition: all 0.2s; } .report-card:hover { box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05); } /* Card Header */ .card-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 12px; border-bottom: 1px solid #f3f4f6; padding-bottom: 12px; } .card-title { font-size: 1.1em; font-weight: 600; color: #1f2937; margin: 0; } .card-subtitle { font-size: 0.9em; color: #6b7280; margin-top: 4px; } /* Status Badges */ .badge { display: inline-flex; align-items: center; padding: 4px 10px; border-radius: 9999px; font-size: 0.8em; font-weight: 500; } .badge-success { background-color: #dcfce7; color: #166534; } .badge-warning { background-color: #fef9c3; color: #854d0e; } .badge-error { background-color: #fee2e2; color: #991b1b; } .badge-info { background-color: #dbeafe; color: #1e40af; } .badge-neutral { background-color: #f3f4f6; color: #374151; } /* Content Styling */ .card-content { font-size: 15px; color: #374151; line-height: 1.6; } .card-content code { background-color: #f3f4f6; padding: 2px 6px; border-radius: 4px; font-family: monospace; font-size: 0.9em; color: #c2410c; } /* Grid for details */ .detail-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px; margin-top: 12px; } .detail-item { background: #f9fafb; padding: 10px; border-radius: 6px; } .detail-label { font-size: 0.8em; color: #6b7280; text-transform: uppercase; letter-spacing: 0.05em; } .detail-value { font-weight: 500; color: #111827; } /* Summary Stats */ .stats-container { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; margin-bottom: 24px; } .stat-card { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 12px; text-align: center; box-shadow: 0 4px 6px rgba(102, 126, 234, 0.25); } .stat-value { font-size: 2em; font-weight: 700; } .stat-label { font-size: 0.9em; opacity: 0.9; margin-top: 4px; } /* Button styling */ .primary-btn { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important; border: none !important; font-weight: 600 !important; } /* Tab styling */ .tab-nav button { font-weight: 500 !important; font-size: 15px !important; } """ def create_config_from_ui( check_metadata: bool, check_usage: bool, check_duplicates: bool, check_preprint_ratio: bool, caption: bool, reference: bool, formatting: bool, equation: bool, ai_artifacts: bool, sentence: bool, consistency: bool, acronym: bool, number: bool, citation_quality: bool, anonymization: bool ) -> BibGuardConfig: """Create a BibGuardConfig from UI settings.""" config = BibGuardConfig() config.bibliography = BibliographyConfig( check_metadata=check_metadata, check_usage=check_usage, check_duplicates=check_duplicates, check_preprint_ratio=check_preprint_ratio, check_relevance=False # Disabled for web ) config.submission = SubmissionConfig( caption=caption, reference=reference, formatting=formatting, equation=equation, ai_artifacts=ai_artifacts, sentence=sentence, consistency=consistency, acronym=acronym, number=number, citation_quality=citation_quality, anonymization=anonymization ) config.output = OutputConfig(quiet=True, minimal_verified=False) return config def generate_bibliography_html(report_gen: ReportGenerator, entries: list) -> str: """Generate HTML content for bibliography report.""" html = ['
'] # 1. Summary Stats total = len(entries) verified = sum(1 for e in report_gen.entries if e.comparison and e.comparison.is_match) used = sum(1 for e in report_gen.entries if e.usage and e.usage.is_used) html.append('
') html.append(f'
{total}
Total Entries
') html.append(f'
{verified}
Verified
') html.append(f'
{used}
Used in Text
') html.append('
') # 2. Entries for report in report_gen.entries: entry = report.entry status_badges = [] # Metadata Status if report.comparison: if report.comparison.is_match: status_badges.append('✓ Verified') if report.comparison.source: status_badges.append(f'{report.comparison.source.upper()}') else: status_badges.append('⚠ Metadata Mismatch') else: status_badges.append('No Metadata Check') # Usage Status if report.usage: if report.usage.is_used: status_badges.append(f'Used: {report.usage.usage_count}x') else: status_badges.append('Unused') # Build Card html.append(f'''

{entry.title or "No Title"}

{entry.key} • {entry.year} • {entry.entry_type}
{" ".join(status_badges)}
{ (lambda e: "".join([ f'
{k}
{v}
' for k, v in filter(None, [ ("Authors", e.author or "N/A"), ("Venue", e.journal or e.booktitle or e.publisher or "N/A"), ("DOI", e.doi) if e.doi else None, ("ArXiv", e.arxiv_id) if e.arxiv_id and not e.doi else None, ("Volume/Pages", f"{'Vol.'+e.volume if e.volume else ''} {'pp.'+e.pages if e.pages else ''}".strip()) if e.volume or e.pages else None, ("URL", f'Link') if e.url else None ]) ]))(entry) }
''') # Add issues if any issues = [] if report.comparison and not report.comparison.is_match: # Add main message derived from match status if report.comparison.issues: for issue in report.comparison.issues: issues.append(f'
• {issue}
') else: issues.append(f'
• Verification failed
') if issues: html.append('
') html.append("".join(issues)) html.append('
') html.append('
') # Close card-content and report-card html.append('
') # Close container return "".join(html) def generate_latex_html(results: list) -> str: """Generate HTML for LaTeX quality check.""" from src.checkers import CheckSeverity html = ['
'] # Stats errors = sum(1 for r in results if r.severity == CheckSeverity.ERROR) warnings = sum(1 for r in results if r.severity == CheckSeverity.WARNING) infos = sum(1 for r in results if r.severity == CheckSeverity.INFO) html.append('
') html.append(f'
{errors}
Errors
') html.append(f'
{warnings}
Warnings
') html.append(f'
{infos}
Suggestions
') html.append('
') if not results: html.append('
✅ No issues found in LaTeX code!
') else: # Group by Checker results.sort(key=lambda x: x.checker_name) current_checker = None for result in results: badge_class = "badge-neutral" if result.severity == CheckSeverity.ERROR: badge_class = "badge-error" elif result.severity == CheckSeverity.WARNING: badge_class = "badge-warning" elif result.severity == CheckSeverity.INFO: badge_class = "badge-info" html.append(f'''

{result.checker_name}

Line {result.line_number}
{result.severity.name}
{result.message} {f'
{result.line_content}
' if result.line_content else ''} {f'
💡 Suggestion: {result.suggestion}
' if result.suggestion else ''}
''') html.append('
') return "".join(html) def generate_line_html(content: str, results: list) -> str: """Generate HTML for Line-by-Line report.""" # Build a dictionary of line_number -> list of issues issues_by_line = {} for r in results: if r.line_number not in issues_by_line: issues_by_line[r.line_number] = [] issues_by_line[r.line_number].append(r) lines = content.split('\n') html = ['
'] html.append('
Issues are mapped to specific lines below.
') for i, line in enumerate(lines, 1): if i in issues_by_line: # Highlight this line line_issues = issues_by_line[i] html.append(f'''
Line {i}
{line}
''') for issue in line_issues: html.append(f'
• {issue.message}
') html.append('
') html.append('
') return "".join(html) def run_check( bib_file, tex_file, check_metadata: bool, check_usage: bool, check_duplicates: bool, check_preprint_ratio: bool, caption: bool, reference: bool, formatting: bool, equation: bool, ai_artifacts: bool, sentence: bool, consistency: bool, acronym: bool, number: bool, citation_quality: bool, anonymization: bool, progress=gr.Progress() ) -> Tuple[str, str, str]: """Run BibGuard checks and return three reports.""" if bib_file is None or tex_file is None: return ( "⚠️ Please upload both `.bib` and `.tex` files.", "⚠️ Please upload both `.bib` and `.tex` files.", "⚠️ Please upload both `.bib` and `.tex` files." ) try: # Create config from UI config = create_config_from_ui( check_metadata, check_usage, check_duplicates, check_preprint_ratio, caption, reference, formatting, equation, ai_artifacts, sentence, consistency, acronym, number, citation_quality, anonymization ) # Get file paths from uploaded files bib_path = bib_file.name tex_path = tex_file.name # Read tex content for checkers tex_content = Path(tex_path).read_text(encoding='utf-8', errors='replace') # Parse files bib_parser = BibParser() entries = bib_parser.parse_file(bib_path) tex_parser = TexParser() tex_parser.parse_file(tex_path) bib_config = config.bibliography # Initialize components arxiv_fetcher = None crossref_fetcher = None semantic_scholar_fetcher = None openalex_fetcher = None dblp_fetcher = None comparator = None usage_checker = None duplicate_detector = None if bib_config.check_metadata: arxiv_fetcher = ArxivFetcher() semantic_scholar_fetcher = SemanticScholarFetcher() openalex_fetcher = OpenAlexFetcher() dblp_fetcher = DBLPFetcher() crossref_fetcher = CrossRefFetcher() comparator = MetadataComparator() if bib_config.check_usage: usage_checker = UsageChecker(tex_parser) if bib_config.check_duplicates: duplicate_detector = DuplicateDetector() # Initialize report generator report_gen = ReportGenerator( minimal_verified=False, check_preprint_ratio=bib_config.check_preprint_ratio, preprint_warning_threshold=bib_config.preprint_warning_threshold ) report_gen.set_metadata([bib_file.name], [tex_file.name]) # Run submission quality checks progress(0.2, desc="Running LaTeX quality checks...") submission_results = [] enabled_checkers = config.submission.get_enabled_checkers() for checker_name in enabled_checkers: if checker_name in CHECKER_REGISTRY: checker = CHECKER_REGISTRY[checker_name]() results = checker.check(tex_content, {}) for r in results: r.file_path = tex_file.name submission_results.extend(results) report_gen.set_submission_results(submission_results, None) # Check for duplicates if bib_config.check_duplicates and duplicate_detector: duplicate_groups = duplicate_detector.find_duplicates(entries) report_gen.set_duplicate_groups(duplicate_groups) # Check missing citations if bib_config.check_usage and usage_checker: missing = usage_checker.get_missing_entries(entries) report_gen.set_missing_citations(missing) # Build workflow workflow_config = get_default_workflow() # Process entries progress(0.3, desc="Processing bibliography entries...") total_entries = len(entries) for i, entry in enumerate(entries): progress(0.3 + 0.5 * (i / total_entries), desc=f"Checking: {entry.key}") # Check usage usage_result = None if usage_checker: usage_result = usage_checker.check_usage(entry) # Fetch and compare metadata comparison_result = None if bib_config.check_metadata and comparator: comparison_result = fetch_and_compare_with_workflow( entry, workflow_config, arxiv_fetcher, crossref_fetcher, semantic_scholar_fetcher, openalex_fetcher, dblp_fetcher, comparator ) # Create entry report entry_report = EntryReport( entry=entry, comparison=comparison_result, usage=usage_result, evaluations=[] ) report_gen.add_entry_report(entry_report) progress(0.85, desc="Generating structured reports...") # Generate Bibliography HTML Report bib_report = generate_bibliography_html(report_gen, entries) # Generate LaTeX Quality HTML Report latex_report = generate_latex_html(submission_results) # Generate Line-by-Line HTML Report line_report = "" if submission_results: line_report = generate_line_html(tex_content, submission_results) else: line_report = '
No issues to display line-by-line.
' progress(1.0, desc="Done!") return bib_report, latex_report, line_report except Exception as e: error_msg = f"❌ Error: {str(e)}" import traceback error_msg += f"\n\n```\n{traceback.format_exc()}\n```" return error_msg, error_msg, error_msg def create_app(): """Create and configure the Gradio app.""" # Load icon as base64 icon_html = "" try: icon_path = Path("assets/icon-192.png") if icon_path.exists(): with open(icon_path, "rb") as f: encoding = base64.b64encode(f.read()).decode() icon_html = f'BibGuard' else: icon_html = '📚' except Exception: icon_html = '📚' with gr.Blocks(title="BibGuard - Bibliography & LaTeX Quality Checker") as app: # Header with icon with gr.Row(elem_classes=["app-header"]): gr.HTML(f"""
{icon_html}

BibGuard

Bibliography & LaTeX Quality Checker

""") with gr.Row(elem_classes=["app-body"]): # Left column: Upload & Settings with gr.Column(scale=1, min_width=280, elem_classes=["app-sidebar"]): gr.Markdown("### 📁 Upload Files") bib_file = gr.File( label="Bibliography (.bib)", file_types=[".bib"], file_count="single" ) tex_file = gr.File( label="LaTeX Source (.tex)", file_types=[".tex"], file_count="single" ) # Check options in grid layout gr.Markdown("#### ⚙️ Options") with gr.Row(): check_metadata = gr.Checkbox(label="🔍 Metadata", value=False) check_usage = gr.Checkbox(label="📊 Usage", value=True) with gr.Row(): check_duplicates = gr.Checkbox(label="👯 Duplicates", value=True) check_preprint_ratio = gr.Checkbox(label="📄 Preprints", value=True) with gr.Row(): caption = gr.Checkbox(label="🖼️ Captions", value=True) reference = gr.Checkbox(label="🔗 References", value=True) with gr.Row(): formatting = gr.Checkbox(label="✨ Formatting", value=True) equation = gr.Checkbox(label="🔢 Equations", value=True) with gr.Row(): ai_artifacts = gr.Checkbox(label="🤖 AI Artifacts", value=True) sentence = gr.Checkbox(label="📝 Sentences", value=True) with gr.Row(): consistency = gr.Checkbox(label="🔄 Consistency", value=True) acronym = gr.Checkbox(label="🔤 Acronyms", value=True) with gr.Row(): number = gr.Checkbox(label="🔢 Numbers", value=True) citation_quality = gr.Checkbox(label="📚 Citations", value=True) with gr.Row(): anonymization = gr.Checkbox(label="🎭 Anonymization", value=True) run_btn = gr.Button("🔍 Check Now", variant="primary", size="lg") gr.HTML("""
GitHub

Developed with ❤️ for researchers

""") # Right column: Reports with gr.Column(scale=4, elem_classes=["app-content"]): with gr.Tabs(): with gr.Tab("📚 Bibliography Report"): bib_report = gr.HTML( value=WELCOME_HTML, elem_classes=["report-panel"] ) with gr.Tab("📝 LaTeX Quality"): latex_report = gr.HTML( value=WELCOME_HTML, elem_classes=["report-panel"] ) with gr.Tab("📋 Line-by-Line"): line_report = gr.HTML( value=WELCOME_HTML, elem_classes=["report-panel"] ) # Event handling run_btn.click( fn=run_check, inputs=[ bib_file, tex_file, check_metadata, check_usage, check_duplicates, check_preprint_ratio, caption, reference, formatting, equation, ai_artifacts, sentence, consistency, acronym, number, citation_quality, anonymization ], outputs=[bib_report, latex_report, line_report] ) return app # Create the app app = create_app() if __name__ == "__main__": app.launch( favicon_path="assets/icon-192.png", show_error=True, css=CUSTOM_CSS, theme=gr.themes.Soft() )