Yannick-Agent commited on
Commit
eaacd3a
Β·
verified Β·
1 Parent(s): f0642fc

Deploy: SaaS Prototype Completion Bridge

Browse files
Files changed (3) hide show
  1. ===FILE: requirements.txt=== +4 -0
  2. README.md +7 -6
  3. requirements.txt +400 -0
===FILE: requirements.txt=== ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio==4.44.1
2
+ requests==2.32.3
3
+ PyGithub==2.3.0
4
+ python-dotenv==1.0.1
README.md CHANGED
@@ -1,12 +1,13 @@
1
  ---
2
- title: Saas Prototype Completion Bridge
3
- emoji: πŸŒ–
4
- colorFrom: pink
5
- colorTo: pink
6
  sdk: gradio
7
- sdk_version: 6.9.0
 
8
  app_file: app.py
9
  pinned: false
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: SaaS Prototype Completion Bridge
3
+ emoji: πŸ“Š
4
+ colorFrom: blue
5
+ colorTo: purple
6
  sdk: gradio
7
+ sdk_version: 5.12.0
8
+ python_version: "3.11"
9
  app_file: app.py
10
  pinned: false
11
  ---
12
 
13
+ # SaaS Prototype Completion Bridge
requirements.txt ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio>=4.44.1
2
+ requests>=2.32.3
3
+ PyGithub>=2.3.0
4
+ python-dotenv>=1.0.1
5
+ ```
6
+
7
+ ===FILE: app.py===
8
+ ```
9
+ import gradio as gr
10
+ from analyzer import analyze_repo, generate_premium_checklist
11
+
12
+ def run_free_analysis(repo_url, state):
13
+ """Run free gap analysis and update state."""
14
+ if not repo_url or not repo_url.strip():
15
+ return "Please enter a GitHub repository URL.", state
16
+
17
+ try:
18
+ gaps, repo_info = analyze_repo(repo_url.strip())
19
+ state = {
20
+ 'repo_url': repo_url.strip(),
21
+ 'gaps': gaps,
22
+ 'repo_info': repo_info
23
+ }
24
+
25
+ if not gaps:
26
+ return "πŸŽ‰ No critical gaps found! Your prototype looks ready for launch.", state
27
+
28
+ output = "## πŸ” Critical Gaps Found\n\n"
29
+ for i, gap in enumerate(gaps, 1):
30
+ output += f"{i}. **{gap['title']}**\n"
31
+ output += f" - *Severity*: {gap['severity']}\n"
32
+ output += f" - *Description*: {gap['description']}\n\n"
33
+
34
+ return output, state
35
+ except ValueError as e:
36
+ return f"❌ Validation error: {str(e)}", state
37
+ except Exception as e:
38
+ return f"❌ Analysis failed: {str(e)}", state
39
+
40
+ def run_premium_checklist(state):
41
+ """Generate premium checklist from state."""
42
+ if not state or 'gaps' not in state or not state['gaps']:
43
+ return "No analysis results available. Please run free analysis first.", state
44
+
45
+ try:
46
+ checklist = generate_premium_checklist(state['gaps'], state['repo_info'])
47
+ return checklist, state
48
+ except Exception as e:
49
+ return f"❌ Checklist generation failed: {str(e)}", state
50
+
51
+ # Gradio UI
52
+ with gr.Blocks(title="SaaS Gap Bridge", theme=gr.themes.Soft()) as demo:
53
+ gr.Markdown("# πŸš€ SaaS Gap Bridge")
54
+ gr.Markdown("Analyze your GitHub prototype for launch-critical gaps and get a detailed checklist.")
55
+
56
+ # State to store analysis results
57
+ app_state = gr.State({})
58
+
59
+ with gr.Row():
60
+ with gr.Column(scale=3):
61
+ repo_input = gr.Textbox(
62
+ label="GitHub Repository URL",
63
+ placeholder="https://github.com/username/repository",
64
+ info="Enter a public GitHub repository URL"
65
+ )
66
+
67
+ analyze_btn = gr.Button("πŸ” Analyze Prototype (Free)", variant="primary")
68
+
69
+ free_output = gr.Markdown(label="Analysis Results")
70
+
71
+ with gr.Column(scale=2):
72
+ gr.Markdown("### Premium Features (Mock)")
73
+ gr.Markdown("Generate a detailed launch checklist with code snippets.")
74
+
75
+ premium_btn = gr.Button("πŸ“‹ Generate Launch Checklist (Premium Simulation)", variant="secondary")
76
+
77
+ premium_output = gr.Markdown(label="Premium Checklist")
78
+
79
+ # Event handlers
80
+ analyze_btn.click(
81
+ fn=run_free_analysis,
82
+ inputs=[repo_input, app_state],
83
+ outputs=[free_output, app_state]
84
+ )
85
+
86
+ premium_btn.click(
87
+ fn=run_premium_checklist,
88
+ inputs=[app_state],
89
+ outputs=[premium_output, app_state]
90
+ )
91
+
92
+ gr.Markdown("---")
93
+ gr.Markdown("""
94
+ ### How it works:
95
+ 1. Paste your public GitHub repository URL
96
+ 2. Click **Analyze Prototype** for free gap detection
97
+ 3. Click **Generate Launch Checklist** for detailed recommendations
98
+
99
+ *Note: This is a demo tool. Premium features are simulated for MVP purposes.*
100
+ """)
101
+
102
+ if __name__ == "__main__":
103
+ demo.launch(server_name="0.0.0.0", server_port=7860)
104
+ ```
105
+
106
+ ===FILE: analyzer.py===
107
+ ```
108
+ import re
109
+ import ast
110
+ import requests
111
+ from typing import List, Dict, Tuple, Optional
112
+ from github import Github, GithubException
113
+ from github.Repository import Repository
114
+ import urllib.parse
115
+
116
+ class RepoAnalyzer:
117
+ """Core analyzer for GitHub repositories."""
118
+
119
+ # Common patterns for hardcoded secrets
120
+ SECRET_PATTERNS = [
121
+ r'api[_-]?key["\']?\s*[:=]\s*["\'][A-Za-z0-9_\-]{20,}["\']',
122
+ r'secret["\']?\s*[:=]\s*["\'][A-Za-z0-9_\-]{20,}["\']',
123
+ r'password["\']?\s*[:=]\s*["\'][^\s"\']{8,}["\']',
124
+ r'token["\']?\s*[:=]\s*["\'][A-Za-z0-9_\-]{20,}["\']',
125
+ r'bearer["\']?\s*[:=]\s*["\'][A-Za-z0-9_\-]{20,}["\']',
126
+ ]
127
+
128
+ # Critical packages for SaaS launch
129
+ CRITICAL_PYTHON_PACKAGES = ['stripe', 'python-dotenv', 'logging', 'flask', 'django', 'fastapi']
130
+
131
+ def __init__(self, github_token: Optional[str] = None):
132
+ """Initialize with optional GitHub token for higher rate limits."""
133
+ self.github = Github(github_token) if github_token else Github()
134
+
135
+ def extract_owner_repo(self, url: str) -> Tuple[str, str]:
136
+ """Extract owner and repository name from GitHub URL."""
137
+ parsed = urllib.parse.urlparse(url)
138
+ if not parsed.netloc.endswith('github.com'):
139
+ raise ValueError("Invalid GitHub URL. Must be a github.com repository.")
140
+
141
+ path_parts = parsed.path.strip('/').split('/')
142
+ if len(path_parts) < 2:
143
+ raise ValueError("URL must include owner and repository name (e.g., https://github.com/owner/repo)")
144
+
145
+ return path_parts[0], path_parts[1]
146
+
147
+ def get_repo(self, url: str) -> Repository:
148
+ """Get GitHub repository object."""
149
+ owner, repo_name = self.extract_owner_repo(url)
150
+ try:
151
+ return self.github.get_repo(f"{owner}/{repo_name}")
152
+ except GithubException as e:
153
+ if e.status == 404:
154
+ raise ValueError(f"Repository not found: {owner}/{repo_name}")
155
+ elif e.status == 403:
156
+ raise Exception("GitHub API rate limit exceeded. Try again later or add a GitHub token.")
157
+ else:
158
+ raise Exception(f"GitHub API error: {str(e)}")
159
+
160
+ def analyze_python_file(self, content: str, filename: str) -> List[Dict]:
161
+ """Analyze Python file for gaps using AST parsing."""
162
+ gaps = []
163
+
164
+ try:
165
+ tree = ast.parse(content)
166
+ except SyntaxError:
167
+ # If AST fails, use regex-based analysis
168
+ return self.analyze_with_regex(content, filename)
169
+
170
+ # Check for hardcoded secrets
171
+ for node in ast.walk(tree):
172
+ if isinstance(node, ast.Assign):
173
+ for target in node.targets:
174
+ if isinstance(target, ast.Name):
175
+ var_name = target.id.lower()
176
+ if any(secret_term in var_name for secret_term in ['key', 'secret', 'password', 'token']):
177
+ if isinstance(node.value, ast.Constant):
178
+ value = str(node.value.value)
179
+ if len(value) > 10: # Suspiciously long value
180
+ gaps.append({
181
+ 'title': 'Hardcoded Secret Detected',
182
+ 'severity': 'CRITICAL',
183
+ 'description': f'Potential hardcoded secret in variable "{target.id}" in {filename}'
184
+ })
185
+
186
+ # Check for missing error handling
187
+ has_try_except = any(isinstance(node, ast.Try) for node in ast.walk(tree))
188
+ if not has_try_except and filename in ['main.py', 'app.py', 'server.py']:
189
+ gaps.append({
190
+ 'title': 'Missing Error Handling',
191
+ 'severity': 'HIGH',
192
+ 'description': f'No try/except blocks found in {filename}. Critical for production stability.'
193
+ })
194
+
195
+ # Check for environment variable usage
196
+ env_imports = False
197
+ for node in ast.walk(tree):
198
+ if isinstance(node, ast.Import):
199
+ for alias in node.names:
200
+ if alias.name in ['os', 'dotenv']:
201
+ env_imports = True
202
+ elif isinstance(node, ast.ImportFrom):
203
+ if node.module in ['os', 'dotenv']:
204
+ env_imports = True
205
+
206
+ if not env_imports and filename in ['main.py', 'app.py', 'config.py']:
207
+ gaps.append({
208
+ 'title': 'No Configuration Management',
209
+ 'severity': 'HIGH',
210
+ 'description': f'No environment variable imports (os/dotenv) found in {filename}.'
211
+ })
212
+
213
+ # Check for payment integrations
214
+ payment_imports = False
215
+ for node in ast.walk(tree):
216
+ if isinstance(node, (ast.Import, ast.ImportFrom)):
217
+ for alias in node.names:
218
+ if 'stripe' in alias.name.lower() or 'pay' in alias.name.lower():
219
+ payment_imports = True
220
+
221
+ if not payment_imports and filename in ['main.py', 'app.py', 'payment.py']:
222
+ gaps.append({
223
+ 'title': 'Missing Payment Integration',
224
+ 'severity': 'MEDIUM',
225
+ 'description': 'No payment-related imports (e.g., Stripe) detected.'
226
+ })
227
+
228
+ return gaps
229
+
230
+ def analyze_with_regex(self, content: str, filename: str) -> List[Dict]:
231
+ """Fallback regex analysis for non-Python files or parsing errors."""
232
+ gaps = []
233
+
234
+ # Check for hardcoded secrets
235
+ for pattern in self.SECRET_PATTERNS:
236
+ if re.search(pattern, content, re.IGNORECASE):
237
+ gaps.append({
238
+ 'title': 'Hardcoded Secret Pattern Detected',
239
+ 'severity': 'CRITICAL',
240
+ 'description': f'Pattern matching hardcoded secret found in {filename}'
241
+ })
242
+ break
243
+
244
+ return gaps
245
+
246
+ def analyze_requirements(self, content: str) -> List[Dict]:
247
+ """Analyze requirements.txt for missing critical packages."""
248
+ gaps = []
249
+ installed_packages = [line.split('==')[0].split('>=')[0].strip().lower()
250
+ for line in content.split('\n')
251
+ if line.strip() and not line.strip().startswith('#')]
252
+
253
+ for package in self.CRITICAL_PYTHON_PACKAGES:
254
+ if package not in installed_packages:
255
+ if package == 'stripe':
256
+ gaps.append({
257
+ 'title': 'Missing Payment SDK',
258
+ 'severity': 'HIGH',
259
+ 'description': f'Stripe package not found in requirements.txt. Required for payment processing.'
260
+ })
261
+ elif package == 'python-dotenv':
262
+ gaps.append({
263
+ 'title': 'Missing Environment Management',
264
+ 'severity': 'MEDIUM',
265
+ 'description': 'python-dotenv not found. Consider adding for configuration management.'
266
+ })
267
+
268
+ return gaps
269
+
270
+ def analyze_repo_structure(self, repo: Repository) -> List[Dict]:
271
+ """Analyze repository structure for common gaps."""
272
+ gaps = []
273
+ contents = repo.get_contents("")
274
+
275
+ # Check for common files
276
+ files = [item.name.lower() for item in contents if item.type == 'file']
277
+ dirs = [item.name.lower() for item in contents if item.type == 'dir']
278
+
279
+ if 'readme.md' not in files and 'readme' not in files:
280
+ gaps.append({
281
+ 'title': 'Missing README',
282
+ 'severity': 'MEDIUM',
283
+ 'description': 'No README.md file found. Important for documentation.'
284
+ })
285
+
286
+ if 'requirements.txt' not in files and 'pyproject.toml' not in files and 'setup.py' not in files:
287
+ gaps.append({
288
+ 'title': 'Missing Dependency File',
289
+ 'severity': 'HIGH',
290
+ 'description': 'No requirements.txt, pyproject.toml, or setup.py found.'
291
+ })
292
+
293
+ if 'tests' not in dirs and 'test' not in dirs:
294
+ gaps.append({
295
+ 'title': 'No Test Directory',
296
+ 'severity': 'MEDIUM',
297
+ 'description': 'No test directory found. Consider adding tests for production readiness.'
298
+ })
299
+
300
+ return gaps
301
+
302
+ def analyze(self, repo_url: str) -> Tuple[List[Dict], Dict]:
303
+ """Main analysis function."""
304
+ repo = self.get_repo(repo_url)
305
+ all_gaps = []
306
+
307
+ # Get repo info
308
+ repo_info = {
309
+ 'name': repo.full_name,
310
+ 'language': repo.language or 'Unknown',
311
+ 'description': repo.description or 'No description',
312
+ 'stars': repo.stargazers_count,
313
+ 'forks': repo.forks_count
314
+ }
315
+
316
+ # Analyze structure
317
+ all_gaps.extend(self.analyze_repo_structure(repo))
318
+
319
+ # Analyze main files
320
+ main_files = ['main.py', 'app.py', 'server.py', 'index.js', 'index.py', 'app.js']
321
+ for filename in main_files:
322
+ try:
323
+ file_content = repo.get_contents(filename)
324
+ if file_content.type == 'file':
325
+ content = file_content.decoded_content.decode('utf-8')
326
+ if filename.endswith('.py'):
327
+ all_gaps.extend(self.analyze_python_file(content, filename))
328
+ else:
329
+ all_gaps.extend(self.analyze_with_regex(content, filename))
330
+ except:
331
+ continue
332
+
333
+ # Analyze requirements.txt
334
+ try:
335
+ req_content = repo.get_contents("requirements.txt")
336
+ if req_content.type == 'file':
337
+ content = req_content.decoded_content.decode('utf-8')
338
+ all_gaps.extend(self.analyze_requirements(content))
339
+ except:
340
+ pass
341
+
342
+ # Remove duplicates and prioritize
343
+ unique_gaps = []
344
+ seen_titles = set()
345
+ for gap in all_gaps:
346
+ if gap['title'] not in seen_titles:
347
+ seen_titles.add(gap['title'])
348
+ unique_gaps.append(gap)
349
+
350
+ # Sort by severity
351
+ severity_order = {'CRITICAL': 0, 'HIGH': 1, 'MEDIUM': 2, 'LOW': 3}
352
+ unique_gaps.sort(key=lambda x: severity_order.get(x['severity'], 4))
353
+
354
+ # Return top 5 gaps max
355
+ return unique_gaps[:5], repo_info
356
+
357
+ def analyze_repo(repo_url: str) -> Tuple[List[Dict], Dict]:
358
+ """Public interface for repo analysis."""
359
+ analyzer = RepoAnalyzer()
360
+ return analyzer.analyze(repo_url)
361
+
362
+ def generate_premium_checklist(gaps: List[Dict], repo_info: Dict) -> str:
363
+ """Generate premium checklist with code snippets."""
364
+ if not gaps:
365
+ return "## πŸŽ‰ No Gaps Found\n\nYour prototype is ready for launch!"
366
+
367
+ output = "# πŸ“‹ SaaS Launch Checklist (Premium)\n\n"
368
+ output += f"**Repository**: {repo_info['name']} \n"
369
+ output += f"**Language**: {repo_info['language']} \n"
370
+ output += f"**Stars**: {repo_info['stars']} \n\n"
371
+ output += "---\n\n"
372
+
373
+ for i, gap in enumerate(gaps, 1):
374
+ output += f"## {i}. {gap['title']}\n"
375
+ output += f"**Severity**: {gap['severity']} \n"
376
+ output += f"**Description**: {gap['description']} \n\n"
377
+
378
+ # Add code snippet based on gap type
379
+ if 'Secret' in gap['title']:
380
+ output += "### πŸ”’ Recommended Fix:\n```python\n# Use environment variables instead of hardcoded secrets\nimport os\nfrom dotenv import load_dotenv\n\nload_dotenv() # Load from .env file\n\n# Access secrets securely\napi_key = os.getenv('API_KEY')\ndb_password = os.getenv('DB_PASSWORD')\n```\n\n"
381
+ elif 'Error Handling' in gap['title']:
382
+ output += "### πŸ›‘οΈ Recommended Fix:\n```python\n# Add comprehensive error handling\nimport logging\nimport traceback\n\nlogging.basicConfig(level=logging.ERROR)\nlogger = logging.getLogger(__name__)\n\ntry:\n # Your main application logic here\n result = risky_operation()\nexcept ValueError as e:\n logger.error(f\"Validation error: {e}\")\n # Handle validation error\nexcept Exception as e:\n logger.error(f\"Unexpected error: {e}\")\n logger.error(traceback.format_exc())\n # Graceful degradation or retry logic\n```\n\n"
383
+ elif 'Payment' in gap['title']:
384
+ output += "### πŸ’³ Recommended Fix:\n```python\n# Add Stripe payment integration\nimport stripe\nimport os\n\nstripe.api_key = os.getenv('STRIPE_SECRET_KEY')\n\n# Example: Create a payment intent\ndef create_payment_intent(amount, currency='usd'):\n try:\n intent = stripe.PaymentIntent.create(\n amount=amount,\n currency=currency,\n metadata={'integration_check': 'accept_a_payment'}\n )\n return intent.client_secret\n except stripe.error.StripeError as e:\n # Handle Stripe-specific errors\n raise\n```\n\n"
385
+ elif 'Configuration' in gap['title']:
386
+ output += "### βš™οΈ Recommended Fix:\n```python\n# Add configuration management\nfrom dotenv import load_dotenv\nimport os\n\n# Create a .env file with:\n# DB_HOST=localhost\n# DB_PORT=5432\n# API_KEY=your_key_here\n\nload_dotenv() # Load environment variables\n\nclass Config:\n DB_HOST = os.getenv('DB_HOST', 'localhost')\n DB_PORT = int(os.getenv('DB_PORT', 5432))\n API_KEY = os.getenv('API_KEY')\n DEBUG = os.getenv('DEBUG', 'False').lower() == 'true'\n```\n\n"
387
+ elif 'README' in gap['title']:
388
+ output += "### πŸ“š Recommended Fix:\n```markdown\n# Project Name\n\nBrief description of your SaaS application.\n\n## Features\n- Feature 1\n- Feature 2\n- Feature 3\n\n## Installation\n```bash\ngit clone https://github.com/username/repo\ncd repo\npip install -r requirements.txt\n```\n\n## Configuration\nCopy `.env.example` to `.env` and fill in your environment variables.\n\n## Usage\n```bash\npython app.py\n```\n\n## Deployment\nInstructions for deploying to Heroku, AWS, etc.\n```\n\n"
389
+
390
+ output += "---\n\n"
391
+
392
+ output += "## πŸš€ Next Steps\n"
393
+ output += "1. Implement the fixes above\n"
394
+ output += "2. Add automated tests\n"
395
+ output += "3. Set up CI/CD pipeline\n"
396
+ output += "4. Deploy to a staging environment\n"
397
+ output += "5. Monitor with error tracking (Sentry, etc.)\n\n"
398
+ output += "*This is a simulated premium checklist. For actual premium features, contact support.*"
399
+
400
+ return output