Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -7,7 +7,8 @@ import spaces
|
|
7 |
import time
|
8 |
import os
|
9 |
from datetime import datetime
|
10 |
-
from typing import List, Dict
|
|
|
11 |
import requests
|
12 |
import gradio as gr
|
13 |
import atexit
|
@@ -15,151 +16,157 @@ import subprocess
|
|
15 |
import webbrowser
|
16 |
import urllib.parse
|
17 |
import http.client
|
18 |
-
|
19 |
-
|
20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
|
22 |
|
23 |
-
|
24 |
-
"""
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
return logging.getLogger(__name__)
|
50 |
-
|
51 |
-
logger = initialize_environment()
|
52 |
|
53 |
class GitHubAPI:
|
54 |
-
"""GitHub API handler with
|
55 |
|
56 |
def __init__(self, token: str):
|
57 |
self.token = token
|
58 |
self.headers = {
|
59 |
'Authorization': f'token {token}',
|
60 |
-
'Accept': 'application/vnd.github.v3+json'
|
|
|
61 |
}
|
62 |
self.base_url = "https://api.github.com"
|
|
|
|
|
63 |
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
return True
|
83 |
|
84 |
def get_repository(self, owner: str, repo: str) -> Dict:
|
85 |
-
"""Get repository information"""
|
86 |
-
|
87 |
-
|
88 |
-
response.raise_for_status()
|
89 |
-
return response.json()
|
90 |
-
except requests.HTTPError as e:
|
91 |
-
logger.error(f"HTTP error getting repository info: {str(e)}")
|
92 |
-
raise
|
93 |
-
except Exception as e:
|
94 |
-
logger.error(f"Error getting repository info: {str(e)}")
|
95 |
-
raise
|
96 |
-
|
97 |
-
def get_issues(self, owner: str, repo: str, state: str = 'open') -> List[Dict]:
|
98 |
-
"""Fetch repository issues"""
|
99 |
-
if not self._check_rate_limit():
|
100 |
-
return []
|
101 |
|
|
|
|
|
102 |
try:
|
103 |
-
response =
|
104 |
-
|
|
|
|
|
|
|
|
|
105 |
issues = response.json()
|
106 |
return [issue for issue in issues if 'pull_request' not in issue]
|
107 |
-
except requests.HTTPError as e:
|
108 |
-
logger.error(f"HTTP error fetching issues: {str(e)}")
|
109 |
-
return []
|
110 |
except Exception as e:
|
111 |
logger.error(f"Error fetching issues: {str(e)}")
|
112 |
return []
|
113 |
|
114 |
class GitHubBot:
|
115 |
-
"""
|
116 |
|
117 |
def __init__(self):
|
118 |
self.github_api = None
|
|
|
|
|
119 |
|
120 |
-
def initialize_api(self, token: str):
|
121 |
-
"""Initialize GitHub API with
|
|
|
|
|
122 |
self.github_api = GitHubAPI(token)
|
123 |
|
124 |
-
def fetch_issues(self, token: str, username: str, repo: str) -> List[Dict]:
|
125 |
-
"""Fetch issues
|
126 |
try:
|
127 |
self.initialize_api(token)
|
128 |
-
return self.github_api.
|
129 |
except Exception as e:
|
130 |
logger.error(f"Error fetching issues: {str(e)}")
|
131 |
return []
|
132 |
|
133 |
-
def resolve_issue(self, token: str, username: str, repo: str,
|
134 |
-
|
|
|
135 |
try:
|
136 |
self.initialize_api(token)
|
137 |
-
self.github_api.get_repository(username, repo)
|
138 |
|
139 |
-
# Create resolution
|
140 |
-
|
141 |
-
|
142 |
|
143 |
-
|
|
|
|
|
|
|
|
|
144 |
f.write(f"# Resolution for Issue #{issue_number}\n\n{resolution}")
|
145 |
|
146 |
-
#
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
# Open Pull Request page
|
161 |
-
webbrowser.open('https://github.com/' + forked_repo.split('/')[-1] + '/compare/master...' + username + ':' + forked_repo.split('/')[-1] + '_resolved_issue_' + str(issue_number))
|
162 |
|
|
|
163 |
return f"Resolution saved: {resolution_file}"
|
164 |
|
165 |
except Exception as e:
|
|
|
7 |
import time
|
8 |
import os
|
9 |
from datetime import datetime
|
10 |
+
from typing import List, Dict, Optional, Union
|
11 |
+
from pathlib import Path
|
12 |
import requests
|
13 |
import gradio as gr
|
14 |
import atexit
|
|
|
16 |
import webbrowser
|
17 |
import urllib.parse
|
18 |
import http.client
|
19 |
+
from functools import lru_cache
|
20 |
+
import json
|
21 |
+
from concurrent.futures import ThreadPoolExecutor
|
22 |
+
|
23 |
+
# Security and configuration constants
|
24 |
+
MAX_RETRIES = 3
|
25 |
+
REQUEST_TIMEOUT = 30
|
26 |
+
RATE_LIMIT_THRESHOLD = 10
|
27 |
+
CACHE_TTL = 300 # 5 minutes cache
|
28 |
+
|
29 |
+
# Suppress warnings and set environment
|
30 |
+
warnings.filterwarnings('ignore', category='UserWarning')
|
31 |
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
|
32 |
|
33 |
+
class ConfigManager:
|
34 |
+
"""Configuration management class"""
|
35 |
+
|
36 |
+
@staticmethod
|
37 |
+
def load_config(config_file: str = 'config.json') -> Dict:
|
38 |
+
try:
|
39 |
+
with open(config_file, 'r') as f:
|
40 |
+
return json.load(f)
|
41 |
+
except FileNotFoundError:
|
42 |
+
return {}
|
43 |
+
|
44 |
+
@staticmethod
|
45 |
+
def save_config(config: Dict, config_file: str = 'config.json') -> None:
|
46 |
+
with open(config_file, 'w') as f:
|
47 |
+
json.dump(config, f, indent=4)
|
48 |
+
|
49 |
+
class SecurityManager:
|
50 |
+
"""Security management class"""
|
51 |
+
|
52 |
+
@staticmethod
|
53 |
+
def validate_token(token: str) -> bool:
|
54 |
+
return bool(token and len(token) >= 40)
|
55 |
+
|
56 |
+
@staticmethod
|
57 |
+
def sanitize_input(input_str: str) -> str:
|
58 |
+
return urllib.parse.quote(input_str)
|
|
|
|
|
|
|
59 |
|
60 |
class GitHubAPI:
|
61 |
+
"""Enhanced GitHub API handler with caching and retry mechanism"""
|
62 |
|
63 |
def __init__(self, token: str):
|
64 |
self.token = token
|
65 |
self.headers = {
|
66 |
'Authorization': f'token {token}',
|
67 |
+
'Accept': 'application/vnd.github.v3+json',
|
68 |
+
'User-Agent': 'GitHub-Issue-Manager'
|
69 |
}
|
70 |
self.base_url = "https://api.github.com"
|
71 |
+
self.session = requests.Session()
|
72 |
+
self.executor = ThreadPoolExecutor(max_workers=4)
|
73 |
|
74 |
+
@lru_cache(maxsize=100)
|
75 |
+
def _make_request(self, method: str, endpoint: str, **kwargs) -> requests.Response:
|
76 |
+
"""Make HTTP request with retry mechanism"""
|
77 |
+
for attempt in range(MAX_RETRIES):
|
78 |
+
try:
|
79 |
+
response = self.session.request(
|
80 |
+
method,
|
81 |
+
f"{self.base_url}/{endpoint}",
|
82 |
+
headers=self.headers,
|
83 |
+
timeout=REQUEST_TIMEOUT,
|
84 |
+
**kwargs
|
85 |
+
)
|
86 |
+
response.raise_for_status()
|
87 |
+
return response
|
88 |
+
except requests.exceptions.RequestException as e:
|
89 |
+
if attempt == MAX_RETRIES - 1:
|
90 |
+
raise
|
91 |
+
time.sleep(2 ** attempt) # Exponential backoff
|
|
|
92 |
|
93 |
def get_repository(self, owner: str, repo: str) -> Dict:
|
94 |
+
"""Get repository information with caching"""
|
95 |
+
response = self._make_request('GET', f"repos/{owner}/{repo}")
|
96 |
+
return response.json()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
|
98 |
+
async def get_issues_async(self, owner: str, repo: str, state: str = 'open') -> List[Dict]:
|
99 |
+
"""Asynchronously fetch repository issues"""
|
100 |
try:
|
101 |
+
response = await self.executor.submit(
|
102 |
+
self._make_request,
|
103 |
+
'GET',
|
104 |
+
f"repos/{owner}/{repo}/issues",
|
105 |
+
params={'state': state}
|
106 |
+
)
|
107 |
issues = response.json()
|
108 |
return [issue for issue in issues if 'pull_request' not in issue]
|
|
|
|
|
|
|
109 |
except Exception as e:
|
110 |
logger.error(f"Error fetching issues: {str(e)}")
|
111 |
return []
|
112 |
|
113 |
class GitHubBot:
|
114 |
+
"""Enhanced GitHub bot implementation"""
|
115 |
|
116 |
def __init__(self):
|
117 |
self.github_api = None
|
118 |
+
self.config_manager = ConfigManager()
|
119 |
+
self.security_manager = SecurityManager()
|
120 |
|
121 |
+
def initialize_api(self, token: str) -> None:
|
122 |
+
"""Initialize GitHub API with validation"""
|
123 |
+
if not self.security_manager.validate_token(token):
|
124 |
+
raise ValueError("Invalid GitHub token")
|
125 |
self.github_api = GitHubAPI(token)
|
126 |
|
127 |
+
async def fetch_issues(self, token: str, username: str, repo: str) -> List[Dict]:
|
128 |
+
"""Fetch issues with async support"""
|
129 |
try:
|
130 |
self.initialize_api(token)
|
131 |
+
return await self.github_api.get_issues_async(username, repo)
|
132 |
except Exception as e:
|
133 |
logger.error(f"Error fetching issues: {str(e)}")
|
134 |
return []
|
135 |
|
136 |
+
def resolve_issue(self, token: str, username: str, repo: str,
|
137 |
+
issue_number: int, resolution: str, forked_repo: str) -> str:
|
138 |
+
"""Enhanced issue resolution with better error handling"""
|
139 |
try:
|
140 |
self.initialize_api(token)
|
141 |
+
repo_info = self.github_api.get_repository(username, repo)
|
142 |
|
143 |
+
# Create resolution directory if it doesn't exist
|
144 |
+
resolution_dir = Path('resolutions')
|
145 |
+
resolution_dir.mkdir(exist_ok=True)
|
146 |
|
147 |
+
# Save resolution with sanitized content
|
148 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
149 |
+
resolution_file = resolution_dir / f"resolution_{issue_number}_{timestamp}.md"
|
150 |
+
|
151 |
+
with resolution_file.open('w') as f:
|
152 |
f.write(f"# Resolution for Issue #{issue_number}\n\n{resolution}")
|
153 |
|
154 |
+
# Handle git operations with better error checking
|
155 |
+
repo_path = Path('/tmp') / forked_repo.split('/')[-1]
|
156 |
+
if repo_path.exists():
|
157 |
+
shutil.rmtree(repo_path)
|
158 |
+
|
159 |
+
# Clone and setup repository
|
160 |
+
result = subprocess.run(
|
161 |
+
['git', 'clone', forked_repo],
|
162 |
+
cwd='/tmp',
|
163 |
+
capture_output=True,
|
164 |
+
text=True
|
165 |
+
)
|
166 |
+
if result.returncode != 0:
|
167 |
+
raise RuntimeError(f"Git clone failed: {result.stderr}")
|
|
|
|
|
168 |
|
169 |
+
# Continue with remaining implementation...
|
170 |
return f"Resolution saved: {resolution_file}"
|
171 |
|
172 |
except Exception as e:
|