Spaces:
Sleeping
Sleeping
Commit
·
5193b03
1
Parent(s):
31f6748
Demo version
Browse files
app.py
CHANGED
|
@@ -1,837 +1,187 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import zipfile
|
| 3 |
-
import io
|
| 4 |
-
import os
|
| 5 |
-
from datetime import datetime
|
| 6 |
import requests
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
try:
|
| 15 |
-
# Create a more specific prompt for Flutter/Dart code using Qwen's strengths
|
| 16 |
-
full_prompt = f"""You are an expert Flutter developer. Generate clean, working Dart code for this requirement:
|
| 17 |
|
| 18 |
-
|
|
|
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
|
| 23 |
-
|
| 24 |
-
"""
|
| 25 |
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
payload = {
|
| 29 |
-
"inputs":
|
| 30 |
"parameters": {
|
| 31 |
-
"
|
| 32 |
-
"temperature": 0.
|
|
|
|
| 33 |
"do_sample": True,
|
| 34 |
-
"return_full_text": False
|
| 35 |
-
"num_return_sequences": 1,
|
| 36 |
-
"top_p": 0.9, # Better sampling for code
|
| 37 |
-
"repetition_penalty": 1.1, # Reduce repetition
|
| 38 |
}
|
| 39 |
}
|
| 40 |
|
| 41 |
-
response = requests.post(
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
else:
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
# Clean up the generated text
|
| 52 |
-
code = generated_text.strip()
|
| 53 |
-
|
| 54 |
-
# Basic cleanup - try to extract Dart-like code
|
| 55 |
-
if "```dart" in code:
|
| 56 |
-
code = code.split("```dart")[1].split("```")[0]
|
| 57 |
-
elif "```" in code:
|
| 58 |
-
code = code.split("```")[1].split("```")[0]
|
| 59 |
-
|
| 60 |
-
# Remove any remaining markdown formatting
|
| 61 |
-
code = code.replace("```", "").strip()
|
| 62 |
-
|
| 63 |
-
# Additional cleanup for common issues
|
| 64 |
-
code = code.replace("dart\n", "").replace("Dart\n", "")
|
| 65 |
-
|
| 66 |
-
return code if code else "// Generated using Qwen 3 0.6B AI model\n// Please try rephrasing your request"
|
| 67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
except Exception as e:
|
| 69 |
-
|
| 70 |
-
return "// Error: AI service unavailable\n// Using fallback template"
|
| 71 |
-
|
| 72 |
-
def generate_flutter_code(description):
|
| 73 |
-
"""
|
| 74 |
-
Generate Flutter code files based on user description using Qwen 3 0.6B AI model.
|
| 75 |
-
|
| 76 |
-
Args:
|
| 77 |
-
description: User's description of the Flutter app/widget
|
| 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 |
-
zip_file.writestr('flutter_app/lib/widgets.dart', widgets_dart)
|
| 103 |
-
|
| 104 |
-
# Generate models.dart
|
| 105 |
-
models_dart = generate_models_dart(description)
|
| 106 |
-
zip_file.writestr('flutter_app/lib/models.dart', models_dart)
|
| 107 |
-
|
| 108 |
-
# Generate services.dart
|
| 109 |
-
services_dart = generate_services_dart(description)
|
| 110 |
-
zip_file.writestr('flutter_app/lib/services.dart', services_dart)
|
| 111 |
-
|
| 112 |
-
# Generate pubspec.yaml
|
| 113 |
-
pubspec = generate_pubspec(description)
|
| 114 |
-
zip_file.writestr('flutter_app/pubspec.yaml', pubspec)
|
| 115 |
-
|
| 116 |
-
# Generate README.md
|
| 117 |
-
readme = generate_readme(description)
|
| 118 |
-
zip_file.writestr('flutter_app/README.md', readme)
|
| 119 |
-
|
| 120 |
-
# Save the ZIP to a temporary file
|
| 121 |
-
zip_buffer.seek(0)
|
| 122 |
-
output_path = f"flutter_app_{timestamp}.zip"
|
| 123 |
-
|
| 124 |
-
with open(output_path, 'wb') as f:
|
| 125 |
-
f.write(zip_buffer.getvalue())
|
| 126 |
-
|
| 127 |
-
success_message = f"""
|
| 128 |
-
✅ **Flutter code generated successfully using Qwen 3 0.6B!**
|
| 129 |
-
|
| 130 |
-
🤖 **AI Model:** Qwen 3 0.6B (specialized for code generation)
|
| 131 |
-
📝 **Your description:** {description[:100]}{'...' if len(description) > 100 else ''}
|
| 132 |
-
|
| 133 |
-
📦 **Generated files:**
|
| 134 |
-
- `lib/main.dart` - Main application entry point
|
| 135 |
-
- `lib/widgets.dart` - Custom widgets with Material Design
|
| 136 |
-
- `lib/models.dart` - Data models with JSON serialization
|
| 137 |
-
- `lib/services.dart` - Business logic and validation services
|
| 138 |
-
- `pubspec.yaml` - Project dependencies
|
| 139 |
-
- `README.md` - Setup and usage instructions
|
| 140 |
-
|
| 141 |
-
💡 **Next steps:**
|
| 142 |
-
1. Download the ZIP file below
|
| 143 |
-
2. Extract it to your desired location
|
| 144 |
-
3. Run `flutter pub get` in the project directory
|
| 145 |
-
4. Run `flutter run` to launch the app
|
| 146 |
-
|
| 147 |
-
⚠️ **Important:** This is AI-generated code using Qwen 3 0.6B. While high-quality, always review and test before production use.
|
| 148 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
|
| 150 |
-
return output_path, success_message, main_dart, widgets_dart, models_dart, services_dart
|
| 151 |
-
|
| 152 |
-
except Exception as e:
|
| 153 |
-
error_message = f"❌ Error generating Flutter code: {str(e)}"
|
| 154 |
-
return None, error_message, "// Error occurred", "// Error occurred", "// Error occurred", "// Error occurred"
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
def generate_main_dart(description):
|
| 158 |
-
"""Generate the main.dart file content using Qwen AI."""
|
| 159 |
-
prompt = f"""Generate a complete Flutter main.dart file for: {description}
|
| 160 |
-
|
| 161 |
-
Requirements:
|
| 162 |
-
1. Import necessary packages (flutter/material.dart)
|
| 163 |
-
2. Create main() function
|
| 164 |
-
3. Create MyApp widget extending StatelessWidget
|
| 165 |
-
4. Include MaterialApp with proper theme
|
| 166 |
-
5. Create a basic HomePage widget
|
| 167 |
-
6. Include app bar and basic layout
|
| 168 |
-
7. Use modern Flutter syntax with const constructors
|
| 169 |
-
|
| 170 |
-
Code structure:
|
| 171 |
-
```dart
|
| 172 |
-
import 'package:flutter/material.dart';
|
| 173 |
-
|
| 174 |
-
void main() => runApp(const MyApp());
|
| 175 |
-
|
| 176 |
-
class MyApp extends StatelessWidget {{
|
| 177 |
-
const MyApp({{super.key}});
|
| 178 |
-
|
| 179 |
-
@override
|
| 180 |
-
Widget build(BuildContext context) {{
|
| 181 |
-
return MaterialApp(
|
| 182 |
-
title: 'Generated App',
|
| 183 |
-
theme: ThemeData(primarySwatch: Colors.blue, useMaterial3: true),
|
| 184 |
-
home: const HomePage(),
|
| 185 |
-
);
|
| 186 |
-
}}
|
| 187 |
-
}}
|
| 188 |
-
|
| 189 |
-
class HomePage extends StatelessWidget {{
|
| 190 |
-
const HomePage({{super.key}});
|
| 191 |
-
|
| 192 |
-
@override
|
| 193 |
-
Widget build(BuildContext context) {{
|
| 194 |
-
return Scaffold(
|
| 195 |
-
appBar: AppBar(title: const Text('Home')),
|
| 196 |
-
body: const Center(child: Text('Welcome to your app!')),
|
| 197 |
-
);
|
| 198 |
-
}}
|
| 199 |
-
}}
|
| 200 |
-
```"""
|
| 201 |
-
|
| 202 |
-
ai_generated_code = generate_code_with_ai(prompt, max_length=1000)
|
| 203 |
-
|
| 204 |
-
# Add header comment
|
| 205 |
-
header = f"""// AI-Generated Flutter Application
|
| 206 |
-
// Description: {description}
|
| 207 |
-
// Generated: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
|
| 208 |
-
// Note: This is AI-generated code - review and test before production use
|
| 209 |
-
|
| 210 |
-
"""
|
| 211 |
-
|
| 212 |
-
return header + ai_generated_code
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
def generate_widgets_dart(description):
|
| 216 |
-
"""Generate the widgets.dart file content using Qwen AI."""
|
| 217 |
-
prompt = f"""Generate Flutter custom widgets for: {description}
|
| 218 |
-
|
| 219 |
-
Create at least 3 reusable widgets with proper documentation:
|
| 220 |
-
|
| 221 |
-
1. CustomInfoCard - A styled card widget for displaying information
|
| 222 |
-
2. CustomButton - An enhanced button with loading states
|
| 223 |
-
3. CustomTextField - A styled text input field
|
| 224 |
-
|
| 225 |
-
Requirements:
|
| 226 |
-
- Use proper Dart documentation comments (///)
|
| 227 |
-
- Include null safety and const constructors
|
| 228 |
-
- Follow Material Design guidelines
|
| 229 |
-
- Include proper parameter validation
|
| 230 |
-
- Use modern Flutter patterns
|
| 231 |
-
|
| 232 |
-
Example structure:
|
| 233 |
-
```dart
|
| 234 |
-
import 'package:flutter/material.dart';
|
| 235 |
-
|
| 236 |
-
/// Custom info card widget for displaying content
|
| 237 |
-
class CustomInfoCard extends StatelessWidget {{
|
| 238 |
-
final String title;
|
| 239 |
-
final String description;
|
| 240 |
-
final IconData? icon;
|
| 241 |
-
final Color? backgroundColor;
|
| 242 |
-
|
| 243 |
-
const CustomInfoCard({{
|
| 244 |
-
super.key,
|
| 245 |
-
required this.title,
|
| 246 |
-
required this.description,
|
| 247 |
-
this.icon,
|
| 248 |
-
this.backgroundColor,
|
| 249 |
-
}});
|
| 250 |
-
|
| 251 |
-
@override
|
| 252 |
-
Widget build(BuildContext context) {{
|
| 253 |
-
return Card(
|
| 254 |
-
elevation: 4,
|
| 255 |
-
color: backgroundColor,
|
| 256 |
-
margin: const EdgeInsets.all(16),
|
| 257 |
-
child: Padding(
|
| 258 |
-
padding: const EdgeInsets.all(20),
|
| 259 |
-
child: Column(
|
| 260 |
-
mainAxisSize: MainAxisSize.min,
|
| 261 |
-
children: [
|
| 262 |
-
if (icon != null) ...[
|
| 263 |
-
Icon(icon, size: 48, color: Theme.of(context).primaryColor),
|
| 264 |
-
const SizedBox(height: 12),
|
| 265 |
-
],
|
| 266 |
-
Text(
|
| 267 |
-
title,
|
| 268 |
-
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
|
| 269 |
-
fontWeight: FontWeight.bold,
|
| 270 |
-
),
|
| 271 |
-
textAlign: TextAlign.center,
|
| 272 |
-
),
|
| 273 |
-
const SizedBox(height: 8),
|
| 274 |
-
Text(
|
| 275 |
-
description,
|
| 276 |
-
style: Theme.of(context).textTheme.bodyMedium,
|
| 277 |
-
textAlign: TextAlign.center,
|
| 278 |
-
),
|
| 279 |
-
],
|
| 280 |
-
),
|
| 281 |
-
),
|
| 282 |
-
);
|
| 283 |
-
}}
|
| 284 |
-
}}
|
| 285 |
-
```"""
|
| 286 |
-
|
| 287 |
-
ai_generated_code = generate_code_with_ai(prompt, max_length=1200)
|
| 288 |
-
|
| 289 |
-
# Add header comment
|
| 290 |
-
header = f"""// Custom Widgets for the Flutter Application
|
| 291 |
-
// Description: {description}
|
| 292 |
-
// Generated: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
|
| 293 |
-
// Note: This is AI-generated code - review and test before production use
|
| 294 |
-
|
| 295 |
-
"""
|
| 296 |
-
|
| 297 |
-
return header + ai_generated_code
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
def generate_models_dart(description):
|
| 301 |
-
"""Generate the models.dart file content using Qwen AI."""
|
| 302 |
-
prompt = f"""Generate Flutter data models for: {description}
|
| 303 |
-
|
| 304 |
-
Create comprehensive data models with:
|
| 305 |
-
1. Proper class structure with const constructors
|
| 306 |
-
2. JSON serialization (toJson/fromJson)
|
| 307 |
-
3. CopyWith methods for immutable updates
|
| 308 |
-
4. Proper type annotations and null safety
|
| 309 |
-
5. Documentation comments
|
| 310 |
-
6. At least 2-3 models relevant to the app
|
| 311 |
-
|
| 312 |
-
Requirements:
|
| 313 |
-
- Use final fields for immutability
|
| 314 |
-
- Include proper error handling in fromJson
|
| 315 |
-
- Add copyWith for state management
|
| 316 |
-
- Use meaningful field names
|
| 317 |
-
|
| 318 |
-
Example structure:
|
| 319 |
-
```dart
|
| 320 |
-
/// Represents a task or item in the application
|
| 321 |
-
class Item {{
|
| 322 |
-
final String id;
|
| 323 |
-
final String title;
|
| 324 |
-
final String description;
|
| 325 |
-
final DateTime createdAt;
|
| 326 |
-
final DateTime? updatedAt;
|
| 327 |
-
final bool isCompleted;
|
| 328 |
-
final String? category;
|
| 329 |
-
|
| 330 |
-
const Item({{
|
| 331 |
-
required this.id,
|
| 332 |
-
required this.title,
|
| 333 |
-
required this.description,
|
| 334 |
-
required this.createdAt,
|
| 335 |
-
this.updatedAt,
|
| 336 |
-
this.isCompleted = false,
|
| 337 |
-
this.category,
|
| 338 |
-
}});
|
| 339 |
-
|
| 340 |
-
/// Convert to JSON for storage/API calls
|
| 341 |
-
Map<String, dynamic> toJson() => {{
|
| 342 |
-
'id': id,
|
| 343 |
-
'title': title,
|
| 344 |
-
'description': description,
|
| 345 |
-
'createdAt': createdAt.toIso8601String(),
|
| 346 |
-
'updatedAt': updatedAt?.toIso8601String(),
|
| 347 |
-
'isCompleted': isCompleted,
|
| 348 |
-
'category': category,
|
| 349 |
-
}};
|
| 350 |
-
|
| 351 |
-
/// Create from JSON data
|
| 352 |
-
factory Item.fromJson(Map<String, dynamic> json) => Item(
|
| 353 |
-
id: json['id'] as String? ?? '',
|
| 354 |
-
title: json['title'] as String? ?? '',
|
| 355 |
-
description: json['description'] as String? ?? '',
|
| 356 |
-
createdAt: DateTime.tryParse(json['createdAt'] as String? ?? '') ?? DateTime.now(),
|
| 357 |
-
updatedAt: json['updatedAt'] != null
|
| 358 |
-
? DateTime.tryParse(json['updatedAt'] as String)
|
| 359 |
-
: null,
|
| 360 |
-
isCompleted: json['isCompleted'] as bool? ?? false,
|
| 361 |
-
category: json['category'] as String?,
|
| 362 |
-
);
|
| 363 |
-
|
| 364 |
-
/// Create a copy with updated fields
|
| 365 |
-
Item copyWith({{
|
| 366 |
-
String? id,
|
| 367 |
-
String? title,
|
| 368 |
-
String? description,
|
| 369 |
-
DateTime? createdAt,
|
| 370 |
-
DateTime? updatedAt,
|
| 371 |
-
bool? isCompleted,
|
| 372 |
-
String? category,
|
| 373 |
-
}}) => Item(
|
| 374 |
-
id: id ?? this.id,
|
| 375 |
-
title: title ?? this.title,
|
| 376 |
-
description: description ?? this.description,
|
| 377 |
-
createdAt: createdAt ?? this.createdAt,
|
| 378 |
-
updatedAt: updatedAt ?? this.updatedAt,
|
| 379 |
-
isCompleted: isCompleted ?? this.isCompleted,
|
| 380 |
-
category: category ?? this.category,
|
| 381 |
-
);
|
| 382 |
-
}}
|
| 383 |
-
```"""
|
| 384 |
-
|
| 385 |
-
ai_generated_code = generate_code_with_ai(prompt, max_length=1000)
|
| 386 |
-
|
| 387 |
-
# Add header comment
|
| 388 |
-
header = f"""// Data Models for the Flutter Application
|
| 389 |
-
// Description: {description}
|
| 390 |
-
// Generated: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
|
| 391 |
-
// Note: This is AI-generated code - review and test before production use
|
| 392 |
-
|
| 393 |
-
"""
|
| 394 |
-
|
| 395 |
-
return header + ai_generated_code
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
def generate_services_dart(description):
|
| 399 |
-
"""Generate the services.dart file content using Qwen AI."""
|
| 400 |
-
prompt = f"""Generate Flutter service classes for: {description}
|
| 401 |
-
|
| 402 |
-
Create comprehensive service classes with:
|
| 403 |
-
1. DataService - For managing application data (CRUD operations)
|
| 404 |
-
2. ValidationService - For input validation and utilities
|
| 405 |
-
3. Proper error handling and state management
|
| 406 |
-
4. Documentation comments
|
| 407 |
-
5. Null safety and modern Dart patterns
|
| 408 |
-
|
| 409 |
-
Requirements:
|
| 410 |
-
- Use proper async/await patterns where applicable
|
| 411 |
-
- Include error handling with try-catch blocks
|
| 412 |
-
- Add meaningful method names and documentation
|
| 413 |
-
- Use immutable data structures where possible
|
| 414 |
-
|
| 415 |
-
Example structure:
|
| 416 |
-
```dart
|
| 417 |
-
import 'dart:convert';
|
| 418 |
-
import 'models.dart';
|
| 419 |
-
|
| 420 |
-
/// Service for managing application data and business logic
|
| 421 |
-
class DataService {{
|
| 422 |
-
final List<Item> _items = [];
|
| 423 |
-
|
| 424 |
-
/// Get all items (returns unmodifiable list)
|
| 425 |
-
List<Item> getAllItems() => List.unmodifiable(_items);
|
| 426 |
-
|
| 427 |
-
/// Get items by completion status
|
| 428 |
-
List<Item> getItems({{bool? completed}}) {{
|
| 429 |
-
if (completed == null) return getAllItems();
|
| 430 |
-
return _items.where((item) => item.isCompleted == completed).toList();
|
| 431 |
-
}}
|
| 432 |
-
|
| 433 |
-
/// Add a new item to the collection
|
| 434 |
-
void addItem(Item item) {{
|
| 435 |
-
_items.add(item);
|
| 436 |
-
}}
|
| 437 |
-
|
| 438 |
-
/// Update an existing item by ID
|
| 439 |
-
bool updateItem(String id, Item updatedItem) {{
|
| 440 |
-
final index = _items.indexWhere((item) => item.id == id);
|
| 441 |
-
if (index != -1) {{
|
| 442 |
-
_items[index] = updatedItem;
|
| 443 |
-
return true;
|
| 444 |
-
}}
|
| 445 |
-
return false;
|
| 446 |
-
}}
|
| 447 |
-
|
| 448 |
-
/// Remove an item by ID
|
| 449 |
-
bool deleteItem(String id) {{
|
| 450 |
-
final index = _items.indexWhere((item) => item.id == id);
|
| 451 |
-
if (index != -1) {{
|
| 452 |
-
_items.removeAt(index);
|
| 453 |
-
return true;
|
| 454 |
-
}}
|
| 455 |
-
return false;
|
| 456 |
-
}}
|
| 457 |
-
|
| 458 |
-
/// Toggle completion status of an item
|
| 459 |
-
bool toggleItemCompletion(String id) {{
|
| 460 |
-
final index = _items.indexWhere((item) => item.id == id);
|
| 461 |
-
if (index != -1) {{
|
| 462 |
-
_items[index] = _items[index].copyWith(
|
| 463 |
-
isCompleted: !_items[index].isCompleted,
|
| 464 |
-
updatedAt: DateTime.now(),
|
| 465 |
-
);
|
| 466 |
-
return true;
|
| 467 |
-
}}
|
| 468 |
-
return false;
|
| 469 |
-
}}
|
| 470 |
-
|
| 471 |
-
/// Clear all items
|
| 472 |
-
void clearAll() {{
|
| 473 |
-
_items.clear();
|
| 474 |
-
}}
|
| 475 |
-
}}
|
| 476 |
-
|
| 477 |
-
/// Utility service for validation and data processing
|
| 478 |
-
class ValidationService {{
|
| 479 |
-
/// Validate email format using regex
|
| 480 |
-
static bool isValidEmail(String email) {{
|
| 481 |
-
final emailRegex = RegExp(
|
| 482 |
-
r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{{2,}}$',
|
| 483 |
-
);
|
| 484 |
-
return emailRegex.hasMatch(email);
|
| 485 |
-
}}
|
| 486 |
-
|
| 487 |
-
/// Check if string is not null or empty
|
| 488 |
-
static bool isNotEmpty(String? value) {{
|
| 489 |
-
return value != null && value.trim().isNotEmpty;
|
| 490 |
-
}}
|
| 491 |
-
|
| 492 |
-
/// Check minimum length requirement
|
| 493 |
-
static bool hasMinLength(String value, int minLength) {{
|
| 494 |
-
return value.length >= minLength;
|
| 495 |
-
}}
|
| 496 |
-
|
| 497 |
-
/// Validate item data before saving
|
| 498 |
-
static String? validateItem(Item item) {{
|
| 499 |
-
if (!isNotEmpty(item.title)) {{
|
| 500 |
-
return 'Title cannot be empty';
|
| 501 |
-
}}
|
| 502 |
-
if (!hasMinLength(item.title, 3)) {{
|
| 503 |
-
return 'Title must be at least 3 characters long';
|
| 504 |
-
}}
|
| 505 |
-
if (!isNotEmpty(item.description)) {{
|
| 506 |
-
return 'Description cannot be empty';
|
| 507 |
-
}}
|
| 508 |
-
return null; // No validation errors
|
| 509 |
-
}}
|
| 510 |
-
}}
|
| 511 |
-
```"""
|
| 512 |
-
|
| 513 |
-
ai_generated_code = generate_code_with_ai(prompt, max_length=1000)
|
| 514 |
-
|
| 515 |
-
# Add header comment
|
| 516 |
-
header = f"""// Business Logic and Services
|
| 517 |
-
// Description: {description}
|
| 518 |
-
// Generated: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
|
| 519 |
-
// Note: This is AI-generated code - review and test before production use
|
| 520 |
-
|
| 521 |
-
"""
|
| 522 |
-
|
| 523 |
-
return header + ai_generated_code
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
def generate_pubspec(description):
|
| 527 |
-
"""Generate the pubspec.yaml file content."""
|
| 528 |
-
return f"""# Flutter Project Configuration
|
| 529 |
-
# Description: {description}
|
| 530 |
-
# Generated: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
|
| 531 |
-
|
| 532 |
-
name: flutter_app
|
| 533 |
-
description: AI-generated Flutter application
|
| 534 |
-
publish_to: 'none'
|
| 535 |
-
|
| 536 |
-
version: 1.0.0+1
|
| 537 |
-
|
| 538 |
-
environment:
|
| 539 |
-
sdk: '>=3.0.0 <4.0.0'
|
| 540 |
-
|
| 541 |
-
dependencies:
|
| 542 |
-
flutter:
|
| 543 |
-
sdk: flutter
|
| 544 |
-
|
| 545 |
-
# UI Components
|
| 546 |
-
cupertino_icons: ^1.0.6
|
| 547 |
-
|
| 548 |
-
# State Management (uncomment as needed)
|
| 549 |
-
# provider: ^6.1.1
|
| 550 |
-
# riverpod: ^2.4.9
|
| 551 |
-
|
| 552 |
-
# Networking (uncomment as needed)
|
| 553 |
-
# http: ^1.1.0
|
| 554 |
-
# dio: ^5.4.0
|
| 555 |
-
|
| 556 |
-
# Local Storage (uncomment as needed)
|
| 557 |
-
# shared_preferences: ^2.2.2
|
| 558 |
-
# hive: ^2.2.3
|
| 559 |
-
|
| 560 |
-
dev_dependencies:
|
| 561 |
-
flutter_test:
|
| 562 |
-
sdk: flutter
|
| 563 |
-
flutter_lints: ^3.0.1
|
| 564 |
-
|
| 565 |
-
flutter:
|
| 566 |
-
uses-material-design: true
|
| 567 |
-
|
| 568 |
-
# Assets (uncomment and configure as needed)
|
| 569 |
-
# assets:
|
| 570 |
-
# - assets/images/
|
| 571 |
-
# - assets/icons/
|
| 572 |
-
|
| 573 |
-
# Fonts (uncomment and configure as needed)
|
| 574 |
-
# fonts:
|
| 575 |
-
# - family: CustomFont
|
| 576 |
-
# fonts:
|
| 577 |
-
# - asset: fonts/CustomFont-Regular.ttf
|
| 578 |
-
# - asset: fonts/CustomFont-Bold.ttf
|
| 579 |
-
# weight: 700
|
| 580 |
-
"""
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
def generate_readme(description):
|
| 584 |
-
"""Generate the README.md file content."""
|
| 585 |
-
return f"""# Flutter Application
|
| 586 |
-
|
| 587 |
-
🤖 **AI-Generated Flutter Project**
|
| 588 |
-
|
| 589 |
-
## Description
|
| 590 |
-
|
| 591 |
-
{description}
|
| 592 |
-
|
| 593 |
-
---
|
| 594 |
-
|
| 595 |
-
## 📋 Project Structure
|
| 596 |
-
|
| 597 |
-
```
|
| 598 |
-
flutter_app/
|
| 599 |
-
├── lib/
|
| 600 |
-
│ ├── main.dart # Application entry point
|
| 601 |
-
│ ├── widgets.dart # Custom UI widgets
|
| 602 |
-
│ ├── models.dart # Data models
|
| 603 |
-
│ └── services.dart # Business logic and services
|
| 604 |
-
├── pubspec.yaml # Project dependencies
|
| 605 |
-
└── README.md # This file
|
| 606 |
-
```
|
| 607 |
-
|
| 608 |
-
## 🚀 Getting Started
|
| 609 |
-
|
| 610 |
-
### Prerequisites
|
| 611 |
-
|
| 612 |
-
- Flutter SDK (>=3.0.0)
|
| 613 |
-
- Dart SDK
|
| 614 |
-
- IDE (VS Code, Android Studio, or IntelliJ)
|
| 615 |
-
|
| 616 |
-
### Installation
|
| 617 |
-
|
| 618 |
-
1. **Extract the ZIP file** to your desired location
|
| 619 |
-
|
| 620 |
-
2. **Navigate to the project directory**
|
| 621 |
-
```bash
|
| 622 |
-
cd flutter_app
|
| 623 |
-
```
|
| 624 |
-
|
| 625 |
-
3. **Install dependencies**
|
| 626 |
-
```bash
|
| 627 |
-
flutter pub get
|
| 628 |
-
```
|
| 629 |
-
|
| 630 |
-
4. **Run the app**
|
| 631 |
-
```bash
|
| 632 |
-
flutter run
|
| 633 |
-
```
|
| 634 |
-
|
| 635 |
-
## 🛠️ Customization
|
| 636 |
-
|
| 637 |
-
This is a generated starter project. You may want to:
|
| 638 |
-
|
| 639 |
-
- ✏️ Modify the UI in `lib/widgets.dart`
|
| 640 |
-
- 📊 Add more data models in `lib/models.dart`
|
| 641 |
-
- ⚙️ Extend business logic in `lib/services.dart`
|
| 642 |
-
- 📦 Add dependencies in `pubspec.yaml`
|
| 643 |
-
|
| 644 |
-
## 📱 Building for Production
|
| 645 |
-
|
| 646 |
-
### Android
|
| 647 |
-
```bash
|
| 648 |
-
flutter build apk --release
|
| 649 |
-
```
|
| 650 |
-
|
| 651 |
-
### iOS
|
| 652 |
-
```bash
|
| 653 |
-
flutter build ios --release
|
| 654 |
-
```
|
| 655 |
-
|
| 656 |
-
### Web
|
| 657 |
-
```bash
|
| 658 |
-
flutter build web --release
|
| 659 |
-
```
|
| 660 |
-
|
| 661 |
-
## 🧪 Testing
|
| 662 |
-
|
| 663 |
-
Run tests with:
|
| 664 |
-
```bash
|
| 665 |
-
flutter test
|
| 666 |
-
```
|
| 667 |
-
|
| 668 |
-
## 📚 Resources
|
| 669 |
-
|
| 670 |
-
- [Flutter Documentation](https://docs.flutter.dev/)
|
| 671 |
-
- [Dart Documentation](https://dart.dev/guides)
|
| 672 |
-
- [Flutter Cookbook](https://docs.flutter.dev/cookbook)
|
| 673 |
-
|
| 674 |
-
## ⚠️ Important Notes
|
| 675 |
-
|
| 676 |
-
- This code was AI-generated and serves as a starting point
|
| 677 |
-
- Review and test all code before production use
|
| 678 |
-
- Customize the app according to your specific requirements
|
| 679 |
-
- Add proper error handling and validation
|
| 680 |
-
|
| 681 |
-
## 📄 License
|
| 682 |
-
|
| 683 |
-
This project is generated for educational and development purposes.
|
| 684 |
-
|
| 685 |
-
---
|
| 686 |
-
|
| 687 |
-
Generated on: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
|
| 688 |
-
"""
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
# Create the Gradio interface
|
| 692 |
-
def create_interface():
|
| 693 |
-
"""Create and configure the Gradio interface."""
|
| 694 |
-
|
| 695 |
-
with gr.Blocks(theme=gr.themes.Soft(), title="Flutter Code Generator") as demo:
|
| 696 |
-
gr.Markdown(
|
| 697 |
-
"""
|
| 698 |
-
# 🚀 AI Flutter Code Generator
|
| 699 |
-
|
| 700 |
-
Generate complete Flutter applications from natural language descriptions!
|
| 701 |
-
|
| 702 |
-
### How to use:
|
| 703 |
-
1. Describe the Flutter app or widget you want to build
|
| 704 |
-
2. Click "Generate Flutter Code"
|
| 705 |
-
3. Download the ZIP file containing your Flutter project
|
| 706 |
-
4. Extract and run with `flutter pub get` then `flutter run`
|
| 707 |
-
"""
|
| 708 |
-
)
|
| 709 |
-
|
| 710 |
with gr.Row():
|
| 711 |
with gr.Column(scale=2):
|
| 712 |
-
|
| 713 |
-
label="Describe your Flutter
|
| 714 |
-
placeholder="
|
| 715 |
lines=6,
|
| 716 |
-
|
| 717 |
)
|
| 718 |
|
| 719 |
-
gr.
|
| 720 |
-
""
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
|
| 724 |
-
- Include details about data storage needs
|
| 725 |
-
- Describe any animations or interactions
|
| 726 |
-
"""
|
| 727 |
)
|
| 728 |
|
| 729 |
generate_btn = gr.Button(
|
| 730 |
-
"
|
| 731 |
variant="primary",
|
| 732 |
size="lg"
|
| 733 |
)
|
| 734 |
|
| 735 |
-
with gr.Column(scale=
|
| 736 |
-
|
| 737 |
-
label="
|
| 738 |
-
value="👋 Ready to generate your Flutter app!"
|
| 739 |
-
)
|
| 740 |
-
|
| 741 |
-
file_output = gr.File(
|
| 742 |
-
label="📦 Download Flutter Project",
|
| 743 |
-
type="filepath"
|
| 744 |
-
)
|
| 745 |
-
|
| 746 |
-
# Code preview tabs
|
| 747 |
-
with gr.Tabs():
|
| 748 |
-
with gr.TabItem("📱 main.dart"):
|
| 749 |
-
main_code_output = gr.Code(
|
| 750 |
-
label="Main Application Code",
|
| 751 |
-
language="dart",
|
| 752 |
-
lines=20,
|
| 753 |
-
value="// Click 'Generate Flutter Code' to see your main.dart code here"
|
| 754 |
-
)
|
| 755 |
-
|
| 756 |
-
with gr.TabItem("🎨 widgets.dart"):
|
| 757 |
-
widgets_code_output = gr.Code(
|
| 758 |
-
label="Custom Widgets Code",
|
| 759 |
language="dart",
|
| 760 |
lines=20,
|
| 761 |
-
|
| 762 |
)
|
| 763 |
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
|
| 777 |
-
|
| 778 |
-
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
""
|
| 782 |
-
|
| 783 |
-
|
| 784 |
-
|
| 785 |
-
- **main.dart** - Application entry point with basic structure
|
| 786 |
-
- **widgets.dart** - Reusable custom widgets
|
| 787 |
-
- **models.dart** - Data models and structures
|
| 788 |
-
- **services.dart** - Business logic and services
|
| 789 |
-
- **pubspec.yaml** - Flutter dependencies configuration
|
| 790 |
-
- **README.md** - Setup and usage instructions
|
| 791 |
-
|
| 792 |
-
### ⚠️ Important Notes:
|
| 793 |
-
- This uses **Qwen 3 0.6B** - a powerful AI model optimized for code generation
|
| 794 |
-
- The AI generates Flutter/Dart code based on your description
|
| 795 |
-
- Always review and test generated code before production use
|
| 796 |
-
- The AI service may occasionally be slow or unavailable - try again if needed
|
| 797 |
-
- Customize the generated code to match your specific requirements
|
| 798 |
-
|
| 799 |
-
### 🔧 Next Steps After Download:
|
| 800 |
-
1. Extract the ZIP file
|
| 801 |
-
2. Open terminal in the project directory
|
| 802 |
-
3. Run `flutter pub get` to install dependencies
|
| 803 |
-
4. Run `flutter run` to launch the app
|
| 804 |
-
5. Customize and extend the generated code
|
| 805 |
-
"""
|
| 806 |
-
)
|
| 807 |
-
|
| 808 |
-
# Connect the button to the generation function
|
| 809 |
generate_btn.click(
|
| 810 |
fn=generate_flutter_code,
|
| 811 |
-
inputs=[
|
| 812 |
-
outputs=
|
|
|
|
| 813 |
)
|
| 814 |
-
|
| 815 |
-
#
|
| 816 |
gr.Examples(
|
| 817 |
examples=[
|
| 818 |
-
["Create a
|
| 819 |
-
["Build a
|
| 820 |
-
["Design a
|
| 821 |
-
["
|
|
|
|
| 822 |
],
|
| 823 |
-
inputs=
|
| 824 |
-
label="
|
| 825 |
)
|
| 826 |
-
|
| 827 |
-
return demo
|
| 828 |
|
|
|
|
| 829 |
|
| 830 |
# Launch the app
|
| 831 |
if __name__ == "__main__":
|
| 832 |
-
|
| 833 |
-
|
| 834 |
-
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import requests
|
| 3 |
+
import os
|
| 4 |
|
| 5 |
+
def generate_flutter_code(prompt, api_token=None):
|
| 6 |
+
"""
|
| 7 |
+
Generate Flutter/Dart code using Hugging Face Inference API with Qwen 3 0.6B
|
| 8 |
+
"""
|
| 9 |
+
if not api_token:
|
| 10 |
+
api_token = os.getenv("HF_TOKEN")
|
| 11 |
|
| 12 |
+
if not api_token:
|
| 13 |
+
return "Error: Hugging Face API token is required. Please provide it in the input field or set HF_TOKEN environment variable."
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
# Qwen 3 0.6B model for code generation
|
| 16 |
+
model_id = "Qwen/Qwen3-0.6B"
|
| 17 |
|
| 18 |
+
# Enhanced prompt for Flutter/Dart code generation
|
| 19 |
+
enhanced_prompt = f"""You are an expert Flutter/Dart developer. Generate high-quality, production-ready Flutter/Dart code based on the following description. Include proper error handling, state management, and follow Flutter best practices.
|
| 20 |
|
| 21 |
+
Description: {prompt}
|
|
|
|
| 22 |
|
| 23 |
+
Please provide:
|
| 24 |
+
1. Complete Dart code with all necessary imports
|
| 25 |
+
2. Proper widget structure
|
| 26 |
+
3. State management if needed
|
| 27 |
+
4. Comments explaining complex parts
|
| 28 |
+
5. Error handling where appropriate
|
| 29 |
+
|
| 30 |
+
Generate the code:"""
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
# Hugging Face Inference API endpoint
|
| 34 |
+
api_url = f"https://api-inference.huggingface.co/models/{model_id}"
|
| 35 |
+
|
| 36 |
+
headers = {
|
| 37 |
+
"Authorization": f"Bearer {api_token}",
|
| 38 |
+
"Content-Type": "application/json"
|
| 39 |
+
}
|
| 40 |
|
| 41 |
payload = {
|
| 42 |
+
"inputs": enhanced_prompt,
|
| 43 |
"parameters": {
|
| 44 |
+
"max_new_tokens": 2048,
|
| 45 |
+
"temperature": 0.1,
|
| 46 |
+
"top_p": 0.95,
|
| 47 |
"do_sample": True,
|
| 48 |
+
"return_full_text": False
|
|
|
|
|
|
|
|
|
|
| 49 |
}
|
| 50 |
}
|
| 51 |
|
| 52 |
+
response = requests.post(api_url, headers=headers, json=payload, timeout=30)
|
| 53 |
+
|
| 54 |
+
if response.status_code == 200:
|
| 55 |
+
result = response.json()
|
| 56 |
+
if isinstance(result, list) and len(result) > 0:
|
| 57 |
+
generated_text = result[0].get("generated_text", "")
|
| 58 |
+
return generated_text.strip()
|
| 59 |
+
else:
|
| 60 |
+
return "Error: Unexpected response format from API"
|
| 61 |
+
elif response.status_code == 503:
|
| 62 |
+
return "Error: Model is currently loading. Please try again in a few moments."
|
| 63 |
+
elif response.status_code == 429:
|
| 64 |
+
return "Error: Rate limit exceeded. Please try again later."
|
| 65 |
else:
|
| 66 |
+
return f"Error: API request failed with status code {response.status_code}. Response: {response.text}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
+
except requests.exceptions.Timeout:
|
| 69 |
+
return "Error: Request timed out. The model might be busy."
|
| 70 |
+
except requests.exceptions.RequestException as e:
|
| 71 |
+
return f"Error: Network request failed: {str(e)}"
|
| 72 |
except Exception as e:
|
| 73 |
+
return f"Error: Unexpected error occurred: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
+
# Gradio interface
|
| 76 |
+
def create_interface():
|
| 77 |
+
with gr.Blocks(
|
| 78 |
+
title="Flutter Code Generator",
|
| 79 |
+
theme=gr.themes.Soft(),
|
| 80 |
+
css="""
|
| 81 |
+
.gradio-container {
|
| 82 |
+
max-width: 1200px;
|
| 83 |
+
margin: auto;
|
| 84 |
+
}
|
| 85 |
+
.title {
|
| 86 |
+
text-align: center;
|
| 87 |
+
color: #2563eb;
|
| 88 |
+
font-size: 2.5em;
|
| 89 |
+
font-weight: bold;
|
| 90 |
+
margin-bottom: 1em;
|
| 91 |
+
}
|
| 92 |
+
.subtitle {
|
| 93 |
+
text-align: center;
|
| 94 |
+
color: #64748b;
|
| 95 |
+
font-size: 1.2em;
|
| 96 |
+
margin-bottom: 2em;
|
| 97 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
"""
|
| 99 |
+
) as interface:
|
| 100 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
with gr.Row():
|
| 106 |
with gr.Column(scale=2):
|
| 107 |
+
prompt_input = gr.Textbox(
|
| 108 |
+
label="Describe your Flutter component or feature",
|
| 109 |
+
placeholder="e.g., Create a login form with email and password fields, validation, and submit button...",
|
| 110 |
lines=6,
|
| 111 |
+
show_copy_button=True
|
| 112 |
)
|
| 113 |
|
| 114 |
+
api_token_input = gr.Textbox(
|
| 115 |
+
label="Hugging Face API Token (optional)",
|
| 116 |
+
placeholder="Enter your HF token or set HF_TOKEN env variable",
|
| 117 |
+
type="password",
|
| 118 |
+
show_copy_button=True
|
|
|
|
|
|
|
|
|
|
| 119 |
)
|
| 120 |
|
| 121 |
generate_btn = gr.Button(
|
| 122 |
+
"Generate Flutter Code ✨",
|
| 123 |
variant="primary",
|
| 124 |
size="lg"
|
| 125 |
)
|
| 126 |
|
| 127 |
+
with gr.Column(scale=3):
|
| 128 |
+
output_code = gr.Code(
|
| 129 |
+
label="Generated Flutter/Dart Code",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
language="dart",
|
| 131 |
lines=20,
|
| 132 |
+
show_copy_button=True
|
| 133 |
)
|
| 134 |
|
| 135 |
+
with gr.Accordion("How to use", open=False):
|
| 136 |
+
gr.Markdown("""
|
| 137 |
+
### Getting Started
|
| 138 |
+
1. **Describe your component**: Write a clear description of the Flutter component you want to create
|
| 139 |
+
2. **API Token**: Get your token from [Hugging Face](https://huggingface.co/settings/tokens) or set `HF_TOKEN` environment variable
|
| 140 |
+
3. **Generate**: Click the button to generate production-ready Flutter/Dart code
|
| 141 |
+
|
| 142 |
+
### Tips for Better Results
|
| 143 |
+
- Be specific about the UI components, layout, and functionality
|
| 144 |
+
- Mention state management needs (e.g., "using Provider" or "using setState")
|
| 145 |
+
- Specify styling preferences (colors, themes, responsive design)
|
| 146 |
+
- Include error handling requirements
|
| 147 |
+
- Mention any specific Flutter packages to use
|
| 148 |
+
|
| 149 |
+
### Example Prompts
|
| 150 |
+
- "Create a shopping cart component with add/remove items, quantity counter, and total price calculation"
|
| 151 |
+
- "Build a weather app screen with current conditions, 7-day forecast, and location search using Riverpod"
|
| 152 |
+
- "Design a user profile page with avatar, edit form, and save functionality"
|
| 153 |
+
""")
|
| 154 |
+
|
| 155 |
+
# Event handling
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
generate_btn.click(
|
| 157 |
fn=generate_flutter_code,
|
| 158 |
+
inputs=[prompt_input, api_token_input],
|
| 159 |
+
outputs=output_code,
|
| 160 |
+
api_name="generate_code"
|
| 161 |
)
|
| 162 |
+
|
| 163 |
+
# Examples
|
| 164 |
gr.Examples(
|
| 165 |
examples=[
|
| 166 |
+
["Create a beautiful login screen with email/password fields, remember me checkbox, and social login buttons"],
|
| 167 |
+
["Build a product card widget with image, title, price, rating stars, and add to cart button"],
|
| 168 |
+
["Design a settings page with toggle switches, dropdown menus, and theme selector"],
|
| 169 |
+
["Create a chat message bubble component with sender info, timestamp, and message status"],
|
| 170 |
+
["Build a dashboard with statistics cards, charts, and navigation drawer"]
|
| 171 |
],
|
| 172 |
+
inputs=prompt_input,
|
| 173 |
+
label="Example prompts to try:"
|
| 174 |
)
|
|
|
|
|
|
|
| 175 |
|
| 176 |
+
return interface
|
| 177 |
|
| 178 |
# Launch the app
|
| 179 |
if __name__ == "__main__":
|
| 180 |
+
interface = create_interface()
|
| 181 |
+
interface.queue(max_size=10) # Enable queuing for multiple users
|
| 182 |
+
interface.launch(
|
| 183 |
+
server_name="0.0.0.0",
|
| 184 |
+
server_port=int(os.getenv("PORT", 7860)),
|
| 185 |
+
show_error=True,
|
| 186 |
+
share=False # Set to True for public sharing on HF Spaces
|
| 187 |
+
)
|