import os import gc import re import json import uuid import time import shutil import random import sqlite3 import zipfile import threading import traceback from pathlib import Path from datetime import datetime os.environ["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "1" os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1" os.environ["TOKENIZERS_PARALLELISM"] = "false" import spaces import gradio as gr import torch from PIL import Image from diffusers import ( DiffusionPipeline, AutoPipelineForImage2Image, ) from transformers import ( AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer, StoppingCriteria, StoppingCriteriaList, ) from threading import Thread, Event # ========================================================= # CONFIGURATION # ========================================================= APP_NAME = "ARISE AI Studio" DEVELOPER_TELEGRAM = "https://t.me/hardhackar009" MAX_INPUT_LENGTH = 4096 MAX_HISTORY_MESSAGES = 10 MAX_UPLOAD_FILES = 100 MAX_FILE_SIZE = 10 * 1024 * 1024 MAX_PROJECT_SIZE = 100 * 1024 * 1024 MAX_CONTEXT_SIZE = 80000 IMAGE_DTYPE = torch.float16 DATA_DIR = Path(os.getenv("ARISE_DATA_DIR", "/data/arise_ai_studio")) try: DATA_DIR.mkdir(parents=True, exist_ok=True) test_file = DATA_DIR / ".write_test" test_file.write_text("ok") test_file.unlink() except Exception: DATA_DIR = Path("./arise_ai_studio_data") DATA_DIR.mkdir(parents=True, exist_ok=True) DB_PATH = DATA_DIR / "arise_history.db" PROJECTS_DIR = DATA_DIR / "projects" PROJECTS_DIR.mkdir(parents=True, exist_ok=True) SUPPORTED_TEXT_EXTENSIONS = { ".py", ".js", ".jsx", ".ts", ".tsx", ".html", ".htm", ".css", ".scss", ".json", ".xml", ".yaml", ".yml", ".md", ".txt", ".java", ".kt", ".gradle", ".properties", ".sh", ".bat", ".c", ".cpp", ".h", ".hpp", ".php", ".sql", ".go", ".rs", ".swift", ".dart", ".vue", ".svelte", ".toml", ".ini", ".cfg", ".env.example", ".gitignore", ".dockerfile", } EXCLUDED_DIRS = { ".git", ".gradle", ".idea", ".vscode", "__pycache__", "node_modules", "build", "dist", ".venv", "venv", ".next", } IMAGE_MODELS = { "SDXL Turbo": {"id": "stabilityai/sdxl-turbo", "steps": 4, "guidance": 0.0, "max_steps": 4}, "Stable Diffusion 1.5": {"id": "stable-diffusion-v1-5/stable-diffusion-v1-5", "steps": 25, "guidance": 7.5, "max_steps": 30}, "SD Turbo": {"id": "stabilityai/sd-turbo", "steps": 4, "guidance": 0.0, "max_steps": 4}, "Tiny SD": {"id": "segmind/tiny-sd", "steps": 20, "guidance": 7.5, "max_steps": 30}, } IMAGE_TO_IMAGE_MODELS = { "Stable Diffusion 1.5 Img2Img": "stable-diffusion-v1-5/stable-diffusion-v1-5", } CODE_MODELS = { "Qwen Coder 0.5B": "Qwen/Qwen2.5-Coder-0.5B-Instruct", "Qwen Coder 1.5B": "Qwen/Qwen2.5-Coder-1.5B-Instruct", "DeepSeek Coder 1.3B": "deepseek-ai/deepseek-coder-1.3b-instruct", "Qwen Coder 3B": "Qwen/Qwen2.5-Coder-3B-Instruct", "StarCoder2 3B": "bigcode/starcoder2-3b", "CodeGen 350M": "Salesforce/codegen-350M-mono", } # ========================================================= # DATABASE (Optimized) # ========================================================= db_lock = threading.RLock() def db_connect(): connection = sqlite3.connect(str(DB_PATH), timeout=30, check_same_thread=False) connection.row_factory = sqlite3.Row return connection def initialize_database(): with db_lock: connection = db_connect() connection.execute(""" CREATE TABLE IF NOT EXISTS conversations ( id TEXT PRIMARY KEY, session_id TEXT NOT NULL, title TEXT NOT NULL, history TEXT NOT NULL, created TEXT NOT NULL, updated TEXT NOT NULL ) """) connection.execute(""" CREATE TABLE IF NOT EXISTS jobs ( id TEXT PRIMARY KEY, session_id TEXT NOT NULL, conversation_id TEXT NOT NULL, status TEXT NOT NULL, prompt TEXT NOT NULL, response TEXT NOT NULL, error TEXT, created TEXT NOT NULL, updated TEXT NOT NULL ) """) connection.commit() connection.close() initialize_database() def now_string(): return datetime.utcnow().isoformat(timespec="seconds") def get_project_dir(conversation_id): path = PROJECTS_DIR / conversation_id path.mkdir(parents=True, exist_ok=True) return path def save_conversation(session_id, conversation_id, title, history): timestamp = now_string() with db_lock: connection = db_connect() connection.execute(""" INSERT INTO conversations (id, session_id, title, history, created, updated) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET title=excluded.title, history=excluded.history, updated=excluded.updated """, (conversation_id, session_id, title, json.dumps(history, ensure_ascii=False), timestamp, timestamp)) connection.commit() connection.close() def get_conversations(session_id): with db_lock: connection = db_connect() rows = connection.execute(""" SELECT id, title, updated FROM conversations WHERE session_id=? ORDER BY updated DESC """, (session_id,)).fetchall() connection.close() return [(f"{row['title']} ยท {row['updated']}", row["id"]) for row in rows] def get_conversation(session_id, conversation_id): with db_lock: connection = db_connect() row = connection.execute(""" SELECT * FROM conversations WHERE id=? AND session_id=? """, (conversation_id, session_id)).fetchone() connection.close() if not row: return None return {"id": row["id"], "title": row["title"], "history": json.loads(row["history"])} def delete_conversations(session_id, conversation_ids): if not conversation_ids: return with db_lock: connection = db_connect() for cid in conversation_ids: connection.execute("DELETE FROM conversations WHERE id=? AND session_id=?", (cid, session_id)) connection.execute("DELETE FROM jobs WHERE conversation_id=? AND session_id=?", (cid, session_id)) project_dir = PROJECTS_DIR / cid if project_dir.exists(): shutil.rmtree(project_dir, ignore_errors=True) connection.commit() connection.close() def create_conversation(session_id, title="New Project"): conversation_id = uuid.uuid4().hex save_conversation(session_id, conversation_id, title, []) get_project_dir(conversation_id) return conversation_id def update_job(job_id, **values): if not values: return values["updated"] = now_string() assignments = ", ".join(f"{key}=?" for key in values) parameters = list(values.values()) + [job_id] with db_lock: connection = db_connect() connection.execute(f"UPDATE jobs SET {assignments} WHERE id=?", parameters) connection.commit() connection.close() def create_job(session_id, conversation_id, prompt): job_id = uuid.uuid4().hex timestamp = now_string() with db_lock: connection = db_connect() connection.execute(""" INSERT INTO jobs (id, session_id, conversation_id, status, prompt, response, error, created, updated) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) """, (job_id, session_id, conversation_id, "queued", prompt, "", None, timestamp, timestamp)) connection.commit() connection.close() return job_id def get_job(job_id, session_id): with db_lock: connection = db_connect() row = connection.execute("SELECT * FROM jobs WHERE id=? AND session_id=?", (job_id, session_id)).fetchone() connection.close() return dict(row) if row else None def get_active_job(session_id, conversation_id): with db_lock: connection = db_connect() row = connection.execute(""" SELECT * FROM jobs WHERE session_id=? AND conversation_id=? AND status IN ('queued', 'running') ORDER BY created DESC LIMIT 1 """, (session_id, conversation_id)).fetchone() connection.close() return dict(row) if row else None # ========================================================= # MODEL CACHE # ========================================================= image_cache = {"name": None, "pipe": None} code_cache = {"name": None, "tokenizer": None, "model": None} image_lock = threading.RLock() code_lock = threading.RLock() job_threads = {} job_threads_lock = threading.RLock() job_stop_events = {} def clear_image_cache(): old_pipe = image_cache["pipe"] image_cache["pipe"] = None image_cache["name"] = None if old_pipe is not None: del old_pipe gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache() def clear_code_cache(): old_model = code_cache["model"] old_tokenizer = code_cache["tokenizer"] code_cache["model"] = None code_cache["tokenizer"] = None code_cache["name"] = None if old_model is not None: del old_model if old_tokenizer is not None: del old_tokenizer gc.collect() def load_image_pipeline(model_id, mode): cache_key = f"{mode}:{model_id}" with image_lock: if image_cache["name"] == cache_key and image_cache["pipe"] is not None: return image_cache["pipe"] clear_image_cache() if mode == "text": pipe = DiffusionPipeline.from_pretrained(model_id, torch_dtype=IMAGE_DTYPE, token=False) elif mode == "image": pipe = AutoPipelineForImage2Image.from_pretrained(model_id, torch_dtype=IMAGE_DTYPE, token=False) else: raise ValueError("Invalid image mode.") pipe = pipe.to("cuda") if hasattr(pipe, "enable_attention_slicing"): pipe.enable_attention_slicing() image_cache["pipe"] = pipe image_cache["name"] = cache_key return pipe @spaces.GPU(duration=120) def generate_image(prompt, negative_prompt, model_name, width, height, steps, seed, random_seed): if not prompt or not prompt.strip(): raise gr.Error("Enter an image prompt.") if model_name not in IMAGE_MODELS: raise gr.Error("Invalid image model.") config = IMAGE_MODELS[model_name] if random_seed: seed = random.randint(0, 2147483647) seed = int(seed or 0) width = (max(256, min(int(width), 768)) // 8) * 8 height = (max(256, min(int(height), 768)) // 8) * 8 actual_steps = min(max(int(steps), 1), config["max_steps"]) if model_name in ["SDXL Turbo", "SD Turbo"]: actual_steps = min(actual_steps, 4) try: with image_lock: pipe = load_image_pipeline(config["id"], "text") generator = torch.Generator(device="cuda").manual_seed(seed) result = pipe( prompt=prompt.strip(), negative_prompt=negative_prompt or None, width=width, height=height, num_inference_steps=actual_steps, guidance_scale=config["guidance"], generator=generator, ) return result.images[0], seed except Exception as error: traceback.print_exc() raise gr.Error(f"Image generation failed: {error}") @spaces.GPU(duration=120) def generate_image_to_image(input_image, prompt, negative_prompt, model_name, strength, steps, guidance, seed, random_seed): if input_image is None: raise gr.Error("Upload an image.") if not prompt or not prompt.strip(): raise gr.Error("Enter transformation prompt.") if model_name not in IMAGE_TO_IMAGE_MODELS: raise gr.Error("Invalid image model.") if random_seed: seed = random.randint(0, 2147483647) seed = int(seed or 0) strength = max(0.05, min(float(strength), 0.95)) steps = max(1, min(int(steps), 30)) try: image = input_image.convert("RGB") image.thumbnail((768, 768), Image.Resampling.LANCZOS) width = max(256, (image.width // 8) * 8) height = max(256, (image.height // 8) * 8) image = image.resize((width, height), Image.Resampling.LANCZOS) model_id = IMAGE_TO_IMAGE_MODELS[model_name] with image_lock: pipe = load_image_pipeline(model_id, "image") generator = torch.Generator(device="cuda").manual_seed(seed) result = pipe( prompt=prompt.strip(), image=image, negative_prompt=negative_prompt or None, strength=strength, num_inference_steps=steps, guidance_scale=float(guidance), generator=generator, ) return result.images[0], seed except Exception as error: traceback.print_exc() raise gr.Error(f"Image-to-image failed: {error}") # ========================================================= # SYSTEM PROMPT & FILE HELPERS # ========================================================= SYSTEM_PROMPT = """ You are ARISE AI, a professional software engineering assistant. When modifying project files, return every complete modified or new file using exactly this format: <<>> complete file content here <<>> Do not use absolute paths. Do not omit required imports or code. """ def load_code_model(model_name): if model_name not in CODE_MODELS: raise ValueError("Invalid coding model.") model_id = CODE_MODELS[model_name] with code_lock: if code_cache["name"] == model_id and code_cache["model"] is not None: return code_cache["tokenizer"], code_cache["model"] clear_code_cache() tokenizer = AutoTokenizer.from_pretrained(model_id, token=False) model = AutoModelForCausalLM.from_pretrained( model_id, token=False, torch_dtype=torch.float32, low_cpu_mem_usage=True, ) model.to("cpu") model.eval() code_cache["name"] = model_id code_cache["tokenizer"] = tokenizer code_cache["model"] = model return tokenizer, model def safe_relative_path(value): value = str(value).replace("\\", "/").strip() path = Path(value) if not value or path.is_absolute() or ".." in path.parts or "\x00" in value: raise ValueError("Unsafe project file path.") return path def is_text_file(path): return (path.suffix.lower() in SUPPORTED_TEXT_EXTENSIONS or path.name.lower() in {"dockerfile", "makefile", ".gitignore"}) def project_files(project_dir): result = [] for root, dirs, files in os.walk(project_dir): dirs[:] = [name for name in dirs if name not in EXCLUDED_DIRS] for filename in files: full_path = Path(root) / filename if full_path.name == "project_index.json": continue try: relative = full_path.relative_to(project_dir) size = full_path.stat().st_size except Exception: continue result.append({"path": relative.as_posix(), "size": size, "text": is_text_file(full_path)}) return result def build_project_context(project_dir): files = project_files(project_dir) output = ["PROJECT STRUCTURE:", json.dumps(files, ensure_ascii=False, indent=2), "", "PROJECT FILE CONTENTS:"] total = 0 for item in files: if not item["text"]: continue path = project_dir / item["path"] try: content = path.read_text(encoding="utf-8", errors="replace") except Exception: continue section = f"\n\n===== FILE: {item['path']} =====\n{content}\n===== END FILE =====\n" if total + len(section) > MAX_CONTEXT_SIZE: output.append("\n[Project context truncated due to configured context limit.]") break output.append(section) total += len(section) return "\n".join(output), files FILE_BLOCK_PATTERN = re.compile( r"<<>>\s*(.*?)\s*<<>>", re.DOTALL | re.IGNORECASE, ) def apply_file_changes(response, project_dir): changed = [] for match in FILE_BLOCK_PATTERN.finditer(response): relative_name = match.group(1).strip() content = match.group(2) try: relative = safe_relative_path(relative_name) except Exception: continue target = Path(project_dir) / relative target.parent.mkdir(parents=True, exist_ok=True) target.write_text(content.rstrip() + "\n", encoding="utf-8") changed.append(relative.as_posix()) return changed def create_project_zip(project_dir): project_dir = Path(project_dir) zip_path = DATA_DIR / ("ARISE_Project_" + uuid.uuid4().hex[:10] + ".zip") with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as archive: for root, dirs, files in os.walk(project_dir): dirs[:] = [name for name in dirs if name not in EXCLUDED_DIRS] for filename in files: full_path = Path(root) / filename if full_path == zip_path: continue archive.write(full_path, full_path.relative_to(project_dir)) return str(zip_path) def create_single_file_download(project_dir, relative_name): relative = safe_relative_path(relative_name) source = Path(project_dir) / relative if not source.exists() or not source.is_file(): return None download_dir = DATA_DIR / "downloads" download_dir.mkdir(exist_ok=True) destination = download_dir / (uuid.uuid4().hex[:8] + "_" + source.name) shutil.copy2(source, destination) return str(destination) def make_html_preview(project_dir): project_dir = Path(project_dir) html_files = list(project_dir.rglob("index.html")) or list(project_dir.rglob("*.html")) if not html_files: return "
No HTML file found in this project.
" html_file = html_files[0] try: html = html_file.read_text(encoding="utf-8", errors="replace") def replace_asset(match): asset_name = match.group(1).split("?")[0].split("#")[0] asset_path = (html_file.parent / asset_name).resolve() try: asset_path.relative_to(project_dir.resolve()) except ValueError: return match.group(0) if not asset_path.exists(): return match.group(0) content = asset_path.read_text(encoding="utf-8", errors="replace") if match.group(0).lower().startswith("\n" + content + "\n" return "" html = re.sub(r']+href=["\']([^"\']+\.css)["\'][^>]*>', replace_asset, html, flags=re.IGNORECASE) html = re.sub(r']+src=["\']([^"\']+\.js)["\'][^>]*>\s*', replace_asset, html, flags=re.IGNORECASE) return f""" """ except Exception as error: return f"
Preview error: {error}
" class StopCriteria(StoppingCriteria): def __init__(self, event): self.event = event def __call__(self, input_ids, scores, **kwargs): return self.event.is_set() # ========================================================= # CODING WORKER (Throttled for smooth streaming) # ========================================================= def run_coding_worker(job_id, session_id, conversation_id, prompt, model_name, max_tokens, temperature, stop_event): try: update_job(job_id, status="running", response="") project_dir = get_project_dir(conversation_id) project_context, files = build_project_context(project_dir) tokenizer, model = load_code_model(model_name) messages = [{"role": "system", "content": SYSTEM_PROMPT}] conversation = get_conversation(session_id, conversation_id) history = conversation["history"] if conversation else [] for item in history[-MAX_HISTORY_MESSAGES:]: if (isinstance(item, dict) and item.get("role") in ["user", "assistant"] and isinstance(item.get("content"), str)): messages.append({"role": item["role"], "content": item["content"]}) project_prompt = prompt if files: project_prompt = ( "PROJECT CONTEXT:\n" + project_context + "\n\nUSER REQUEST:\n" + prompt + "\n\n" + "Analyze the supplied project before editing. Make only the requested changes. " + "Return every changed/new file using the required <<>> format." ) messages.append({"role": "user", "content": project_prompt}) if getattr(tokenizer, "chat_template", None): formatted_prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) else: formatted_prompt = "\n\n".join(f"{i['role'].upper()}:\n{i['content']}" for i in messages) + "\n\nASSISTANT:\n" inputs = tokenizer(formatted_prompt, return_tensors="pt", truncation=True, max_length=MAX_INPUT_LENGTH) streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=120) generation_kwargs = { **inputs, "streamer": streamer, "max_new_tokens": max(128, min(int(max_tokens), 2048)), "do_sample": float(temperature) > 0.05, "temperature": max(float(temperature), 0.05), "pad_token_id": tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id, "stopping_criteria": StoppingCriteriaList([StopCriteria(stop_event)]), } errors = [] def generate(): try: with torch.inference_mode(): model.generate(**generation_kwargs) except Exception as error: errors.append(str(error)) traceback.print_exc() try: streamer.end() except Exception: pass generation_thread = Thread(target=generate, daemon=True) generation_thread.start() response = "" last_db_update = time.time() for token in streamer: if stop_event.is_set(): break response += token # ๐Ÿ”ฅ LAG FIX: Update database only every 0.2 seconds instead of every token if time.time() - last_db_update > 0.2: update_job(job_id, response=response, status="running") last_db_update = time.time() generation_thread.join(timeout=15) if generation_thread.is_alive(): stop_event.set() if errors: raise RuntimeError(errors[0]) if stop_event.is_set(): update_job(job_id, status="stopped", response=response + "\n\nGeneration stopped.") return if not response.strip(): response = "No response generated." changed_files = apply_file_changes(response, project_dir) history = history + [ {"role": "user", "content": prompt}, {"role": "assistant", "content": response}, ] title = prompt.strip().replace("\n", " ")[:55] or "ARISE Project" save_conversation(session_id, conversation_id, title, history) final_response = response if changed_files: file_status = "\n".join( f"- โœ“ `{name}` โ€” Edited" for name in changed_files ) final_response += "\n\n---\n### Project File Updates\n" + file_status update_job(job_id, status="completed", response=final_response) except Exception as error: traceback.print_exc() update_job(job_id, status="error", error=str(error), response=f"**Coding error:** {error}") finally: with job_threads_lock: job_threads.pop(job_id, None) job_stop_events.pop(job_id, None) def coding_assistant(prompt, model_name, max_tokens, temperature, conversation_id, request: gr.Request): if not prompt or not prompt.strip(): yield ("Please enter your coding request.", conversation_id, "Waiting for prompt.", None, None, None) return session_id = request.session_hash if request else "default" if not conversation_id: conversation_id = create_conversation(session_id, prompt.strip().replace("\n", " ")[:55]) project_dir = get_project_dir(conversation_id) job_id = create_job(session_id, conversation_id, prompt.strip()) stop_event = Event() with job_threads_lock: job_stop_events[job_id] = stop_event worker = Thread( target=run_coding_worker, args=(job_id, session_id, conversation_id, prompt.strip(), model_name, max_tokens, temperature, stop_event), daemon=True, ) job_threads[job_id] = worker worker.start() yield ("โณ ARISE AI is analyzing your request...", conversation_id, "Job started.", None, None, job_id) previous_response = "" while True: job = get_job(job_id, session_id) if not job: yield ("Job not found.", conversation_id, "Job unavailable.", None, None, job_id) return response = job["response"] or "" status = job["status"] status_text = { "queued": "โณ Waiting in queue", "running": "โš™๏ธ ARISE AI is working", "completed": "โœ… Coding completed", "stopped": "โน Generation stopped", "error": "โŒ Job failed", }.get(status, status) if response != previous_response or status not in ["queued", "running"]: previous_response = response zip_file = None single_file = None if status == "completed": zip_file = create_project_zip(project_dir) changed = apply_file_changes(response, project_dir) if changed: single_file = create_single_file_download(project_dir, changed[-1]) yield (response or "No response yet.", conversation_id, status_text, zip_file, single_file, job_id) if status not in ["queued", "running"]: return time.sleep(0.5) # ๐Ÿ”ฅ Faster UI polling def resume_job(job_id, request: gr.Request): session_id = request.session_hash if request else "default" if not job_id: yield ("No active job selected.", "Nothing to resume.", None, None) return while True: job = get_job(job_id, session_id) if not job: yield ("Job not found for this session.", "Job unavailable.", None, None) return status = job["status"] response = job["response"] or "" yield (response, f"Job status: {status}", None, None) if status not in ["queued", "running"]: return time.sleep(1.5) def stop_job(job_id): if not job_id: return "No active job." with job_threads_lock: event = job_stop_events.get(job_id) if event: event.set() return "โน Stop requested." return "No running job found." # ========================================================= # HISTORY # ========================================================= def refresh_history(request: gr.Request): session_id = request.session_hash if request else "default" return gr.Dropdown(choices=get_conversations(session_id), value=None) def load_selected_history(conversation_id, request: gr.Request): session_id = request.session_hash if request else "default" if not conversation_id: return ("", None, "Select a history item.", None) conversation = get_conversation(session_id, conversation_id) if not conversation: return ("", None, "History not found.", None) display = "" for item in conversation["history"]: role = item.get("role", "assistant").title() content = item.get("content", "") display += f"\n\n### {role}\n{content}\n" active_job = get_active_job(session_id, conversation_id) job_id = active_job["id"] if active_job else None return (display or "This conversation is empty.", conversation_id, f"Loaded: {conversation['title']}", job_id) def delete_selected_history(conversation_ids, request: gr.Request): session_id = request.session_hash if request else "default" delete_conversations(session_id, conversation_ids or []) return (gr.Dropdown(choices=get_conversations(session_id), value=None), "Selected history deleted.") def clear_current_conversation(): return ("", None, "Ready for a new conversation.", None) def preview_project(conversation_id): if not conversation_id: return "

No project selected.

" return make_html_preview(get_project_dir(conversation_id)) # ========================================================= # PREMIUM CSS โ€” Optimized for Smooth Performance # ========================================================= CSS = r""" @import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;600&display=swap'); :root { color-scheme: dark; --arise-violet: #8b5cf6; --arise-cyan: #22d3ee; --arise-pink: #f472b6; --arise-deep: #06080f; } * { box-sizing: border-box; } body, .gradio-container { font-family: 'Space Grotesk', -apple-system, sans-serif !important; } /* ๐Ÿ”ฅ LAG FIX: Lighter background gradient */ body { background: radial-gradient(circle at 10% 10%, rgba(139,92,246,0.12), transparent 40%), radial-gradient(circle at 90% 20%, rgba(34,211,238,0.08), transparent 40%), #06080f !important; min-height: 100vh; overflow-x: hidden; position: relative; } /* === CONTAINER === */ .gradio-container { width: 100% !important; max-width: 1300px !important; margin: auto !important; background: transparent !important; padding: 14px !important; position: relative; z-index: 1; animation: fadeBoot 0.5s ease-out; } @keyframes fadeBoot { from { opacity: 0; } to { opacity: 1; } } /* === HEADER BANNER === */ #main-header { position: relative; overflow: hidden; text-align: center; padding: 46px 20px; border: 1px solid rgba(139,92,246,0.4); border-radius: 26px; background: linear-gradient(135deg, rgba(45,26,90,0.95) 0%, rgba(9,35,57,0.95) 50%, rgba(30,17,70,0.95) 100%); box-shadow: 0 0 40px rgba(139,92,246,0.25); } .hero-title { font-family: 'Space Grotesk', sans-serif; font-size: clamp(32px, 6vw, 62px); font-weight: 800; letter-spacing: -2px; background: linear-gradient(90deg, #fff 0%, #b8a5ff 25%, #56e8ff 50%, #f472b6 75%, #fff 100%); background-size: 300% auto; -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; animation: heroShine 5s linear infinite; } @keyframes heroShine { 0% { background-position: 0% center; } 100% { background-position: 300% center; } } .hero-subtitle { color: #bdc7df; font-size: 13px; letter-spacing: 4px; margin-top: 14px; font-weight: 600; text-transform: uppercase; } .hero-badges span { display: inline-flex; align-items: center; gap: 6px; background: rgba(255,255,255,0.06); padding: 8px 16px; border-radius: 30px; color: #d8d5ff; font-size: 12px; font-weight: 500; margin: 4px; border: 1px solid rgba(255,255,255,0.1); transition: all 0.3s ease; } .hero-badges span:hover { background: rgba(139,92,246,0.25); border-color: rgba(139,92,246,0.6); box-shadow: 0 0 20px rgba(139,92,246,0.5); transform: translateY(-3px); } /* === TABS === */ .gradio-container .tab-nav { border: 1px solid rgba(139,92,246,0.3) !important; border-radius: 18px !important; background: rgba(18,24,40,0.85) !important; padding: 8px !important; } .gradio-container .tab-nav button { border-radius: 12px !important; transition: all 0.3s ease !important; font-weight: 600 !important; } .gradio-container .tab-nav button.selected { background: linear-gradient(135deg, #7045ed, #168edb) !important; color: #fff !important; box-shadow: 0 0 25px rgba(139,92,246,0.6) !important; } /* === BUTTONS === */ .gradio-container button { border-radius: 12px !important; transition: all 0.3s ease !important; font-weight: 600 !important; } .primary { background: linear-gradient(135deg, #7045ed 0%, #a855f7 50%, #168edb 100%) !important; background-size: 200% 200% !important; color: white !important; font-weight: 700 !important; animation: gradientShift 3s ease infinite; box-shadow: 0 4px 20px rgba(139,92,246,0.4) !important; } @keyframes gradientShift { 0%, 100% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } } /* === INPUTS === */ textarea, input[type="text"], input[type="number"] { border-radius: 14px !important; background: rgba(15,20,35,0.7) !important; border: 1px solid rgba(139,92,246,0.2) !important; transition: border-color 0.3s ease !important; } textarea:focus, input:focus { border-color: rgba(139,92,246,0.7) !important; box-shadow: 0 0 0 3px rgba(139,92,246,0.2) !important; outline: none !important; } /* === CODING OUTPUT === */ #coding-output { min-height: 320px; padding: 22px; border: 1px solid rgba(34,211,238,0.3); border-radius: 18px; background: linear-gradient(135deg, rgba(9,15,28,0.92), rgba(18,15,40,0.92)); overflow-wrap: anywhere; position: relative; box-shadow: 0 0 30px rgba(34,211,238,0.15); font-family: 'JetBrains Mono', 'Space Grotesk', monospace; font-size: 14px; line-height: 1.7; } #coding-output pre { max-width: 100%; overflow-x: auto; background: rgba(0,0,0,0.5) !important; padding: 14px !important; border-radius: 10px !important; border: 1px solid rgba(139,92,246,0.15); } /* Blinking cursor */ #coding-output.streaming::after { content: 'โ–‹'; color: #22d3ee; animation: cursorBlink 0.8s step-end infinite; margin-left: 2px; } @keyframes cursorBlink { 0%, 50% { opacity: 1; } 51%, 100% { opacity: 0; } } /* === STATUS BADGE === */ #coding-status { display: inline-block; padding: 8px 16px; border-radius: 20px; background: rgba(34,211,238,0.1); border: 1px solid rgba(34,211,238,0.3); color: #a5f3fc; font-size: 12px; font-weight: 600; } /* === SCROLLBAR === */ ::-webkit-scrollbar { width: 8px; height: 8px; } ::-webkit-scrollbar-track { background: rgba(255,255,255,0.03); border-radius: 10px; } ::-webkit-scrollbar-thumb { background: linear-gradient(180deg, #8b5cf6, #22d3ee); border-radius: 10px; } /* === FOOTER === */ #footer { text-align: center; color: #8390ad; padding: 30px 20px; border-top: 1px solid rgba(139,92,246,0.15); margin-top: 30px; } /* === MOBILE === */ @media(max-width: 650px) { .gradio-container { padding: 6px !important; } #main-header { padding: 28px 12px; border-radius: 18px; } .hero-title { font-size: 30px; letter-spacing: -1px; } .hero-subtitle { font-size: 10px; letter-spacing: 2px; } .gradio-container .tab-nav button { font-size: 11px !important; padding: 8px 5px !important; } #coding-output { min-height: 240px; padding: 12px; font-size: 12px; } } """ # ========================================================= # PREMIUM JS (Lightweight & Smooth) # ========================================================= PREMIUM_JS = """ () => { // Cursor effect on streaming output only const attachCursor = () => { const output = document.querySelector('#coding-output'); if (!output || output.dataset.cursorAttached) return; output.dataset.cursorAttached = '1'; let streamTimer = null; const observer = new MutationObserver(() => { output.classList.add('streaming'); clearTimeout(streamTimer); streamTimer = setTimeout(() => output.classList.remove('streaming'), 1200); }); observer.observe(output, { childList: true, subtree: true, characterData: true }); }; // Run once on load setTimeout(attachCursor, 1000); } """ # ========================================================= # HEADER # ========================================================= HEADER = """
โœฆ NEXT GENERATION ARTIFICIAL INTELLIGENCE โœฆ
โšก ARISE AI STUDIO
CREATE ยท TRANSFORM ยท CODE ยท INNOVATE
๐ŸŽจ AI Art ๐Ÿ–ผ Image Transform ๐Ÿ’ป AI Coding
""" # ========================================================= # GRADIO APP # ========================================================= with gr.Blocks(title=APP_NAME) as demo: conversation_state = gr.State(None) job_state = gr.State(None) gr.HTML(HEADER) with gr.Row(): menu_button = gr.Button("โ˜ฐ Menu", size="sm") gr.Markdown(f"[Developer Contact โ†—]({DEVELOPER_TELEGRAM})") with gr.Column(visible=False, elem_id="menu-panel") as menu_panel: gr.Markdown("### โšก ARISE AI Studio Menu") gr.Markdown(f"**Developer Contact:** [Telegram @hardhackar009]({DEVELOPER_TELEGRAM})") gr.Markdown("Open the **History** tab to load, select or delete saved conversations.") menu_button.click(lambda: gr.update(visible=True), outputs=menu_panel) with gr.Tabs(): # --- TEXT TO IMAGE --- with gr.Tab("๐ŸŽจ Text to Image"): image_model = gr.Dropdown(choices=list(IMAGE_MODELS.keys()), value="SDXL Turbo", label="Select Image Model") image_prompt = gr.Textbox(label="Image Prompt", placeholder="Describe your image in detail...", lines=4) negative_prompt = gr.Textbox(label="Negative Prompt", lines=2) with gr.Row(): width = gr.Slider(256, 768, value=512, step=64, label="Image Width") height = gr.Slider(256, 768, value=512, step=64, label="Image Height") steps = gr.Slider(1, 30, value=4, step=1, label="Inference Steps") with gr.Row(): seed = gr.Number(value=0, precision=0, label="Seed") random_seed = gr.Checkbox(value=True, label="Random Seed") generate_button = gr.Button("โœจ Generate Image", variant="primary") image_output = gr.Image(label="Generated Artwork", type="pil", height=400) seed_output = gr.Number(label="Used Seed", precision=0) generate_button.click( fn=generate_image, inputs=[image_prompt, negative_prompt, image_model, width, height, steps, seed, random_seed], outputs=[image_output, seed_output], ) # --- IMAGE TO IMAGE --- with gr.Tab("๐Ÿ–ผ Image to Image"): input_image = gr.Image(label="Upload Original Image", type="pil", height=300) img2img_model = gr.Dropdown(choices=list(IMAGE_TO_IMAGE_MODELS.keys()), value="Stable Diffusion 1.5 Img2Img", label="Image-to-Image Model") img2img_prompt = gr.Textbox(label="Transformation Prompt", placeholder="Describe the new image style...", lines=4) img2img_negative = gr.Textbox(label="Negative Prompt", lines=2) strength = gr.Slider(0.05, 0.95, value=0.70, step=0.05, label="Transformation Strength") with gr.Row(): img2img_steps = gr.Slider(1, 30, value=25, step=1, label="Inference Steps") img2img_guidance = gr.Slider(1, 15, value=7.5, step=0.5, label="Guidance Scale") with gr.Row(): img2img_seed = gr.Number(value=0, precision=0, label="Seed") img2img_random = gr.Checkbox(value=True, label="Random Seed") img2img_button = gr.Button("๐Ÿช„ Transform Image", variant="primary") img2img_output = gr.Image(label="Transformed Image", type="pil", height=400) img2img_seed_output = gr.Number(label="Used Seed", precision=0) img2img_button.click( fn=generate_image_to_image, inputs=[input_image, img2img_prompt, img2img_negative, img2img_model, strength, img2img_steps, img2img_guidance, img2img_seed, img2img_random], outputs=[img2img_output, img2img_seed_output], ) # --- AI CODING --- with gr.Tab("๐Ÿ’ป AI Coding"): gr.Markdown("## ๐Ÿ’ป ARISE AI Coding Workspace") code_model = gr.Dropdown(choices=list(CODE_MODELS.keys()), value="Qwen Coder 0.5B", label="Select Coding Model") code_prompt = gr.Textbox(label="Your Coding Request", placeholder="Describe your changes...", lines=5) with gr.Row(): max_tokens = gr.Slider(128, 2048, value=768, step=128, label="Maximum Output Tokens") temperature = gr.Slider(0.1, 1.0, value=0.3, step=0.1, label="Temperature") coding_output = gr.Markdown(value="Ready to work on your project.", elem_id="coding-output") with gr.Row(): generate_code = gr.Button("โšก Start Coding", variant="primary") stop_button = gr.Button("โน Stop", variant="stop") new_project_button = gr.Button("๏ผ‹ New Project", variant="secondary") coding_status = gr.Markdown("Ready.", elem_id="coding-status") gr.Markdown("### ๐Ÿ“ฆ Project Downloads") with gr.Row(): project_zip_download = gr.File(label="Download Full Project ZIP", interactive=False) single_file_download = gr.File(label="Download Last Edited File", interactive=False) preview_button = gr.Button("๐ŸŒ Preview HTML Project") html_preview = gr.HTML(value="
HTML preview will appear here.
") generate_code.click( fn=coding_assistant, inputs=[code_prompt, code_model, max_tokens, temperature, conversation_state], outputs=[coding_output, conversation_state, coding_status, project_zip_download, single_file_download, job_state], ) stop_button.click(fn=stop_job, inputs=job_state, outputs=coding_status) new_project_button.click(fn=clear_current_conversation, outputs=[coding_output, conversation_state, coding_status, job_state]) preview_button.click(fn=preview_project, inputs=conversation_state, outputs=html_preview) # --- HISTORY --- with gr.Tab("๐Ÿ“š History"): history_dropdown = gr.Dropdown(choices=[], label="Saved History", interactive=True) with gr.Row(): refresh_history_button = gr.Button("๐Ÿ”„ Refresh History") load_history_button = gr.Button("๐Ÿ“‚ Open Selected", variant="primary") history_output = gr.Markdown("Select a saved conversation.") history_status = gr.Markdown("") resume_button = gr.Button("โ–ถ Resume Selected Job") with gr.Row(): delete_history_button = gr.Button("๐Ÿ—‘ Delete Selected", variant="stop") delete_all_history_button = gr.Button("๐Ÿ—‘ Delete All", variant="stop") refresh_history_button.click(fn=refresh_history, outputs=history_dropdown) load_history_button.click(fn=load_selected_history, inputs=history_dropdown, outputs=[history_output, conversation_state, history_status, job_state]) delete_history_button.click(fn=delete_selected_history, inputs=history_dropdown, outputs=[history_dropdown, history_status]) def delete_all(request: gr.Request): session_id = request.session_hash if request else "default" ids = [value for _, value in get_conversations(session_id)] delete_conversations(session_id, ids) return (gr.Dropdown(choices=[], value=None), "All history deleted.") delete_all_history_button.click(fn=delete_all, outputs=[history_dropdown, history_status]) resume_button.click(fn=resume_job, inputs=job_state, outputs=[history_output, history_status, project_zip_download, single_file_download]) gr.HTML(f""" """) demo.load(fn=None, js=PREMIUM_JS) # ========================================================= # LAUNCH # ========================================================= if __name__ == "__main__": demo.queue(default_concurrency_limit=1, max_size=20).launch( theme=gr.themes.Soft(primary_hue="violet", secondary_hue="cyan", neutral_hue="slate"), css=CSS, allowed_paths=[str(DATA_DIR.resolve())], show_error=True, share=False, )