help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
code-assistant-bot
/
utils
/
__pycache__
RSK World
code-assistant-bot
Code Assistant Bot - Python + Flask + OpenAI API + Code Generation + Debugging + Code Analysis + GitHub Integration
__pycache__
  • code_analyzer.cpython-313.pyc17.6 KB
  • code_comparator.cpython-313.pyc6.5 KB
  • code_documenter.cpython-313.pyc14 KB
  • code_formatter.cpython-313.pyc9.9 KB
  • code_reviewer.cpython-313.pyc10.5 KB
  • github_integration.cpython-313.pyc14.2 KB
  • syntax_checker.cpython-313.pyc21.6 KB
code_comparator.pycode_documenter.cpython-313.pyc
utils/code_comparator.py
Raw Download
Find: Go to:
"""
Code Comparator Utility for Code Assistant Bot
Author: RSK World (https://rskworld.in)
Founder: Molla Samser
Designer & Tester: Rima Khatun
Contact: help@rskworld.in, +91 93305 39277
Year: 2026
"""

import difflib
from typing import Dict, List, Any, Tuple

class CodeComparator:
    """
    Utility class for comparing code differences
    """
    
    def __init__(self):
        pass
    
    def compare_code(self, code1: str, code2: str, language: str = 'auto') -> Dict[str, Any]:
        """
        Compare two code snippets and show differences
        """
        try:
            lines1 = code1.splitlines(keepends=True)
            lines2 = code2.splitlines(keepends=True)
            
            # Use difflib to find differences
            diff = list(difflib.unified_diff(
                lines1, lines2,
                fromfile='Original',
                tofile='Modified',
                lineterm=''
            ))
            
            # Calculate statistics
            added_lines = sum(1 for line in diff if line.startswith('+') and not line.startswith('+++'))
            removed_lines = sum(1 for line in diff if line.startswith('-') and not line.startswith('---'))
            modified_blocks = self._count_modified_blocks(diff)
            
            # Generate HTML diff
            html_diff = self._generate_html_diff(lines1, lines2)
            
            # Generate side-by-side comparison
            side_by_side = self._generate_side_by_side(lines1, lines2)
            
            return {
                'success': True,
                'diff': diff,
                'html_diff': html_diff,
                'side_by_side': side_by_side,
                'statistics': {
                    'total_lines_original': len(lines1),
                    'total_lines_modified': len(lines2),
                    'lines_added': added_lines,
                    'lines_removed': removed_lines,
                    'lines_unchanged': len(lines1) - removed_lines,
                    'modified_blocks': modified_blocks,
                    'similarity_ratio': difflib.SequenceMatcher(None, code1, code2).ratio()
                }
            }
            
        except Exception as e:
            return {
                'success': False,
                'error': f'Code comparison failed: {str(e)}',
                'diff': [],
                'statistics': {}
            }
    
    def _count_modified_blocks(self, diff: List[str]) -> int:
        """Count number of modified blocks in diff"""
        blocks = 0
        in_block = False
        
        for line in diff:
            if line.startswith('@@'):
                if in_block:
                    blocks += 1
                in_block = True
            elif line.startswith(' ') and in_block:
                in_block = False
        
        if in_block:
            blocks += 1
        
        return blocks
    
    def _generate_html_diff(self, lines1: List[str], lines2: List[str]) -> str:
        """Generate HTML formatted diff"""
        diff = list(difflib.unified_diff(
            lines1, lines2,
            fromfile='Original',
            tofile='Modified',
            lineterm=''
        ))
        
        html = '<div class="diff-container">\n'
        html += '<pre class="diff">\n'
        
        for line in diff:
            if line.startswith('+++') or line.startswith('---'):
                html += f'<span class="diff-header">{line}</span>\n'
            elif line.startswith('@@'):
                html += f'<span class="diff-hunk">{line}</span>\n'
            elif line.startswith('+'):
                html += f'<span class="diff-added">{line}</span>\n'
            elif line.startswith('-'):
                html += f'<span class="diff-removed">{line}</span>\n'
            else:
                html += f'<span class="diff-context">{line}</span>\n'
        
        html += '</pre>\n'
        html += '</div>\n'
        
        return html
    
    def _generate_side_by_side(self, lines1: List[str], lines2: List[str]) -> List[Dict[str, Any]]:
        """Generate side-by-side comparison"""
        matcher = difflib.SequenceMatcher(None, lines1, lines2)
        comparison = []
        
        for tag, i1, i2, j1, j2 in matcher.get_opcodes():
            if tag == 'equal':
                for i in range(i1, i2):
                    comparison.append({
                        'type': 'equal',
                        'left': lines1[i],
                        'right': lines2[i1 + (i - i1)],
                        'line_number_left': i + 1,
                        'line_number_right': i1 + (i - i1) + 1
                    })
            elif tag == 'delete':
                for i in range(i1, i2):
                    comparison.append({
                        'type': 'delete',
                        'left': lines1[i],
                        'right': '',
                        'line_number_left': i + 1,
                        'line_number_right': None
                    })
            elif tag == 'insert':
                for j in range(j1, j2):
                    comparison.append({
                        'type': 'insert',
                        'left': '',
                        'right': lines2[j],
                        'line_number_left': None,
                        'line_number_right': j + 1
                    })
            elif tag == 'replace':
                max_len = max(i2 - i1, j2 - j1)
                for k in range(max_len):
                    comparison.append({
                        'type': 'replace',
                        'left': lines1[i1 + k] if k < (i2 - i1) else '',
                        'right': lines2[j1 + k] if k < (j2 - j1) else '',
                        'line_number_left': i1 + k + 1 if k < (i2 - i1) else None,
                        'line_number_right': j1 + k + 1 if k < (j2 - j1) else None
                    })
        
        return comparison
164 lines•6 KB
python
code_documenter.cpython-313.pyc

This file cannot be displayed in the browser.

Download File

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer