nihalaninihal commited on
Commit
15ca5a8
·
verified ·
1 Parent(s): 119add6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -117
app.py CHANGED
@@ -4,7 +4,7 @@ import json
4
  import tempfile
5
  import shutil
6
  from pathlib import Path
7
- from typing import Dict, Any, Tuple, List
8
  from dotenv import load_dotenv
9
 
10
  # Import all the analyzer modules
@@ -20,111 +20,79 @@ from prompt_analyzer import create_handler
20
  load_dotenv()
21
 
22
  class StyleAnalyzerApp:
23
- """Modern Gradio application for GitHub code style analysis"""
24
-
25
  def __init__(self):
26
- """Initialize the application with temporary directory and handler"""
27
  self.temp_dir = tempfile.mkdtemp()
28
  self.handler = create_handler()
29
 
30
  def cleanup(self):
31
- """Clean up temporary files on application shutdown"""
32
  if os.path.exists(self.temp_dir):
33
  shutil.rmtree(self.temp_dir)
34
 
35
- async def process_upload(self,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  files: List[gr.File],
37
  username: str,
38
  github_token: str = None,
39
  gemini_key: str = None) -> Tuple[str, Dict]:
40
- """
41
- Process uploaded files and perform analysis asynchronously
42
-
43
- Args:
44
- files: List of uploaded files
45
- username: GitHub username
46
- github_token: Optional GitHub API token
47
- gemini_key: Optional Google Gemini API key
48
-
49
- Returns:
50
- Tuple containing status message and analysis results
51
- """
52
-
53
- # Set environment variables if provided
54
- gemini_key="AIzaSyBHtQa-YQwhlDGihbyUUlS2MiclnXxiN8E"
55
- github_token="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"
56
 
57
- # Create user directory
58
- user_path = Path(self.temp_dir) / username
59
- user_path.mkdir(parents=True, exist_ok=True)
60
 
61
- # Process uploaded files
62
- report_data = None
63
- try:
64
  for file in files:
65
  file_path = file.name
66
  if file_path.endswith('report.json'):
67
  with open(file_path, 'r') as f:
68
  report_data = json.load(f)
69
- # Save to user directory
70
  with open(user_path / 'report.json', 'w') as out_f:
71
  json.dump(report_data, out_f)
72
  else:
73
- # Copy other files to user directory
74
  shutil.copy2(file_path, user_path)
75
 
76
  if not report_data:
77
- return gr.update(value="Error: No report.json file found in uploads"), None
78
 
79
- # Initialize repository selector
80
  repo_selector = RepositorySelector(self.temp_dir, username)
81
  sources_to_analyze = repo_selector.select_repositories(report_data)
82
-
83
- # Update status
84
- yield gr.update(value="Analyzing repository structure..."), None
85
-
86
- # Analyze repository structure
87
- sources_data = analyze_repository_structure(sources_to_analyze, user_path)
88
-
89
- # Perform analyses with status updates
90
- yield gr.update(value="Analyzing code style patterns..."), None
91
- code_style = analyze_code_style(sources_data)
92
-
93
- yield gr.update(value="Analyzing temporal patterns..."), None
94
- temporal_patterns = analyze_temporal_patterns(sources_data, report_data)
95
-
96
- yield gr.update(value="Analyzing project preferences..."), None
97
- project_preferences = analyze_project_preferences(sources_data)
98
 
99
- yield gr.update(value="Calculating identity confidence..."), None
100
- identity_confidence = calculate_identity_confidence(
101
- sources_data,
102
- code_style,
103
- project_preferences,
104
- temporal_patterns
105
- )
106
-
107
- # Combine results
108
- analysis_results = {
109
- "code_style_metrics": code_style,
110
- "temporal_patterns": temporal_patterns,
111
- "project_preferences": project_preferences,
112
- "identity_confidence": identity_confidence,
113
- }
114
-
115
- yield gr.update(value="Analysis completed successfully!"), analysis_results
116
 
117
  except Exception as e:
118
- yield gr.update(value=f"Error during analysis: {str(e)}"), None
119
 
120
  def create_interface(self) -> gr.Blocks:
121
- """Create the Gradio interface with modern styling and features"""
122
-
123
- # Custom CSS for better styling
124
  css = """
125
- .gradio-container {
126
- font-family: 'Helvetica Neue', Arial, sans-serif;
127
- }
128
  .analyze-btn {
129
  background-color: #2196F3;
130
  color: white;
@@ -133,9 +101,7 @@ class StyleAnalyzerApp:
133
  border-radius: 5px;
134
  cursor: pointer;
135
  }
136
- .analyze-btn:hover {
137
- background-color: #1976D2;
138
- }
139
  """
140
 
141
  with gr.Blocks(css=css, theme=gr.themes.Base()) as interface:
@@ -143,12 +109,6 @@ class StyleAnalyzerApp:
143
  # GitHub Stylometry Analyzer
144
 
145
  Analyze coding patterns and style from GitHub repositories.
146
-
147
- ## Instructions
148
- 1. Enter your GitHub username
149
- 2. Upload your repository files including report.json
150
- 3. Optionally provide API tokens for enhanced analysis
151
- 4. Click Analyze to begin
152
  """)
153
 
154
  with gr.Group():
@@ -156,35 +116,30 @@ class StyleAnalyzerApp:
156
  with gr.Column(scale=1):
157
  username = gr.Textbox(
158
  label="GitHub Username",
159
- placeholder="Enter your GitHub username",
160
- scale=2
161
  )
162
 
163
  with gr.Accordion("API Configuration", open=False):
164
  github_token = gr.Textbox(
165
  label="GitHub Token",
166
  placeholder="Your GitHub API token",
167
- type="password",
168
- show_label=True
169
  )
170
  gemini_key = gr.Textbox(
171
  label="Google Gemini API Key",
172
  placeholder="Your Gemini API key",
173
- type="password",
174
- show_label=True
175
  )
176
 
177
  files = gr.File(
178
  label="Upload Repository Files",
179
  file_count="multiple",
180
- file_types=[".json", ".git", ".zip"],
181
- scale=2
182
  )
183
 
184
  analyze_btn = gr.Button(
185
  "Start Analysis",
186
- elem_classes=["analyze-btn"],
187
- variant="primary"
188
  )
189
 
190
  with gr.Column(scale=1):
@@ -197,46 +152,24 @@ class StyleAnalyzerApp:
197
  interactive=False
198
  )
199
 
200
- # Event handlers
201
  analyze_btn.click(
202
- fn=self.process_upload,
203
  inputs=[files, username, github_token, gemini_key],
204
- outputs=[status, results],
205
- api_name="analyze"
206
  )
207
 
208
- # Example usage section
209
- with gr.Accordion("Example Usage", open=False):
210
- gr.Markdown("""
211
- ### Example Repository Analysis
212
-
213
- 1. Export your GitHub repository data using gh-analyze
214
- 2. Upload the generated report.json and repository files
215
- 3. The analyzer will process:
216
- - Code style patterns
217
- - Temporal commit patterns
218
- - Project preferences
219
- - Developer identity confidence
220
-
221
- Results include detailed metrics and analysis across multiple dimensions.
222
- """)
223
-
224
  return interface
225
 
226
  def main():
227
- """Main application entry point"""
228
  app = StyleAnalyzerApp()
229
  interface = app.create_interface()
230
 
231
  try:
232
- # Launch with modern Gradio configurations
233
- interface.queue(max_size=5).launch(
234
  server_name="0.0.0.0",
235
  server_port=7860,
236
  share=True,
237
- show_error=True,
238
- favicon_path="favicon.ico",
239
- auth=None, # Add authentication if needed
240
  )
241
  finally:
242
  app.cleanup()
 
4
  import tempfile
5
  import shutil
6
  from pathlib import Path
7
+ from typing import Dict, Any, Tuple, List, Generator
8
  from dotenv import load_dotenv
9
 
10
  # Import all the analyzer modules
 
20
  load_dotenv()
21
 
22
  class StyleAnalyzerApp:
 
 
23
  def __init__(self):
 
24
  self.temp_dir = tempfile.mkdtemp()
25
  self.handler = create_handler()
26
 
27
  def cleanup(self):
 
28
  if os.path.exists(self.temp_dir):
29
  shutil.rmtree(self.temp_dir)
30
 
31
+ def process_analysis(self, user_path: Path, sources_to_analyze: List[str]) -> Tuple[str, Dict]:
32
+ """Perform the main analysis steps"""
33
+ sources_data = analyze_repository_structure(sources_to_analyze, user_path)
34
+ code_style = analyze_code_style(sources_data)
35
+ temporal_patterns = analyze_temporal_patterns(sources_data, self.report_data)
36
+ project_preferences = analyze_project_preferences(sources_data)
37
+
38
+ identity_confidence = calculate_identity_confidence(
39
+ sources_data,
40
+ code_style,
41
+ project_preferences,
42
+ temporal_patterns
43
+ )
44
+
45
+ return {
46
+ "code_style_metrics": code_style,
47
+ "temporal_patterns": temporal_patterns,
48
+ "project_preferences": project_preferences,
49
+ "identity_confidence": identity_confidence,
50
+ }
51
+
52
+ def process_files(self,
53
  files: List[gr.File],
54
  username: str,
55
  github_token: str = None,
56
  gemini_key: str = None) -> Tuple[str, Dict]:
57
+ """Process uploaded files and run analysis"""
58
+ try:
59
+ # Set environment variables if provided
60
+ gemini_key="AIzaSyBHtQa-YQwhlDGihbyUUlS2MiclnXxiN8E"
61
+ github_token="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"
 
 
 
 
 
 
 
 
 
 
 
62
 
63
+ # Create user directory
64
+ user_path = Path(self.temp_dir) / username
65
+ user_path.mkdir(parents=True, exist_ok=True)
66
 
67
+ # Process uploaded files
68
+ report_data = None
 
69
  for file in files:
70
  file_path = file.name
71
  if file_path.endswith('report.json'):
72
  with open(file_path, 'r') as f:
73
  report_data = json.load(f)
 
74
  with open(user_path / 'report.json', 'w') as out_f:
75
  json.dump(report_data, out_f)
76
  else:
 
77
  shutil.copy2(file_path, user_path)
78
 
79
  if not report_data:
80
+ return "Error: No report.json file found in uploads", None
81
 
82
+ self.report_data = report_data
83
  repo_selector = RepositorySelector(self.temp_dir, username)
84
  sources_to_analyze = repo_selector.select_repositories(report_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
+ analysis_results = self.process_analysis(user_path, sources_to_analyze)
87
+ return "Analysis completed successfully!", analysis_results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
  except Exception as e:
90
+ return f"Error during analysis: {str(e)}", None
91
 
92
  def create_interface(self) -> gr.Blocks:
93
+ """Create the Gradio interface"""
 
 
94
  css = """
95
+ .gradio-container { font-family: 'Helvetica Neue', Arial, sans-serif; }
 
 
96
  .analyze-btn {
97
  background-color: #2196F3;
98
  color: white;
 
101
  border-radius: 5px;
102
  cursor: pointer;
103
  }
104
+ .analyze-btn:hover { background-color: #1976D2; }
 
 
105
  """
106
 
107
  with gr.Blocks(css=css, theme=gr.themes.Base()) as interface:
 
109
  # GitHub Stylometry Analyzer
110
 
111
  Analyze coding patterns and style from GitHub repositories.
 
 
 
 
 
 
112
  """)
113
 
114
  with gr.Group():
 
116
  with gr.Column(scale=1):
117
  username = gr.Textbox(
118
  label="GitHub Username",
119
+ placeholder="Enter your GitHub username"
 
120
  )
121
 
122
  with gr.Accordion("API Configuration", open=False):
123
  github_token = gr.Textbox(
124
  label="GitHub Token",
125
  placeholder="Your GitHub API token",
126
+ type="password"
 
127
  )
128
  gemini_key = gr.Textbox(
129
  label="Google Gemini API Key",
130
  placeholder="Your Gemini API key",
131
+ type="password"
 
132
  )
133
 
134
  files = gr.File(
135
  label="Upload Repository Files",
136
  file_count="multiple",
137
+ file_types=[".json", ".git", ".zip"]
 
138
  )
139
 
140
  analyze_btn = gr.Button(
141
  "Start Analysis",
142
+ elem_classes=["analyze-btn"]
 
143
  )
144
 
145
  with gr.Column(scale=1):
 
152
  interactive=False
153
  )
154
 
 
155
  analyze_btn.click(
156
+ fn=self.process_files,
157
  inputs=[files, username, github_token, gemini_key],
158
+ outputs=[status, results]
 
159
  )
160
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  return interface
162
 
163
  def main():
 
164
  app = StyleAnalyzerApp()
165
  interface = app.create_interface()
166
 
167
  try:
168
+ interface.queue().launch(
 
169
  server_name="0.0.0.0",
170
  server_port=7860,
171
  share=True,
172
+ show_error=True
 
 
173
  )
174
  finally:
175
  app.cleanup()