from flask import Flask, render_template_string, request, jsonify import requests from collections import Counter import re app = Flask(__name__) # HTML template (simplified version of your provided HTML) HTML_TEMPLATE = ''' AI Issue Resolver Pro

AI Issue Resolver Pro

Collaborative Issue Resolution Powered by AI

Status updates appear here... Idle tasks may run in background.
📋 Issue Board
💻 Resolution Studio
📈 Analytics
Open Issues
ID Title Severity Cluster
Issue Severity Distribution
👥 Active Collaborators
User_abc1: Viewing Issue #123
User_def2: Editing Issue #124
User_ghi3: Idle
Selected Issue Details

Select an issue from the 'Issue Board' tab.

🛠️ AI Assistance Tools
AI Output

AI suggestions and patches will appear here...

Collaborative Code Editor (Context-Aware)

Warning

Real-time collaborative editing is experimental and may lose data with simultaneous edits. Use with caution and save work frequently!

# Select an issue to load relevant code context.

Repository Analytics

Issue Severity Distribution

Issue Cluster Analysis (Top Clusters)

Cluster ID Issue Count Top Keywords
1 15 authentication, login, session
2 8 performance, slow, response
3 5 documentation, api, update

Analytics update after scanning the repository. More detailed analytics could be added.

''' def extract_owner_repo(url): """Extract owner and repository name from GitHub URL""" pattern = r"github\.com/([^/]+)/([^/]+)" match = re.search(pattern, url) if match: owner, repo = match.groups() # Remove .git suffix if present if repo.endswith('.git'): repo = repo[:-4] return owner, repo return None, None def get_github_issues(owner, repo, token=None): """Fetch open issues from a GitHub repository""" url = f"https://api.github.com/repos/{owner}/{repo}/issues" headers = { "Accept": "application/vnd.github.v3+json" } if token: headers["Authorization"] = f"token {token}" params = { "state": "open", "per_page": 100 } try: response = requests.get(url, headers=headers, params=params) response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: raise Exception(f"Failed to fetch issues: {str(e)}") def classify_issue_severity(title, body): """Simple rule-based severity classification""" text = (title + " " + (body or "")).lower() critical_keywords = ['crash', 'critical', 'fail', 'broken', 'security', 'vulnerability'] high_keywords = ['error', 'bug', 'performance', 'slow'] medium_keywords = ['improve', 'enhancement', 'feature', 'request'] low_keywords = ['documentation', 'typo', 'minor'] for keyword in critical_keywords: if keyword in text: return 'Critical' for keyword in high_keywords: if keyword in text: return 'High' for keyword in medium_keywords: if keyword in text: return 'Medium' for keyword in low_keywords: if keyword in text: return 'Low' return 'Unknown' def cluster_issues(issues): """Simple clustering based on keywords in titles""" clusters = {} cluster_id = 1 for issue in issues: title = issue['title'].lower() # Extract potential cluster keywords if 'auth' in title or 'login' in title or 'session' in title: cluster = 1 elif 'performance' in title or 'slow' in title or 'speed' in title: cluster = 2 elif 'doc' in title or 'readme' in title or 'documentation' in title: cluster = 3 else: cluster = cluster_id cluster_id += 1 issue['cluster'] = cluster if cluster not in clusters: clusters[cluster] = [] clusters[cluster].append(issue) return issues, len(clusters) @app.route('/') def index(): return render_template_string(HTML_TEMPLATE) @app.route('/scan_issues', methods=['POST']) def scan_issues(): try: data = request.get_json() repo_url = data.get('repo_url') github_token = data.get('github_token') if not repo_url: return jsonify({'error': 'Repository URL is required'}), 400 owner, repo = extract_owner_repo(repo_url) if not owner or not repo: return jsonify({'error': 'Invalid GitHub URL format'}), 400 # Fetch issues from GitHub github_issues = get_github_issues(owner, repo, github_token) # Process issues processed_issues = [] for issue in github_issues: if 'pull_request' not in issue: # Skip pull requests processed_issues.append({ 'number': issue['number'], 'title': issue['title'], 'body': issue['body'], 'severity': classify_issue_severity(issue['title'], issue['body']) }) # Cluster issues clustered_issues, cluster_count = cluster_issues(processed_issues) # Calculate severity distribution severity_counter = Counter(issue['severity'] for issue in clustered_issues) return jsonify({ 'issues': clustered_issues, 'total_issues': len(clustered_issues), 'clusters': cluster_count, 'severity_distribution': dict(severity_counter) }) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/ai_suggestions', methods=['POST']) def ai_suggestions(): try: data = request.get_json() issue_id = data.get('issue_id') hf_token = data.get('hf_token') model = data.get('model') if not hf_token: return jsonify({'error': 'Hugging Face token is required'}), 400 # In a real implementation, you would call the Hugging Face API here # For this example, we'll return mock suggestions suggestions = f'''

💡 Suggestion based on {model}:

1. Address Missing Information: Request steps to reproduce from the user and ask for server error logs.

2. Refine Understanding: The issue #{issue_id} appears to be related to authentication flow problems.

3. Identify Relevant Code Areas: Check authentication modules and session management code.

4. Implementation Steps:

  1. Review authentication implementation
  2. Check session handling logic
  3. Verify token generation and validation
  4. Test fix in staging environment

5. Testing Recommendations: Test with different browsers and network conditions.

''' return jsonify({'suggestions': suggestions}) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/ai_patch', methods=['POST']) def ai_patch(): try: data = request.get_json() issue_id = data.get('issue_id') hf_token = data.get('hf_token') model = data.get('model') if not hf_token: return jsonify({'error': 'Hugging Face token is required'}), 400 # In a real implementation, you would call the Hugging Face API here # For this example, we'll return a mock patch patch = f'''

🩹 Patch Generation Result from {model}: (Patch Generated)

Explanation: This patch addresses issue #{issue_id} by improving error handling in the authentication flow.


Patch:

--- a/src/auth/auth_service.py
+++ b/src/auth/auth_service.py
@@ -42,6 +42,10 @@
         user = self.get_user(credentials.username)
         if not user:
             raise AuthenticationError("User not found")
+        
+        # Validate account status
+        if not user.is_active:
+            raise AuthenticationError("Account is deactivated")
         
         if not self.check_password(credentials.password, user.password_hash):
             raise AuthenticationError("Invalid credentials")
            
''' return jsonify({'patch': patch}) except Exception as e: return jsonify({'error': str(e)}), 500 if __name__ == '__main__': app.run(debug=True)