Cynetics / app.py
CynnixSinn
Fix: Improve readability with dark theme
9e639b5
import gradio as gr
from huggingface_hub import InferenceClient
import os
import json
import zipfile
import io
from datetime import datetime
# Initialize the client
client = InferenceClient(model="cynnix69/qwen3-coder-30b", token=os.environ.get("HF_TOKEN"))
# Store project history
project_history = []
def parse_generated_code(response):
"""Parse the generated code into separate files"""
files = {}
current_file = None
current_content = []
for line in response.split('\n'):
if line.startswith('```') and ('/' in line or '.' in line):
if current_file:
files[current_file] = '\n'.join(current_content)
current_file = line.strip('`').strip()
current_content = []
elif line.startswith('```'):
if current_file:
files[current_file] = '\n'.join(current_content)
current_file = None
current_content = []
elif current_file:
current_content.append(line)
return files if files else {"main.py": response}
def create_zip(files_dict):
"""Create a ZIP file from the generated files"""
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
for filename, content in files_dict.items():
zip_file.writestr(filename, content)
zip_buffer.seek(0)
return zip_buffer
def build_software(requirements, project_type, framework, include_tests, include_docker,
complexity, code_style, add_comments, security_level, optimization):
"""Generate complete software based on detailed requirements"""
if not requirements.strip():
return None, "❌ Please provide project requirements", "", None, ""
# Enhanced prompt with all features
prompt = f"""You are Cynetics Pro, an elite automated software architect and developer.
PROJECT SPECIFICATIONS:
- Type: {project_type}
- Framework: {framework}
- Complexity: {complexity}
- Code Style: {code_style}
- Security Level: {security_level}
- Optimization: {optimization}
REQUIREMENTS:
{requirements}
MANDATORY DELIVERABLES:
1. Complete project structure with all necessary files
2. Main application code with proper architecture
3. Configuration files (package.json, requirements.txt, etc.)
4. Comprehensive README.md with:
- Setup instructions
- Usage examples
- API documentation (if applicable)
- Environment variables needed
5. .gitignore file
6. Environment configuration (.env.example)
{'7. Complete unit tests with >80% coverage' if include_tests else ''}
{'8. Dockerfile and docker-compose.yml with optimization' if include_docker else ''}
CODE REQUIREMENTS:
- {'Add detailed inline comments explaining logic' if add_comments else 'Minimal comments, focus on clean code'}
- Security: {security_level} (include input validation, sanitization, auth best practices)
- Performance: {optimization} level optimization
- Error handling: Comprehensive try-catch blocks
- Logging: Structured logging throughout
- Type hints/annotations where applicable
OUTPUT FORMAT:
For each file, use this exact format:
```filename.ext
[file content here]
```
Generate production-ready, scalable code following industry best practices."""
try:
# Generate code
response = client.text_generation(
prompt,
max_new_tokens=4000,
temperature=0.7,
top_p=0.95,
repetition_penalty=1.1
)
# Parse response into files
files = parse_generated_code(response)
# Create file tree view
file_tree = "πŸ“ Project Structure:\n"
for filename in sorted(files.keys()):
file_tree += f"β”œβ”€β”€ {filename}\n"
# Create download zip
zip_file = create_zip(files)
# Add to history
project_history.append({
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"type": project_type,
"framework": framework,
"requirements": requirements[:100] + "...",
"files_count": len(files)
})
# Get first file for preview
preview_file = list(files.keys())[0]
preview_content = files[preview_file]
status = f"βœ… Generated {len(files)} files successfully!"
return response, status, file_tree, zip_file, preview_content
except Exception as e:
return None, f"❌ Error: {str(e)}", "", None, ""
def review_code(code, review_type):
"""AI code review with suggestions"""
prompt = f"""You are a senior code reviewer. Perform a {review_type} review of this code:
{code}
Provide:
1. Security vulnerabilities (if any)
2. Performance issues
3. Code smells
4. Best practice violations
5. Suggestions for improvement
Format as a detailed review with severity levels (Critical/High/Medium/Low)."""
try:
response = client.text_generation(
prompt,
max_new_tokens=1500,
temperature=0.5
)
return response
except Exception as e:
return f"Error during review: {str(e)}"
def refactor_code(code, refactor_goal):
"""Refactor code based on specific goal"""
prompt = f"""Refactor this code to: {refactor_goal}
Original code:
{code}
Provide:
1. Refactored code
2. Explanation of changes
3. Benefits of refactoring"""
try:
response = client.text_generation(
prompt,
max_new_tokens=2000,
temperature=0.6
)
return response
except Exception as e:
return f"Error during refactoring: {str(e)}"
def generate_tests(code, test_framework):
"""Generate comprehensive tests for the code"""
prompt = f"""Generate comprehensive unit tests for this code using {test_framework}:
{code}
Include:
1. Unit tests for all functions/methods
2. Edge cases
3. Error cases
4. Mock external dependencies
5. Test fixtures/setup"""
try:
response = client.text_generation(
prompt,
max_new_tokens=2000,
temperature=0.6
)
return response
except Exception as e:
return f"Error generating tests: {str(e)}"
def explain_code(code, explanation_level):
"""Explain code in detail"""
levels = {
"Beginner": "Explain like I'm 5, with simple analogies",
"Intermediate": "Technical explanation with some details",
"Expert": "Deep technical analysis with design patterns and architecture"
}
prompt = f"""{levels[explanation_level]}
Code to explain:
{code}
Provide a comprehensive explanation."""
try:
response = client.text_generation(
prompt,
max_new_tokens=1500,
temperature=0.5
)
return response
except Exception as e:
return f"Error explaining code: {str(e)}"
def update_framework_options(project_type):
"""Update framework dropdown based on project type"""
frameworks = {
"Web App": ["React + Node.js", "Vue.js + Express", "Next.js", "Django", "Flask", "FastAPI", "Angular + NestJS", "Svelte + Express"],
"Mobile App": ["React Native", "Flutter", "Swift (iOS)", "Kotlin (Android)", "Ionic", "NativeScript"],
"API Service": ["FastAPI", "Express.js", "Django REST", "Flask-RESTful", "Spring Boot", "ASP.NET Core", "GraphQL"],
"CLI Tool": ["Python Click", "Node.js Commander", "Go Cobra", "Rust Clap", "Python Typer"],
"Desktop App": ["Electron", "PyQt", "Tauri", ".NET MAUI", "Flutter Desktop", "GTK"],
"Data Pipeline": ["Apache Airflow", "Prefect", "Python + Pandas", "Apache Spark", "Luigi", "Dagster"],
"Machine Learning": ["PyTorch", "TensorFlow", "Scikit-learn", "Hugging Face", "JAX", "FastAI"],
"Game": ["Unity C#", "Godot", "Pygame", "Three.js", "Phaser", "LibGDX"],
"Blockchain": ["Solidity + Hardhat", "Rust + Anchor", "Web3.js", "Ethers.js"],
"DevOps Tool": ["Python + Boto3", "Terraform", "Ansible", "Kubernetes Operators"],
"Chrome Extension": ["Manifest V3 + React", "Vanilla JS", "Vue.js"],
"Discord Bot": ["Discord.py", "Discord.js", "JDA (Java)"]
}
return gr.Dropdown(choices=frameworks.get(project_type, ["Custom"]), value=frameworks.get(project_type, ["Custom"])[0])
# Custom CSS
custom_css = """
@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&display=swap');
* {
font-family: 'Space Grotesk', sans-serif;
}
#main_container {
max-width: 1600px;
margin: auto;
background: #0f1419;
}
.header {
text-align: center;
background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
color: white;
padding: 3rem;
border-radius: 15px;
margin-bottom: 2rem;
box-shadow: 0 10px 40px rgba(102, 126, 234, 0.4);
}
.header h1 {
font-size: 3.5rem;
font-weight: 700;
margin: 0;
text-shadow: 2px 2px 4px rgba(0,0,0,0.2);
}
.feature-card {
background: linear-gradient(135deg, #1a1f2e 0%, #2d3748 100%);
padding: 1.5rem;
border-radius: 12px;
border-left: 5px solid #667eea;
margin: 1rem 0;
box-shadow: 0 4px 15px rgba(0,0,0,0.3);
transition: transform 0.3s ease;
color: #e2e8f0 !important;
}
.feature-card:hover {
transform: translateY(-5px);
}
.feature-card h3 {
color: #ffffff !important;
margin-bottom: 0.5rem;
}
.feature-card p {
color: #cbd5e0 !important;
}
.feature-card small {
color: #a0aec0 !important;
}
.stat-box {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 1rem;
border-radius: 10px;
text-align: center;
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
color: white !important;
}
.stat-box h3 {
color: white !important;
margin: 0;
font-size: 2rem;
}
.stat-box p {
color: rgba(255,255,255,0.9) !important;
margin: 0.5rem 0 0 0;
}
.pro-badge {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
color: white;
padding: 0.3rem 0.8rem;
border-radius: 20px;
font-size: 0.8rem;
font-weight: 600;
display: inline-block;
margin-left: 0.5rem;
}
.tabs {
border-radius: 10px;
overflow: hidden;
}
/* Fix for all text elements */
.gradio-container {
background: #0f1419 !important;
}
label {
color: #e2e8f0 !important;
}
.prose {
color: #e2e8f0 !important;
}
/* Make sure all markdown text is visible */
.markdown-text, .markdown-text * {
color: #e2e8f0 !important;
}
"""
# Create the main interface
with gr.Blocks(css=custom_css, title="Cynetics Pro - Ultimate AI Software Builder", theme=gr.themes.Soft(primary_hue="purple")) as demo:
with gr.Column(elem_id="main_container"):
# Header
gr.HTML("""
<div class="header">
<h1>πŸš€ CYNETICS PRO</h1>
<h2>Ultimate AI Software Builder <span class="pro-badge">PREMIUM</span></h2>
<p style="font-size: 1.2rem;">From Idea to Production-Ready Code in Seconds</p>
<p>Powered by Qwen 3 Coder 30B | Built by cynnix69</p>
</div>
""")
# Stats Dashboard
with gr.Row():
with gr.Column(scale=1):
gr.HTML('<div class="stat-box"><h3 style="color: white; margin: 0;">12+</h3><p style="color: white; margin: 0.5rem 0 0 0;">Project Types</p></div>')
with gr.Column(scale=1):
gr.HTML('<div class="stat-box"><h3 style="color: white; margin: 0;">50+</h3><p style="color: white; margin: 0.5rem 0 0 0;">Frameworks</p></div>')
with gr.Column(scale=1):
gr.HTML('<div class="stat-box"><h3 style="color: white; margin: 0;">AI Powered</h3><p style="color: white; margin: 0.5rem 0 0 0;">Code Review</p></div>')
with gr.Column(scale=1):
gr.HTML('<div class="stat-box"><h3 style="color: white; margin: 0;">100%</h3><p style="color: white; margin: 0.5rem 0 0 0;">Production Ready</p></div>')
gr.Markdown("---")
# Main Tabs
with gr.Tabs() as tabs:
# Tab 1: Build Software
with gr.Tab("πŸ—οΈ Build Software"):
with gr.Row():
# Left Panel - Configuration
with gr.Column(scale=1):
gr.Markdown("### πŸ“‹ Project Configuration")
project_type = gr.Dropdown(
choices=[
"Web App",
"Mobile App",
"API Service",
"CLI Tool",
"Desktop App",
"Data Pipeline",
"Machine Learning",
"Game",
"Blockchain",
"DevOps Tool",
"Chrome Extension",
"Discord Bot"
],
label="🎯 Project Type",
value="Web App",
info="Select what you want to build"
)
framework = gr.Dropdown(
choices=["React + Node.js", "Vue.js + Express", "Next.js", "Django", "Flask", "FastAPI"],
label="⚑ Framework/Stack",
value="React + Node.js",
info="Technology stack"
)
requirements = gr.TextArea(
label="πŸ“ Requirements & Features",
placeholder="Describe your software in detail...\n\nExample:\n- User authentication with OAuth2\n- Real-time chat functionality\n- Dashboard with analytics\n- File upload with S3 integration\n- Payment processing with Stripe\n- Email notifications\n- Admin panel with role-based access",
lines=10
)
with gr.Row():
complexity = gr.Radio(
choices=["Simple", "Medium", "Complex", "Enterprise"],
label="🎚️ Complexity",
value="Medium"
)
code_style = gr.Radio(
choices=["Clean", "Documented", "Compact"],
label="✨ Code Style",
value="Clean"
)
with gr.Row():
security_level = gr.Dropdown(
choices=["Basic", "Standard", "High", "Enterprise"],
label="πŸ”’ Security Level",
value="Standard"
)
optimization = gr.Dropdown(
choices=["None", "Moderate", "High", "Maximum"],
label="⚑ Optimization",
value="Moderate"
)
gr.Markdown("### 🎁 Additional Features")
with gr.Row():
include_tests = gr.Checkbox(label="πŸ§ͺ Unit Tests", value=True)
include_docker = gr.Checkbox(label="🐳 Docker", value=True)
add_comments = gr.Checkbox(label="πŸ’¬ Comments", value=True)
with gr.Row():
clear_btn = gr.Button("πŸ—‘οΈ Clear", variant="secondary", size="sm")
build_btn = gr.Button("πŸš€ BUILD SOFTWARE", variant="primary", size="lg", scale=2)
status_output = gr.Textbox(label="Status", show_label=False, interactive=False)
# Right Panel - Output
with gr.Column(scale=1):
gr.Markdown("### πŸ’» Generated Code")
file_tree = gr.Textbox(
label="πŸ“ Project Structure",
lines=5,
interactive=False
)
code_output = gr.Code(
label="Preview",
language="python",
lines=15
)
full_output = gr.Textbox(
label="Full Generated Code",
lines=15,
max_lines=30
)
download_file = gr.File(label="πŸ“₯ Download Project ZIP")
with gr.Row():
copy_btn = gr.Button("πŸ“‹ Copy Code", variant="secondary")
share_btn = gr.Button("πŸ”— Share Project", variant="secondary")
# Tab 2: Code Review
with gr.Tab("πŸ” Code Review"):
gr.Markdown("### AI-Powered Code Review")
gr.Markdown("Get expert feedback on your code with security analysis and best practices")
with gr.Row():
with gr.Column():
review_code_input = gr.Code(
label="Paste Your Code",
language="python",
lines=15
)
review_type = gr.Radio(
choices=["Security Audit", "Performance Analysis", "Best Practices", "Complete Review"],
label="Review Type",
value="Complete Review"
)
review_btn = gr.Button("πŸ” Review Code", variant="primary")
with gr.Column():
review_output = gr.Markdown(label="Review Results")
# Tab 3: Refactor Code
with gr.Tab("♻️ Refactor"):
gr.Markdown("### Code Refactoring")
gr.Markdown("Improve your code structure and maintainability")
with gr.Row():
with gr.Column():
refactor_code_input = gr.Code(
label="Code to Refactor",
language="python",
lines=15
)
refactor_goal = gr.Dropdown(
choices=[
"Improve Performance",
"Better Readability",
"Reduce Complexity",
"Add Type Hints",
"Extract Functions",
"Apply Design Patterns",
"Async/Await Conversion"
],
label="Refactoring Goal",
value="Improve Performance"
)
refactor_btn = gr.Button("♻️ Refactor", variant="primary")
with gr.Column():
refactor_output = gr.Code(
label="Refactored Code",
language="python",
lines=20
)
# Tab 4: Generate Tests
with gr.Tab("πŸ§ͺ Test Generator"):
gr.Markdown("### Automated Test Generation")
gr.Markdown("Generate comprehensive unit tests for your code")
with gr.Row():
with gr.Column():
test_code_input = gr.Code(
label="Code to Test",
language="python",
lines=15
)
test_framework = gr.Dropdown(
choices=["pytest", "unittest", "Jest", "Mocha", "JUnit", "RSpec"],
label="Testing Framework",
value="pytest"
)
generate_tests_btn = gr.Button("πŸ§ͺ Generate Tests", variant="primary")
with gr.Column():
tests_output = gr.Code(
label="Generated Tests",
language="python",
lines=20
)
# Tab 5: Code Explainer
with gr.Tab("πŸ“– Explain Code"):
gr.Markdown("### Code Explanation")
gr.Markdown("Understand complex code with AI-powered explanations")
with gr.Row():
with gr.Column():
explain_code_input = gr.Code(
label="Code to Explain",
language="python",
lines=15
)
explanation_level = gr.Radio(
choices=["Beginner", "Intermediate", "Expert"],
label="Explanation Level",
value="Intermediate"
)
explain_btn = gr.Button("πŸ“– Explain", variant="primary")
with gr.Column():
explanation_output = gr.Markdown(label="Explanation")
# Tab 6: Project History
with gr.Tab("πŸ“š History"):
gr.Markdown("### Your Project History")
history_output = gr.Dataframe(
headers=["Timestamp", "Type", "Framework", "Requirements", "Files"],
datatype=["str", "str", "str", "str", "number"],
label="Generated Projects"
)
refresh_history_btn = gr.Button("πŸ”„ Refresh History")
# Examples Section
gr.Markdown("---")
gr.Markdown("## πŸ’‘ Featured Project Templates")
with gr.Row():
with gr.Column():
gr.HTML("""
<div class="feature-card">
<h3 style="color: #ffffff !important; font-size: 1.3rem; margin-bottom: 0.5rem;">πŸ›’ E-Commerce Platform</h3>
<p style="color: #e2e8f0 !important; font-size: 1rem; margin-bottom: 0.5rem;">Full-stack online store with payment integration, inventory management, and admin dashboard</p>
<small style="color: #a0aec0 !important;">Stack: Next.js + Node.js + PostgreSQL</small>
</div>
""")
with gr.Column():
gr.HTML("""
<div class="feature-card">
<h3 style="color: #ffffff !important; font-size: 1.3rem; margin-bottom: 0.5rem;">πŸ“Š SaaS Analytics Dashboard</h3>
<p style="color: #e2e8f0 !important; font-size: 1rem; margin-bottom: 0.5rem;">Real-time analytics with charts, user management, and subscription billing</p>
<small style="color: #a0aec0 !important;">Stack: React + FastAPI + Redis</small>
</div>
""")
with gr.Column():
gr.HTML("""
<div class="feature-card">
<h3 style="color: #ffffff !important; font-size: 1.3rem; margin-bottom: 0.5rem;">πŸ€– AI Chatbot API</h3>
<p style="color: #e2e8f0 !important; font-size: 1rem; margin-bottom: 0.5rem;">Scalable chatbot service with NLP, webhooks, and multi-channel support</p>
<small style="color: #a0aec0 !important;">Stack: Python + FastAPI + ML</small>
</div>
""")
gr.Examples(
examples=[
[
"Build a comprehensive project management SaaS with:\n- User authentication (OAuth2 + JWT)\n- Real-time collaboration (WebSockets)\n- Kanban board with drag-and-drop\n- Time tracking and reporting\n- File attachments (S3)\n- Email notifications\n- Team management\n- API for integrations\n- Mobile responsive design",
"Web App",
"Next.js",
True,
True,
"Complex",
"Documented",
True,
"High",
"High"
],
[
"Create a RESTful API for a social media platform:\n- User profiles and authentication\n- Post creation with media upload\n- Like, comment, share functionality\n- Follow/unfollow system\n- Feed algorithm\n- Real-time notifications\n- Rate limiting\n- Redis caching\n- Full API documentation",
"API Service",
"FastAPI",
True,
True,
"Enterprise",
"Clean",
True,
"Enterprise",
"Maximum"
],
[
"Build a cryptocurrency trading bot:\n- Connect to exchange APIs\n- Technical indicators (RSI, MACD, Bollinger)\n- Automated trading strategies\n- Risk management\n- Portfolio tracking\n- Backtesting system\n- Telegram notifications\n- Database for trade history",
"CLI Tool",
"Python Click",
True,
False,
"Complex",
"Documented",
True,
"High",
"High"
],
],
inputs=[requirements, project_type, framework, include_tests, include_docker,
complexity, code_style, add_comments, security_level, optimization]
)
# Footer
gr.Markdown("---")
gr.Markdown("""
<div style="text-align: center; color: #666; padding: 2rem;">
<h3>🌟 Why Cynetics Pro?</h3>
<div style="display: flex; justify-content: space-around; margin: 2rem 0;">
<div>⚑ <b>Lightning Fast</b><br>Generate in seconds</div>
<div>πŸ”’ <b>Enterprise Security</b><br>Production-grade code</div>
<div>πŸ§ͺ <b>Comprehensive Tests</b><br>80%+ coverage</div>
<div>πŸ“¦ <b>Ready to Deploy</b><br>Docker included</div>
<div>🎯 <b>Best Practices</b><br>Clean architecture</div>
</div>
<p>πŸ”’ Privacy First: Your code is never stored | Generated in real-time</p>
<p>Powered by <b>Qwen 3 Coder 30B</b> | Built with ❀️ by <b>cynnix69</b></p>
<p><a href="https://huggingface.co/cynnix69" target="_blank">πŸ€— Visit My Profile</a></p>
</div>
""")
# Event Handlers
# Update framework options
project_type.change(
fn=update_framework_options,
inputs=[project_type],
outputs=[framework]
)
# Build software
build_btn.click(
fn=build_software,
inputs=[requirements, project_type, framework, include_tests, include_docker,
complexity, code_style, add_comments, security_level, optimization],
outputs=[full_output, status_output, file_tree, download_file, code_output]
)
# Clear inputs
clear_btn.click(
fn=lambda: ("", "", "", None, ""),
outputs=[requirements, full_output, file_tree, download_file, code_output]
)
# Code Review
review_btn.click(
fn=review_code,
inputs=[review_code_input, review_type],
outputs=[review_output]
)
# Refactor
refactor_btn.click(
fn=refactor_code,
inputs=[refactor_code_input, refactor_goal],
outputs=[refactor_output]
)
# Generate Tests
generate_tests_btn.click(
fn=generate_tests,
inputs=[test_code_input, test_framework],
outputs=[tests_output]
)
# Explain Code
explain_btn.click(
fn=explain_code,
inputs=[explain_code_input, explanation_level],
outputs=[explanation_output]
)
# Refresh History
def get_history():
if not project_history:
return []
return [[p["timestamp"], p["type"], p["framework"], p["requirements"], p["files_count"]]
for p in project_history]
refresh_history_btn.click(
fn=get_history,
outputs=[history_output]
)
if __name__ == "__main__":
demo.launch(share=False)