-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
294 lines (237 loc) Β· 12.3 KB
/
main.py
File metadata and controls
294 lines (237 loc) Β· 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
"""
Main CLI application for FigmaToBDD tool
"""
import click
import json
import os
from dotenv import load_dotenv
from typing import Dict, Any
from figma_client import FigmaClient
from bedrock_client import BedrockClient
from document_generator import DocumentGenerator
# Load environment variables
load_dotenv()
@click.group()
@click.version_option(version="1.0.0")
def cli():
"""FigmaToBDD: Extract Figma designs and generate BDD scenarios using AWS Bedrock"""
pass
@cli.command()
@click.option('--file-id', '-f', required=True, help='Figma file ID')
@click.option('--output', '-o', default='figma_data', help='Output filename (without extension)')
@click.option('--token', '-t', help='Figma access token (overrides .env)')
@click.option('--no-ssl-verify', is_flag=True, help='Disable SSL verification')
def extract_figma(file_id: str, output: str, token: str, no_ssl_verify: bool):
"""Extract design data from Figma and save as JSON"""
try:
# Get configuration
figma_token = token or os.getenv('FIGMA_ACCESS_TOKEN')
verify_ssl = not no_ssl_verify and os.getenv('VERIFY_SSL', 'true').lower() == 'true'
if not figma_token:
click.echo("Error: Figma access token is required. Set FIGMA_ACCESS_TOKEN in .env or use --token", err=True)
return
click.echo(f"π Extracting Figma design data for file ID: {file_id}")
# Initialize Figma client
figma_client = FigmaClient(figma_token, verify_ssl)
# Extract data
raw_data = figma_client.get_file(file_id)
processed_data = figma_client.extract_design_elements(raw_data)
# Save data
doc_generator = DocumentGenerator()
filepath = doc_generator.save_figma_data(processed_data, output)
click.echo(f"β
Figma data extracted and saved to: {filepath}")
click.echo(f"π Found {len(processed_data.get('pages', []))} pages")
# Display summary
for page in processed_data.get('pages', []):
click.echo(f" π Page: {page.get('name')} ({len(page.get('frames', []))} frames)")
except Exception as e:
click.echo(f"β Error extracting Figma data: {str(e)}", err=True)
@cli.command()
@click.option('--input', '-i', required=True, help='Input JSON file with Figma data')
@click.option('--output', '-o', default='bdd_scenarios', help='Output filename (without extension)')
@click.option('--type', '-T', type=click.Choice(['functional', 'ui', 'accessibility', 'performance']),
default='functional', help='Type of BDD scenarios to generate')
@click.option('--format', '-F', type=click.Choice(['markdown', 'pdf', 'html', 'all']),
default='markdown', help='Output format')
@click.option('--no-ssl-verify', is_flag=True, help='Disable SSL verification')
def generate_bdd(input: str, output: str, type: str, format: str, no_ssl_verify: bool):
"""Generate BDD scenarios from Figma JSON data using AWS Bedrock"""
try:
# Get configuration
aws_access_key = os.getenv('AWS_ACCESS_KEY_ID')
aws_secret_key = os.getenv('AWS_SECRET_ACCESS_KEY')
aws_region = os.getenv('AWS_REGION', 'us-east-1')
verify_ssl = not no_ssl_verify and os.getenv('VERIFY_SSL', 'true').lower() == 'true'
if not aws_access_key or not aws_secret_key:
click.echo("Error: AWS credentials are required. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in .env", err=True)
return
# Load Figma data
if not os.path.exists(input):
click.echo(f"Error: Input file {input} not found", err=True)
return
with open(input, 'r', encoding='utf-8') as f:
figma_data = json.load(f)
click.echo(f"π Generating {type} BDD scenarios using AWS Bedrock...")
# Initialize Bedrock client
bedrock_client = BedrockClient(aws_access_key, aws_secret_key, aws_region, verify_ssl)
# Generate scenarios
if type == 'functional':
bdd_scenarios = bedrock_client.generate_bdd_scenarios(figma_data)
else:
bdd_scenarios = bedrock_client.generate_test_scenarios(figma_data, type)
# Generate documents
doc_generator = DocumentGenerator()
if format == 'all':
generated_files = doc_generator.generate_all_formats(bdd_scenarios, figma_data, output)
click.echo("β
BDD scenarios generated in all formats:")
for fmt, filepath in generated_files.items():
click.echo(f" π {fmt.upper()}: {filepath}")
else:
if format == 'markdown':
filepath = doc_generator.generate_markdown_document(bdd_scenarios, figma_data, output)
elif format == 'pdf':
filepath = doc_generator.generate_pdf_document(bdd_scenarios, figma_data, output)
elif format == 'html':
filepath = doc_generator.generate_html_document(bdd_scenarios, figma_data, output)
click.echo(f"β
BDD scenarios generated: {filepath}")
except Exception as e:
click.echo(f"β Error generating BDD scenarios: {str(e)}", err=True)
@cli.command()
@click.option('--file-id', '-f', required=True, help='Figma file ID')
@click.option('--output', '-o', default='bdd_scenarios', help='Output filename (without extension)')
@click.option('--type', '-T', type=click.Choice(['functional', 'ui', 'accessibility', 'performance']),
default='functional', help='Type of BDD scenarios to generate')
@click.option('--format', '-F', type=click.Choice(['markdown', 'pdf', 'html', 'all']),
default='all', help='Output format')
@click.option('--figma-token', help='Figma access token (overrides .env)')
@click.option('--no-ssl-verify', is_flag=True, help='Disable SSL verification')
def full_pipeline(file_id: str, output: str, type: str, format: str, figma_token: str, no_ssl_verify: bool):
"""Complete pipeline: extract Figma data and generate BDD scenarios"""
try:
# Get configuration
figma_token = figma_token or os.getenv('FIGMA_ACCESS_TOKEN')
aws_access_key = os.getenv('AWS_ACCESS_KEY_ID')
aws_secret_key = os.getenv('AWS_SECRET_ACCESS_KEY')
aws_region = os.getenv('AWS_REGION', 'us-east-1')
verify_ssl = not no_ssl_verify and os.getenv('VERIFY_SSL', 'true').lower() == 'true'
if not figma_token:
click.echo("Error: Figma access token is required", err=True)
return
if not aws_access_key or not aws_secret_key:
click.echo("Error: AWS credentials are required", err=True)
return
click.echo(f"π Starting full pipeline for Figma file: {file_id}")
# Step 1: Extract Figma data
click.echo("π₯ Step 1: Extracting Figma design data...")
figma_client = FigmaClient(figma_token, verify_ssl)
raw_data = figma_client.get_file(file_id)
figma_data = figma_client.extract_design_elements(raw_data)
click.echo(f"β
Extracted data for {len(figma_data.get('pages', []))} pages")
# Step 2: Generate BDD scenarios
click.echo(f"π€ Step 2: Generating {type} BDD scenarios with AWS Bedrock...")
bedrock_client = BedrockClient(aws_access_key, aws_secret_key, aws_region, verify_ssl)
if type == 'functional':
bdd_scenarios = bedrock_client.generate_bdd_scenarios(figma_data)
else:
bdd_scenarios = bedrock_client.generate_test_scenarios(figma_data, type)
# Step 3: Generate documents
click.echo(f"π Step 3: Creating documents in {format} format(s)...")
doc_generator = DocumentGenerator()
if format == 'all':
generated_files = doc_generator.generate_all_formats(bdd_scenarios, figma_data, output)
click.echo("π Pipeline completed! Generated files:")
for fmt, filepath in generated_files.items():
click.echo(f" π {fmt.upper()}: {filepath}")
else:
if format == 'markdown':
filepath = doc_generator.generate_markdown_document(bdd_scenarios, figma_data, output)
elif format == 'pdf':
filepath = doc_generator.generate_pdf_document(bdd_scenarios, figma_data, output)
elif format == 'html':
filepath = doc_generator.generate_html_document(bdd_scenarios, figma_data, output)
click.echo(f"π Pipeline completed! Generated: {filepath}")
except Exception as e:
click.echo(f"β Pipeline failed: {str(e)}", err=True)
@cli.command()
def setup():
"""Display setup instructions for API keys and configuration"""
click.echo("π οΈ FigmaToBDD Setup Instructions")
click.echo("=" * 50)
click.echo("\nπ Step 1: Figma API Setup")
click.echo("-" * 25)
click.echo("1. Go to https://www.figma.com/developers/api")
click.echo("2. Click 'Get personal access token'")
click.echo("3. Log in to your Figma account")
click.echo("4. Generate a new personal access token")
click.echo("5. Copy the token and add it to your .env file:")
click.echo(" FIGMA_ACCESS_TOKEN=your_token_here")
click.echo("\n6. To get your Figma file ID:")
click.echo(" - Open your Figma file in browser")
click.echo(" - Copy the file ID from URL: https://www.figma.com/file/FILE_ID/...")
click.echo(" - Add it to .env: FIGMA_FILE_ID=your_file_id_here")
click.echo("\nπ Step 2: AWS Bedrock Setup")
click.echo("-" * 25)
click.echo("1. Go to AWS Console: https://console.aws.amazon.com/")
click.echo("2. Navigate to IAM service")
click.echo("3. Create a new user or use existing user")
click.echo("4. Attach policy: AmazonBedrockFullAccess")
click.echo("5. Generate access keys (Access Key ID + Secret)")
click.echo("6. Add to your .env file:")
click.echo(" AWS_ACCESS_KEY_ID=your_access_key")
click.echo(" AWS_SECRET_ACCESS_KEY=your_secret_key")
click.echo(" AWS_REGION=us-east-1")
click.echo("\n7. Enable Bedrock models:")
click.echo(" - Go to AWS Bedrock console")
click.echo(" - Navigate to 'Model access'")
click.echo(" - Request access to Anthropic Claude models")
click.echo("\nπ Step 3: SSL Configuration")
click.echo("-" * 25)
click.echo("For production: VERIFY_SSL=true")
click.echo("For testing/dev: VERIFY_SSL=false")
click.echo("\nπ Step 4: Install Dependencies")
click.echo("-" * 25)
click.echo("Run: pip install -r requirements.txt")
click.echo("\nπ Step 5: Usage Examples")
click.echo("-" * 25)
click.echo("# Extract Figma data only:")
click.echo("python main.py extract-figma -f YOUR_FILE_ID")
click.echo("\n# Generate BDD from existing JSON:")
click.echo("python main.py generate-bdd -i figma_data.json")
click.echo("\n# Full pipeline:")
click.echo("python main.py full-pipeline -f YOUR_FILE_ID")
click.echo("\nβ
Configuration file (.env) should contain:")
click.echo("-" * 40)
with open('.env', 'r') as f:
click.echo(f.read())
@cli.command()
@click.option('--figma-token', help='Test Figma token')
@click.option('--aws-key', help='Test AWS access key')
@click.option('--aws-secret', help='Test AWS secret key')
def test_connection(figma_token: str, aws_key: str, aws_secret: str):
"""Test connections to Figma and AWS Bedrock APIs"""
click.echo("π Testing API connections...")
# Test Figma connection
try:
token = figma_token or os.getenv('FIGMA_ACCESS_TOKEN')
if token:
figma_client = FigmaClient(token)
# Try a simple API call to test connection
click.echo("β
Figma API: Connection successful")
else:
click.echo("β Figma API: No token provided")
except Exception as e:
click.echo(f"β Figma API: Connection failed - {str(e)}")
# Test AWS Bedrock connection
try:
access_key = aws_key or os.getenv('AWS_ACCESS_KEY_ID')
secret_key = aws_secret or os.getenv('AWS_SECRET_ACCESS_KEY')
region = os.getenv('AWS_REGION', 'us-east-1')
if access_key and secret_key:
bedrock_client = BedrockClient(access_key, secret_key, region)
click.echo("β
AWS Bedrock: Connection successful")
else:
click.echo("β AWS Bedrock: No credentials provided")
except Exception as e:
click.echo(f"β AWS Bedrock: Connection failed - {str(e)}")
if __name__ == '__main__':
cli()