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
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
code-assistant-bot
/
utils
RSK World
code-assistant-bot
Code Assistant Bot - Python + Flask + OpenAI API + Code Generation + Debugging + Code Analysis + GitHub Integration
utils
  • __pycache__
  • __init__.py874 B
  • code_analyzer.py14.1 KB
  • code_comparator.py6 KB
  • code_converter.py15.4 KB
  • code_documenter.py12.8 KB
  • code_formatter.py10.3 KB
  • code_optimizer.py12.6 KB
  • code_reviewer.py11.7 KB
  • code_tester.py20.8 KB
  • github_integration.py14.4 KB
  • syntax_checker.py24.3 KB
code_documenter.pygithub_integration.py
utils/code_documenter.py
Raw Download
Find: Go to:
"""
Code Documentation Generator 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 re
import ast
from typing import Dict, List, Any, Optional

class CodeDocumenter:
    """
    Utility class for generating code documentation
    """
    
    def __init__(self):
        self.supported_languages = [
            'python', 'javascript', 'typescript', 'java', 'cpp', 'c',
            'csharp', 'php', 'ruby', 'go', 'rust'
        ]
    
    def generate_documentation(self, code: str, language: str, doc_style: str = 'standard') -> Dict[str, Any]:
        """
        Generate documentation for code
        """
        try:
            if language not in self.supported_languages:
                return {
                    'success': False,
                    'error': f'Language {language} not supported for documentation',
                    'documented_code': code
                }
            
            if language == 'python':
                return self._document_python(code, doc_style)
            elif language in ['javascript', 'typescript']:
                return self._document_javascript(code, doc_style)
            elif language == 'java':
                return self._document_java(code, doc_style)
            else:
                return self._document_generic(code, language, doc_style)
                
        except Exception as e:
            return {
                'success': False,
                'error': f'Documentation generation failed: {str(e)}',
                'documented_code': code
            }
    
    def _document_python(self, code: str, doc_style: str) -> Dict[str, Any]:
        """Generate Python documentation"""
        try:
            documented_code = code
            changes = []
            
            # Parse the code
            try:
                tree = ast.parse(code)
                
                # Find functions and classes without docstrings
                for node in ast.walk(tree):
                    if isinstance(node, ast.FunctionDef):
                        if not ast.get_docstring(node):
                            # Generate docstring
                            func_name = node.name
                            params = [arg.arg for arg in node.args.args]
                            
                            docstring = f'    """\n'
                            docstring += f'    {self._generate_function_description(func_name, params)}\n'
                            docstring += f'\n'
                            
                            if params:
                                docstring += f'    Args:\n'
                                for param in params:
                                    if param != 'self':
                                        docstring += f'        {param}: Description of {param}\n'
                            
                            # Check for return statement
                            has_return = any(isinstance(n, ast.Return) for n in ast.walk(node))
                            if has_return:
                                docstring += f'\n    Returns:\n'
                                docstring += f'        Description of return value\n'
                            
                            docstring += f'    """'
                            
                            # Find the line after function definition
                            func_line = node.lineno - 1
                            lines = documented_code.split('\n')
                            
                            # Insert docstring after function definition
                            if func_line < len(lines):
                                indent = len(lines[func_line]) - len(lines[func_line].lstrip())
                                docstring_lines = docstring.split('\n')
                                indented_docstring = '\n'.join([' ' * indent + line.lstrip() for line in docstring_lines])
                                
                                lines.insert(func_line + 1, indented_docstring)
                                documented_code = '\n'.join(lines)
                                changes.append(f'Added docstring to function {func_name}')
                    
                    elif isinstance(node, ast.ClassDef):
                        if not ast.get_docstring(node):
                            # Generate class docstring
                            class_name = node.name
                            docstring = f'    """\n'
                            docstring += f'    {self._generate_class_description(class_name)}\n'
                            docstring += f'    """'
                            
                            class_line = node.lineno - 1
                            lines = documented_code.split('\n')
                            
                            if class_line >= 0 and class_line < len(lines):
                                indent = len(lines[class_line]) - len(lines[class_line].lstrip())
                                docstring_lines = docstring.split('\n')
                                indented_docstring = '\n'.join([' ' * indent + line.lstrip() for line in docstring_lines])
                                
                                lines.insert(class_line + 1, indented_docstring)
                                documented_code = '\n'.join(lines)
                                changes.append(f'Added docstring to class {class_name}')
            
            except SyntaxError:
                # If parsing fails, add basic comments
                documented_code = self._add_basic_comments(code)
                changes.append('Added basic comments (code parsing failed)')
            
            return {
                'success': True,
                'documented_code': documented_code,
                'changes_made': changes if changes else ['Code already has documentation']
            }
            
        except Exception as e:
            return {
                'success': False,
                'error': f'Python documentation failed: {str(e)}',
                'documented_code': code
            }
    
    def _document_javascript(self, code: str, doc_style: str) -> Dict[str, Any]:
        """Generate JavaScript/TypeScript documentation"""
        try:
            documented_code = code
            changes = []
            
            # Find functions without JSDoc comments
            function_pattern = r'(function\s+(\w+)\s*\([^)]*\)|const\s+(\w+)\s*=\s*(?:\([^)]*\)|function\s*\([^)]*\))\s*=>)'
            
            def add_jsdoc(match):
                func_match = match.group(0)
                func_name = match.group(2) if match.lastindex >= 2 and match.group(2) else (match.group(3) if match.lastindex >= 3 and match.group(3) else 'function')
                
                # Extract parameters
                params_match = re.search(r'\(([^)]*)\)', func_match)
                params = [p.strip().split('=')[0].strip() for p in params_match.group(1).split(',') if p.strip()] if params_match and params_match.group(1) else []
                
                jsdoc = '/**\n'
                jsdoc += f' * {self._generate_function_description(func_name, params)}\n'
                
                if params:
                    for param in params:
                        if param:
                            jsdoc += f' * @param {{type}} {param} - Description of {param}\n'
                
                jsdoc += ' * @returns {type} Description of return value\n'
                jsdoc += ' */\n'
                
                changes.append(f'Added JSDoc to function {func_name}')
                return jsdoc + func_match
            
            documented_code = re.sub(function_pattern, add_jsdoc, documented_code)
            
            return {
                'success': True,
                'documented_code': documented_code,
                'changes_made': changes if changes else ['Code already has documentation']
            }
            
        except Exception as e:
            return {
                'success': False,
                'error': f'JavaScript documentation failed: {str(e)}',
                'documented_code': code
            }
    
    def _document_java(self, code: str, doc_style: str) -> Dict[str, Any]:
        """Generate Java documentation"""
        try:
            documented_code = code
            changes = []
            
            # Find methods without JavaDoc comments
            method_pattern = r'(public|private|protected)?\s*(static)?\s*(\w+)\s+(\w+)\s*\([^)]*\)'
            
            def add_javadoc(match):
                method_name = match.group(4)
                return_type = match.group(3)
                
                javadoc = '/**\n'
                javadoc += f' * {self._generate_function_description(method_name, [])}\n'
                javadoc += ' *\n'
                
                # Extract parameters
                params_match = re.search(r'\(([^)]*)\)', match.group(0))
                if params_match:
                    params = [p.strip().split()[1] if len(p.strip().split()) > 1 else p.strip() 
                             for p in params_match.group(1).split(',') if p.strip()]
                    for param in params:
                        javadoc += f' * @param {param} Description of {param}\n'
                
                javadoc += f' * @return Description of return value\n'
                javadoc += ' */\n'
                
                changes.append(f'Added JavaDoc to method {method_name}')
                return javadoc + match.group(0)
            
            documented_code = re.sub(method_pattern, add_javadoc, documented_code)
            
            return {
                'success': True,
                'documented_code': documented_code,
                'changes_made': changes if changes else ['Code already has documentation']
            }
            
        except Exception as e:
            return {
                'success': False,
                'error': f'Java documentation failed: {str(e)}',
                'documented_code': code
            }
    
    def _document_generic(self, code: str, language: str, doc_style: str) -> Dict[str, Any]:
        """Generic documentation for other languages"""
        try:
            documented_code = self._add_basic_comments(code)
            
            return {
                'success': True,
                'documented_code': documented_code,
                'changes_made': ['Added basic comments']
            }
        except Exception as e:
            return {
                'success': False,
                'error': f'Documentation failed: {str(e)}',
                'documented_code': code
            }
    
    def _generate_function_description(self, func_name: str, params: List[str]) -> str:
        """Generate a description for a function"""
        # Simple heuristic-based description generation
        if 'get' in func_name.lower():
            return f'Gets {func_name.replace("get", "").lower()}'
        elif 'set' in func_name.lower():
            return f'Sets {func_name.replace("set", "").lower()}'
        elif 'is' in func_name.lower() or 'has' in func_name.lower():
            return f'Checks if {func_name.lower()}'
        elif 'create' in func_name.lower() or 'make' in func_name.lower():
            return f'Creates {func_name.lower()}'
        elif 'delete' in func_name.lower() or 'remove' in func_name.lower():
            return f'Removes {func_name.lower()}'
        else:
            return f'Performs {func_name} operation'
    
    def _generate_class_description(self, class_name: str) -> str:
        """Generate a description for a class"""
        return f'Represents a {class_name.lower()}'
    
    def _add_basic_comments(self, code: str) -> str:
        """Add basic comments to code"""
        lines = code.split('\n')
        commented_lines = []
        
        for i, line in enumerate(lines):
            stripped = line.strip()
            
            # Add comment before function/class definitions
            if stripped.startswith(('def ', 'class ', 'function ', 'class ')):
                if i > 0 and not lines[i-1].strip().startswith('#'):
                    indent = len(line) - len(line.lstrip())
                    commented_lines.append(' ' * indent + f'# {stripped}')
                else:
                    commented_lines.append(line)
            else:
                commented_lines.append(line)
        
        return '\n'.join(commented_lines)
289 lines•12.8 KB
python
utils/github_integration.py
Raw Download
Find: Go to:
"""
GitHub Integration 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 requests
import json
from typing import Dict, List, Any, Optional

class GitHubIntegration:
    """
    Utility class for integrating with GitHub API
    """
    
    def __init__(self):
        self.base_url = "https://api.github.com"
        self.token = None  # Set this with GitHub personal access token for higher rate limits
        self.headers = {
            "Accept": "application/vnd.github.v3+json",
            "User-Agent": "Code-Assistant-Bot/1.0"
        }
        
        if self.token:
            self.headers["Authorization"] = f"token {self.token}"
    
    def search_repositories(self, query: str, language: Optional[str] = None, sort: str = "stars", order: str = "desc") -> Dict[str, Any]:
        """
        Search GitHub repositories
        """
        try:
            # Build search query
            search_query = query
            if language:
                search_query += f" language:{language}"
            
            # Make API request
            url = f"{self.base_url}/search/repositories"
            params = {
                "q": search_query,
                "sort": sort,
                "order": order,
                "per_page": 20
            }
            
            response = requests.get(url, headers=self.headers, params=params)
            response.raise_for_status()
            
            data = response.json()
            
            # Process results
            repositories = []
            for repo in data.get("items", []):
                repositories.append({
                    "id": repo["id"],
                    "name": repo["name"],
                    "full_name": repo["full_name"],
                    "description": repo["description"],
                    "html_url": repo["html_url"],
                    "clone_url": repo["clone_url"],
                    "ssh_url": repo["ssh_url"],
                    "stars": repo["stargazers_count"],
                    "forks": repo["forks_count"],
                    "language": repo["language"],
                    "updated_at": repo["updated_at"],
                    "created_at": repo["created_at"],
                    "size": repo["size"],
                    "open_issues": repo["open_issues_count"],
                    "watchers": repo.get("watchers_count", 0),
                    "license": repo.get("license", {}).get("name") if repo.get("license") else None,
                    "topics": repo.get("topics", []),
                    "owner": {
                        "login": repo["owner"]["login"],
                        "type": repo["owner"]["type"],
                        "avatar_url": repo["owner"]["avatar_url"]
                    }
                })
            
            return {
                "total_count": data.get("total_count", 0),
                "incomplete_results": data.get("incomplete_results", False),
                "repositories": repositories
            }
            
        except requests.exceptions.RequestException as e:
            return {
                "error": f"GitHub API request failed: {str(e)}",
                "repositories": []
            }
        except Exception as e:
            return {
                "error": f"Unexpected error: {str(e)}",
                "repositories": []
            }
    
    def get_repository_details(self, owner: str, repo: str) -> Dict[str, Any]:
        """
        Get detailed information about a specific repository
        """
        try:
            url = f"{self.base_url}/repos/{owner}/{repo}"
            response = requests.get(url, headers=self.headers)
            response.raise_for_status()
            
            data = response.json()
            
            return {
                "id": data["id"],
                "name": data["name"],
                "full_name": data["full_name"],
                "description": data["description"],
                "html_url": data["html_url"],
                "clone_url": data["clone_url"],
                "ssh_url": data["ssh_url"],
                "stars": data["stargazers_count"],
                "forks": data["forks_count"],
                "language": data["language"],
                "updated_at": data["updated_at"],
                "created_at": data["created_at"],
                "pushed_at": data["pushed_at"],
                "size": data["size"],
                "open_issues": data["open_issues_count"],
                "watchers": data["watchers_count"],
                "network_count": data["network_count"],
                "subscribers_count": data["subscribers_count"],
                "license": data.get("license", {}).get("name") if data.get("license") else None,
                "topics": data.get("topics", []),
                "has_issues": data["has_issues"],
                "has_projects": data["has_projects"],
                "has_wiki": data["has_wiki"],
                "has_pages": data["has_pages"],
                "has_downloads": data["has_downloads"],
                "archived": data["archived"],
                "disabled": data["disabled"],
                "visibility": data.get("visibility", "public"),
                "default_branch": data["default_branch"],
                "owner": {
                    "login": data["owner"]["login"],
                    "id": data["owner"]["id"],
                    "type": data["owner"]["type"],
                    "avatar_url": data["owner"]["avatar_url"]
                }
            }
            
        except requests.exceptions.RequestException as e:
            return {"error": f"GitHub API request failed: {str(e)}"}
        except Exception as e:
            return {"error": f"Unexpected error: {str(e)}"}
    
    def get_repository_contents(self, owner: str, repo: str, path: str = "", ref: Optional[str] = None) -> Dict[str, Any]:
        """
        Get contents of a repository directory or file
        """
        try:
            url = f"{self.base_url}/repos/{owner}/{repo}/contents/{path}"
            params = {}
            if ref:
                params["ref"] = ref
            
            response = requests.get(url, headers=self.headers, params=params)
            response.raise_for_status()
            
            data = response.json()
            
            if isinstance(data, list):
                # Directory contents
                contents = []
                for item in data:
                    contents.append({
                        "name": item["name"],
                        "path": item["path"],
                        "type": item["type"],
                        "size": item.get("size", 0),
                        "download_url": item.get("download_url"),
                        "html_url": item.get("html_url"),
                        "git_url": item.get("git_url"),
                        "_links": item.get("_links", {})
                    })
                return {"type": "dir", "contents": contents}
            else:
                # File contents
                if data["type"] == "file":
                    import base64
                    content = base64.b64decode(data["content"]).decode('utf-8')
                    return {
                        "type": "file",
                        "name": data["name"],
                        "path": data["path"],
                        "size": data["size"],
                        "content": content,
                        "encoding": data["encoding"],
                        "download_url": data.get("download_url"),
                        "html_url": data.get("html_url")
                    }
                else:
                    return {"type": data["type"], "name": data["name"]}
            
        except requests.exceptions.RequestException as e:
            return {"error": f"GitHub API request failed: {str(e)}"}
        except Exception as e:
            return {"error": f"Unexpected error: {str(e)}"}
    
    def get_repository_commits(self, owner: str, repo: str, sha: Optional[str] = None, per_page: int = 20) -> Dict[str, Any]:
        """
        Get commit history for a repository
        """
        try:
            url = f"{self.base_url}/repos/{owner}/{repo}/commits"
            params = {"per_page": per_page}
            if sha:
                params["sha"] = sha
            
            response = requests.get(url, headers=self.headers, params=params)
            response.raise_for_status()
            
            data = response.json()
            
            commits = []
            for commit in data:
                commits.append({
                    "sha": commit["sha"],
                    "message": commit["commit"]["message"],
                    "author": {
                        "name": commit["commit"]["author"]["name"],
                        "email": commit["commit"]["author"]["email"],
                        "date": commit["commit"]["author"]["date"]
                    },
                    "committer": {
                        "name": commit["commit"]["committer"]["name"],
                        "email": commit["commit"]["committer"]["email"],
                        "date": commit["commit"]["committer"]["date"]
                    },
                    "url": commit["url"],
                    "html_url": commit["html_url"],
                    "parents": [parent["sha"] for parent in commit.get("parents", [])]
                })
            
            return {"commits": commits}
            
        except requests.exceptions.RequestException as e:
            return {"error": f"GitHub API request failed: {str(e)}"}
        except Exception as e:
            return {"error": f"Unexpected error: {str(e)}"}
    
    def get_repository_languages(self, owner: str, repo: str) -> Dict[str, Any]:
        """
        Get language breakdown for a repository
        """
        try:
            url = f"{self.base_url}/repos/{owner}/{repo}/languages"
            response = requests.get(url, headers=self.headers)
            response.raise_for_status()
            
            data = response.json()
            
            # Calculate percentages
            total_bytes = sum(data.values())
            languages = {}
            for language, bytes_count in data.items():
                languages[language] = {
                    "bytes": bytes_count,
                    "percentage": round((bytes_count / total_bytes) * 100, 2) if total_bytes > 0 else 0
                }
            
            return {
                "languages": languages,
                "total_bytes": total_bytes
            }
            
        except requests.exceptions.RequestException as e:
            return {"error": f"GitHub API request failed: {str(e)}"}
        except Exception as e:
            return {"error": f"Unexpected error: {str(e)}"}
    
    def get_repository_contributors(self, owner: str, repo: str) -> Dict[str, Any]:
        """
        Get contributors for a repository
        """
        try:
            url = f"{self.base_url}/repos/{owner}/{repo}/contributors"
            response = requests.get(url, headers=self.headers)
            response.raise_for_status()
            
            data = response.json()
            
            contributors = []
            for contributor in data:
                contributors.append({
                    "login": contributor["login"],
                    "id": contributor["id"],
                    "type": contributor["type"],
                    "contributions": contributor["contributions"],
                    "avatar_url": contributor["avatar_url"],
                    "html_url": contributor["html_url"]
                })
            
            return {"contributors": contributors}
            
        except requests.exceptions.RequestException as e:
            return {"error": f"GitHub API request failed: {str(e)}"}
        except Exception as e:
            return {"error": f"Unexpected error: {str(e)}"}
    
    def search_code(self, query: str, language: Optional[str] = None, sort: str = "indexed", order: str = "desc") -> Dict[str, Any]:
        """
        Search for code across GitHub
        """
        try:
            # Build search query
            search_query = query
            if language:
                search_query += f" language:{language}"
            
            # Make API request
            url = f"{self.base_url}/search/code"
            params = {
                "q": search_query,
                "sort": sort,
                "order": order,
                "per_page": 20
            }
            
            response = requests.get(url, headers=self.headers, params=params)
            response.raise_for_status()
            
            data = response.json()
            
            # Process results
            code_items = []
            for item in data.get("items", []):
                code_items.append({
                    "name": item["name"],
                    "path": item["path"],
                    "sha": item["sha"],
                    "url": item["url"],
                    "git_url": item["git_url"],
                    "html_url": item["html_url"],
                    "repository": {
                        "id": item["repository"]["id"],
                        "name": item["repository"]["name"],
                        "full_name": item["repository"]["full_name"],
                        "html_url": item["repository"]["html_url"]
                    },
                    "score": item["score"]
                })
            
            return {
                "total_count": data.get("total_count", 0),
                "incomplete_results": data.get("incomplete_results", False),
                "items": code_items
            }
            
        except requests.exceptions.RequestException as e:
            return {
                "error": f"GitHub API request failed: {str(e)}",
                "items": []
            }
        except Exception as e:
            return {
                "error": f"Unexpected error: {str(e)}",
                "items": []
            }
366 lines•14.4 KB
python
🚀 Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work ❤️

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