lastwarning commited on
Commit
75fc42b
Β·
verified Β·
1 Parent(s): 3bc3dc6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1278 -260
app.py CHANGED
@@ -41,6 +41,7 @@ from threading import Thread, Event
41
  # =========================================================
42
  # CONFIGURATION
43
  # =========================================================
 
44
  APP_NAME = "ARISE AI Studio"
45
  DEVELOPER_TELEGRAM = "https://t.me/hardhackar009"
46
 
@@ -54,6 +55,7 @@ MAX_CONTEXT_SIZE = 80000
54
  IMAGE_DTYPE = torch.float16
55
 
56
  DATA_DIR = Path(os.getenv("ARISE_DATA_DIR", "/data/arise_ai_studio"))
 
57
  try:
58
  DATA_DIR.mkdir(parents=True, exist_ok=True)
59
  test_file = DATA_DIR / ".write_test"
@@ -68,16 +70,22 @@ PROJECTS_DIR = DATA_DIR / "projects"
68
  PROJECTS_DIR.mkdir(parents=True, exist_ok=True)
69
 
70
  SUPPORTED_TEXT_EXTENSIONS = {
71
- ".py", ".js", ".jsx", ".ts", ".tsx", ".html", ".htm", ".css", ".scss",
72
- ".json", ".xml", ".yaml", ".yml", ".md", ".txt", ".java", ".kt",
73
- ".gradle", ".properties", ".sh", ".bat", ".c", ".cpp", ".h", ".hpp",
74
- ".php", ".sql", ".go", ".rs", ".swift", ".dart", ".vue", ".svelte",
75
- ".toml", ".ini", ".cfg", ".env.example", ".gitignore", ".dockerfile",
 
 
 
 
 
76
  }
77
 
78
  EXCLUDED_DIRS = {
79
- ".git", ".gradle", ".idea", ".vscode", "__pycache__",
80
- "node_modules", "build", "dist", ".venv", "venv", ".next",
 
81
  }
82
 
83
  IMAGE_MODELS = {
@@ -103,6 +111,7 @@ CODE_MODELS = {
103
  # =========================================================
104
  # DATABASE
105
  # =========================================================
 
106
  db_lock = threading.RLock()
107
 
108
  def db_connect():
@@ -115,15 +124,25 @@ def initialize_database():
115
  connection = db_connect()
116
  connection.execute("""
117
  CREATE TABLE IF NOT EXISTS conversations (
118
- id TEXT PRIMARY KEY, session_id TEXT NOT NULL, title TEXT NOT NULL,
119
- history TEXT NOT NULL, created TEXT NOT NULL, updated TEXT NOT NULL
 
 
 
 
120
  )
121
  """)
122
  connection.execute("""
123
  CREATE TABLE IF NOT EXISTS jobs (
124
- id TEXT PRIMARY KEY, session_id TEXT NOT NULL, conversation_id TEXT NOT NULL,
125
- status TEXT NOT NULL, prompt TEXT NOT NULL, response TEXT NOT NULL,
126
- error TEXT, created TEXT NOT NULL, updated TEXT NOT NULL
 
 
 
 
 
 
127
  )
128
  """)
129
  connection.commit()
@@ -144,36 +163,50 @@ def save_conversation(session_id, conversation_id, title, history):
144
  with db_lock:
145
  connection = db_connect()
146
  connection.execute("""
147
- INSERT INTO conversations (id, session_id, title, history, created, updated)
 
148
  VALUES (?, ?, ?, ?, ?, ?)
149
- ON CONFLICT(id) DO UPDATE SET title=excluded.title, history=excluded.history, updated=excluded.updated
150
- """, (conversation_id, session_id, title, json.dumps(history, ensure_ascii=False), timestamp, timestamp))
 
 
 
 
151
  connection.commit()
152
  connection.close()
153
 
154
  def get_conversations(session_id):
155
  with db_lock:
156
  connection = db_connect()
157
- rows = connection.execute("SELECT id, title, updated FROM conversations WHERE session_id=? ORDER BY updated DESC", (session_id,)).fetchall()
 
 
 
158
  connection.close()
159
  return [(f"{row['title']} Β· {row['updated']}", row["id"]) for row in rows]
160
 
161
  def get_conversation(session_id, conversation_id):
162
  with db_lock:
163
  connection = db_connect()
164
- row = connection.execute("SELECT * FROM conversations WHERE id=? AND session_id=?", (conversation_id, session_id)).fetchone()
 
 
165
  connection.close()
166
- return {"id": row["id"], "title": row["title"], "history": json.loads(row["history"])} if row else None
 
 
167
 
168
  def delete_conversations(session_id, conversation_ids):
169
- if not conversation_ids: return
 
170
  with db_lock:
171
  connection = db_connect()
172
  for cid in conversation_ids:
173
  connection.execute("DELETE FROM conversations WHERE id=? AND session_id=?", (cid, session_id))
174
  connection.execute("DELETE FROM jobs WHERE conversation_id=? AND session_id=?", (cid, session_id))
175
  project_dir = PROJECTS_DIR / cid
176
- if project_dir.exists(): shutil.rmtree(project_dir, ignore_errors=True)
 
177
  connection.commit()
178
  connection.close()
179
 
@@ -184,7 +217,8 @@ def create_conversation(session_id, title="New Project"):
184
  return conversation_id
185
 
186
  def update_job(job_id, **values):
187
- if not values: return
 
188
  values["updated"] = now_string()
189
  assignments = ", ".join(f"{key}=?" for key in values)
190
  parameters = list(values.values()) + [job_id]
@@ -217,112 +251,208 @@ def get_job(job_id, session_id):
217
  def get_active_job(session_id, conversation_id):
218
  with db_lock:
219
  connection = db_connect()
220
- 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()
 
 
 
221
  connection.close()
222
  return dict(row) if row else None
223
 
224
  # =========================================================
225
- # MODEL CACHE & IMAGE PIPELINE
226
  # =========================================================
 
227
  image_cache = {"name": None, "pipe": None}
228
  code_cache = {"name": None, "tokenizer": None, "model": None}
229
  image_lock = threading.RLock()
230
  code_lock = threading.RLock()
231
- job_threads, job_threads_lock, job_stop_events = {}, threading.RLock(), {}
 
 
232
 
233
  def clear_image_cache():
234
- if image_cache["pipe"] is not None: del image_cache["pipe"]
235
- image_cache["pipe"], image_cache["name"] = None, None
 
 
 
236
  gc.collect()
237
- if torch.cuda.is_available(): torch.cuda.empty_cache()
 
238
 
239
  def clear_code_cache():
240
- if code_cache["model"] is not None: del code_cache["model"]
241
- if code_cache["tokenizer"] is not None: del code_cache["tokenizer"]
242
- code_cache["model"], code_cache["tokenizer"], code_cache["name"] = None, None, None
 
 
 
 
 
 
243
  gc.collect()
244
 
245
  def load_image_pipeline(model_id, mode):
246
  cache_key = f"{mode}:{model_id}"
247
  with image_lock:
248
- if image_cache["name"] == cache_key and image_cache["pipe"] is not None: return image_cache["pipe"]
 
249
  clear_image_cache()
250
- if mode == "text": pipe = DiffusionPipeline.from_pretrained(model_id, torch_dtype=IMAGE_DTYPE, token=False)
251
- elif mode == "image": pipe = AutoPipelineForImage2Image.from_pretrained(model_id, torch_dtype=IMAGE_DTYPE, token=False)
 
 
 
 
252
  pipe = pipe.to("cuda")
253
- if hasattr(pipe, "enable_attention_slicing"): pipe.enable_attention_slicing()
254
- image_cache["pipe"], image_cache["name"] = pipe, cache_key
 
 
255
  return pipe
256
 
257
  @spaces.GPU(duration=120)
258
  def generate_image(prompt, negative_prompt, model_name, width, height, steps, seed, random_seed):
259
- if not prompt or not prompt.strip(): raise gr.Error("Enter an image prompt.")
 
 
 
260
  config = IMAGE_MODELS[model_name]
261
- if random_seed: seed = random.randint(0, 2147483647)
 
262
  seed = int(seed or 0)
263
  width = (max(256, min(int(width), 768)) // 8) * 8
264
  height = (max(256, min(int(height), 768)) // 8) * 8
265
  actual_steps = min(max(int(steps), 1), config["max_steps"])
266
- if model_name in ["SDXL Turbo", "SD Turbo"]: actual_steps = min(actual_steps, 4)
 
267
  try:
268
  with image_lock:
269
  pipe = load_image_pipeline(config["id"], "text")
270
  generator = torch.Generator(device="cuda").manual_seed(seed)
271
- 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)
 
 
 
 
 
 
 
272
  return result.images[0], seed
273
  except Exception as error:
 
274
  raise gr.Error(f"Image generation failed: {error}")
275
 
276
  @spaces.GPU(duration=120)
277
  def generate_image_to_image(input_image, prompt, negative_prompt, model_name, strength, steps, guidance, seed, random_seed):
278
- if input_image is None: raise gr.Error("Upload an image.")
279
- if not prompt or not prompt.strip(): raise gr.Error("Enter transformation prompt.")
280
- if random_seed: seed = random.randint(0, 2147483647)
 
 
 
 
 
281
  seed = int(seed or 0)
 
 
282
  try:
283
  image = input_image.convert("RGB")
284
  image.thumbnail((768, 768), Image.Resampling.LANCZOS)
285
- width, height = max(256, (image.width // 8) * 8), max(256, (image.height // 8) * 8)
 
286
  image = image.resize((width, height), Image.Resampling.LANCZOS)
 
287
  with image_lock:
288
- pipe = load_image_pipeline(IMAGE_TO_IMAGE_MODELS[model_name], "image")
289
  generator = torch.Generator(device="cuda").manual_seed(seed)
290
- result = pipe(prompt=prompt.strip(), image=image, negative_prompt=negative_prompt or None, strength=max(0.05, min(float(strength), 0.95)), num_inference_steps=max(1, min(int(steps), 30)), guidance_scale=float(guidance), generator=generator)
 
 
 
 
 
291
  return result.images[0], seed
292
  except Exception as error:
 
293
  raise gr.Error(f"Image-to-image failed: {error}")
294
 
295
  # =========================================================
296
- # SYSTEM PROMPT & FILE HELPERS
297
  # =========================================================
 
298
  SYSTEM_PROMPT = """
299
  You are ARISE AI, a professional software engineering assistant.
300
- When modifying project files, return every complete modified or new file using exactly this format:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
301
  <<<FILE: relative/path/to/file.ext>>>
302
  complete file content here
303
  <<<END FILE>>>
304
- Do not use absolute paths. Do not omit required imports or code.
 
 
 
 
 
 
 
305
  """
306
 
307
  def load_code_model(model_name):
 
 
308
  model_id = CODE_MODELS[model_name]
309
  with code_lock:
310
- if code_cache["name"] == model_id and code_cache["model"] is not None: return code_cache["tokenizer"], code_cache["model"]
 
311
  clear_code_cache()
312
  tokenizer = AutoTokenizer.from_pretrained(model_id, token=False)
313
- model = AutoModelForCausalLM.from_pretrained(model_id, token=False, torch_dtype=torch.float32, low_cpu_mem_usage=True).to("cpu")
 
 
 
314
  model.eval()
315
- code_cache["name"], code_cache["tokenizer"], code_cache["model"] = model_id, tokenizer, model
 
 
316
  return tokenizer, model
317
 
 
 
 
 
318
  def safe_relative_path(value):
319
  value = str(value).replace("\\", "/").strip()
320
  path = Path(value)
321
- if not value or path.is_absolute() or ".." in path.parts or "\x00" in value: raise ValueError("Unsafe path.")
 
322
  return path
323
 
324
  def is_text_file(path):
325
- return (path.suffix.lower() in SUPPORTED_TEXT_EXTENSIONS or path.name.lower() in {"dockerfile", "makefile", ".gitignore"})
 
326
 
327
  def project_files(project_dir):
328
  result = []
@@ -330,9 +460,14 @@ def project_files(project_dir):
330
  dirs[:] = [name for name in dirs if name not in EXCLUDED_DIRS]
331
  for filename in files:
332
  full_path = Path(root) / filename
333
- if full_path.name == "project_index.json": continue
334
- try: result.append({"path": full_path.relative_to(project_dir).as_posix(), "size": full_path.stat().st_size, "text": is_text_file(full_path)})
335
- except: continue
 
 
 
 
 
336
  return result
337
 
338
  def build_project_context(project_dir):
@@ -340,309 +475,1192 @@ def build_project_context(project_dir):
340
  output = ["PROJECT STRUCTURE:", json.dumps(files, ensure_ascii=False, indent=2), "", "PROJECT FILE CONTENTS:"]
341
  total = 0
342
  for item in files:
343
- if not item["text"]: continue
344
- try: content = (project_dir / item["path"]).read_text(encoding="utf-8", errors="replace")
345
- except: continue
 
 
 
 
346
  section = f"\n\n===== FILE: {item['path']} =====\n{content}\n===== END FILE =====\n"
347
  if total + len(section) > MAX_CONTEXT_SIZE:
348
- output.append("\n[Project context truncated.]")
349
  break
350
  output.append(section)
351
  total += len(section)
352
  return "\n".join(output), files
353
 
354
- def extract_zip_safely(zip_path, destination):
355
- with zipfile.ZipFile(zip_path, "r") as archive:
356
- for item in archive.infolist():
357
- relative = safe_relative_path(item.filename)
358
- if item.is_dir(): continue
359
- target = destination / relative
360
- target.parent.mkdir(parents=True, exist_ok=True)
361
- with archive.open(item, "r") as source, target.open("wb") as output:
362
- shutil.copyfileobj(source, output)
363
-
364
- def process_uploads(uploaded_files, project_dir):
365
- if not uploaded_files: return "No files."
366
- messages = []
367
- for uploaded in uploaded_files:
368
- source = Path(getattr(uploaded, "name", uploaded))
369
- if source.suffix.lower() == ".zip":
370
- extract_zip_safely(source, project_dir)
371
- messages.append(f"Extracted {source.name}")
372
- else:
373
- shutil.copy2(source, project_dir / source.name)
374
- messages.append(f"Added {source.name}")
375
- return "\n".join(messages)
376
-
377
- FILE_BLOCK_PATTERN = re.compile(r"<<<FILE:\s*(.*?)>>>\s*(.*?)\s*<<<END FILE>>>", re.DOTALL | re.IGNORECASE)
378
 
379
  def apply_file_changes(response, project_dir):
380
  changed = []
381
  for match in FILE_BLOCK_PATTERN.finditer(response):
 
 
382
  try:
383
- relative = safe_relative_path(match.group(1).strip())
384
- target = Path(project_dir) / relative
385
- target.parent.mkdir(parents=True, exist_ok=True)
386
- target.write_text(match.group(2).rstrip() + "\n", encoding="utf-8")
387
- changed.append(relative.as_posix())
388
- except: continue
 
389
  return changed
390
 
391
  def create_project_zip(project_dir):
 
392
  zip_path = DATA_DIR / ("ARISE_Project_" + uuid.uuid4().hex[:10] + ".zip")
393
  with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as archive:
394
  for root, dirs, files in os.walk(project_dir):
395
  dirs[:] = [name for name in dirs if name not in EXCLUDED_DIRS]
396
- for filename in files: archive.write(Path(root) / filename, (Path(root) / filename).relative_to(project_dir))
 
 
 
 
397
  return str(zip_path)
398
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
399
  class StopCriteria(StoppingCriteria):
400
- def __init__(self, event): self.event = event
401
- def __call__(self, input_ids, scores, **kwargs): return self.event.is_set()
 
 
 
402
 
403
  # =========================================================
404
  # CODING WORKER
405
  # =========================================================
 
406
  def run_coding_worker(job_id, session_id, conversation_id, prompt, model_name, max_tokens, temperature, stop_event):
407
  try:
408
  update_job(job_id, status="running", response="")
409
  project_dir = get_project_dir(conversation_id)
410
  project_context, files = build_project_context(project_dir)
411
  tokenizer, model = load_code_model(model_name)
 
412
  messages = [{"role": "system", "content": SYSTEM_PROMPT}]
413
  conversation = get_conversation(session_id, conversation_id)
414
  history = conversation["history"] if conversation else []
415
- for item in history[-MAX_HISTORY_MESSAGES:]: messages.append({"role": item["role"], "content": item["content"]})
416
-
417
- project_prompt = f"PROJECT CONTEXT:\n{project_context}\n\nUSER REQUEST:\n{prompt}\n\nReturn changed files using <<<FILE: path>>> format." if files else prompt
 
 
 
 
 
 
 
 
 
 
418
  messages.append({"role": "user", "content": project_prompt})
419
 
420
- formatted_prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) if getattr(tokenizer, "chat_template", None) else "\n\n".join(f"{i['role'].upper()}:\n{i['content']}" for i in messages) + "\n\nASSISTANT:\n"
 
 
 
 
421
  inputs = tokenizer(formatted_prompt, return_tensors="pt", truncation=True, max_length=MAX_INPUT_LENGTH)
422
  streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=120)
423
-
424
  generation_kwargs = {
425
- **inputs, "streamer": streamer, "max_new_tokens": max(128, min(int(max_tokens), 2048)),
426
- "do_sample": float(temperature) > 0.05, "temperature": max(float(temperature), 0.05),
427
- "pad_token_id": tokenizer.pad_token_id or tokenizer.eos_token_id,
428
- "stopping_criteria": StoppingCriteriaList([StopCriteria(stop_event)])
 
 
 
429
  }
430
-
431
  errors = []
432
  def generate():
433
  try:
434
- with torch.inference_mode(): model.generate(**generation_kwargs)
435
- except Exception as e:
436
- errors.append(str(e))
437
- try: streamer.end()
438
- except: pass
 
 
 
 
 
 
 
439
 
440
- Thread(target=generate, daemon=True).start()
441
  response = ""
442
  for token in streamer:
443
- if stop_event.is_set(): break
 
444
  response += token
445
  update_job(job_id, response=response, status="running")
446
-
447
- if errors: raise RuntimeError(errors[0])
448
- if stop_event.is_set(): return update_job(job_id, status="stopped", response=response + "\n\nStopped.")
449
-
 
 
 
 
 
 
 
 
450
  changed_files = apply_file_changes(response, project_dir)
451
- history.extend([{"role": "user", "content": prompt}, {"role": "assistant", "content": response}])
452
- save_conversation(session_id, conversation_id, prompt.strip().replace("\n", " ")[:55] or "ARISE Project", history)
453
-
454
- final_response = response + ("\n\n---\n### Updated Files:\n" + "\n".join(f"- `{name}`" for name in changed_files) if changed_files else "")
 
 
 
 
 
 
 
 
 
 
455
  update_job(job_id, status="completed", response=final_response)
456
- except Exception as e:
457
- update_job(job_id, status="error", error=str(e), response=f"**Coding error:** {e}")
 
 
458
  finally:
459
  with job_threads_lock:
460
  job_threads.pop(job_id, None)
461
  job_stop_events.pop(job_id, None)
462
 
463
- def coding_assistant(prompt, model_name, max_tokens, temperature, uploaded_files, conversation_id, request: gr.Request):
464
- if not prompt or not prompt.strip(): return
 
 
 
465
  session_id = request.session_hash if request else "default"
466
- if not conversation_id: conversation_id = create_conversation(session_id, prompt.strip()[:55])
 
 
 
467
  project_dir = get_project_dir(conversation_id)
468
- if uploaded_files: process_uploads(uploaded_files, project_dir)
469
-
470
  job_id = create_job(session_id, conversation_id, prompt.strip())
471
  stop_event = Event()
472
  with job_threads_lock:
473
  job_stop_events[job_id] = stop_event
474
- job_threads[job_id] = Thread(target=run_coding_worker, args=(job_id, session_id, conversation_id, prompt.strip(), model_name, max_tokens, temperature, stop_event), daemon=True)
475
- job_threads[job_id].start()
476
-
477
- yield ("⏳ Analyzing...", conversation_id, "Job started.", None, None, job_id)
478
- prev_resp = ""
 
 
 
 
 
 
 
479
  while True:
480
  job = get_job(job_id, session_id)
481
- if not job: return
482
- resp, status = job["response"] or "", job["status"]
483
- if resp != prev_resp or status not in ["queued", "running"]:
484
- prev_resp = resp
 
 
 
 
 
 
 
 
 
 
 
 
485
  zip_file = None
486
- if status == "completed": zip_file = create_project_zip(project_dir)
487
- yield (resp or "Working...", conversation_id, f"Status: {status}", zip_file, None, job_id)
488
- if status not in ["queued", "running"]: return
 
 
 
 
 
 
 
 
489
  time.sleep(1)
490
 
491
- def refresh_history(request: gr.Request):
492
- return gr.Dropdown(choices=get_conversations(request.session_hash if request else "default"), value=None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
493
 
494
  def stop_job(job_id):
495
- if not job_id: return "No active job."
 
496
  with job_threads_lock:
497
- if event := job_stop_events.get(job_id): event.set(); return "⏹ Stop requested."
 
 
 
498
  return "No running job found."
499
 
500
  # =========================================================
501
- # CHATGPT RESPONSIVE UI CSS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
502
  # =========================================================
503
- CSS = """
 
 
 
 
 
 
 
 
 
 
 
 
 
504
  body, .gradio-container {
505
- background-color: #212121 !important;
506
- color: #ececec !important;
507
- font-family: 'SΓΆhne', 'Helvetica Neue', Arial, sans-serif !important;
508
- }
509
- /* Sidebar Styling */
510
- #sidebar {
511
- background-color: #171717 !important;
512
- padding: 10px;
513
- border-right: 1px solid #2f2f2f !important;
514
- height: 100vh;
515
- }
516
- @media (max-width: 768px) {
517
- #sidebar { height: auto; border-right: none; border-bottom: 1px solid #2f2f2f !important; }
518
- }
519
- /* Chat Area Styling */
520
- #chatbot-ui { background-color: transparent !important; }
521
- #chatbot-ui .message-row .user {
522
- background-color: #2f2f2f !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
523
  border-radius: 12px !important;
 
 
 
524
  }
525
- #chatbot-ui .message-row .bot {
526
- background-color: #212121 !important;
527
- border: none !important;
 
 
 
 
 
 
 
528
  }
529
- /* Inputs & Buttons */
530
- textarea, input[type="text"], input[type="number"] {
531
- background-color: #2f2f2f !important;
532
- border: 1px solid #444 !important;
533
  border-radius: 12px !important;
534
- color: #ececec !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
535
  }
536
- textarea:focus { border-color: #10a37f !important; box-shadow: 0 0 0 1px #10a37f !important; }
537
- .primary { background-color: #10a37f !important; color: white !important; border: none !important; border-radius: 8px !important; }
538
- .primary:hover { background-color: #1a7f64 !important; }
539
- /* Hide Gradio default borders */
540
- .gr-box { border: none !important; box-shadow: none !important; background: transparent !important; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
541
  """
542
 
543
  # =========================================================
544
  # GRADIO APP
545
  # =========================================================
 
546
  with gr.Blocks(title=APP_NAME) as demo:
 
547
  conversation_state = gr.State(None)
548
  job_state = gr.State(None)
549
 
 
 
550
  with gr.Row():
551
- # LEFT SIDEBAR (Fully responsive)
552
- with gr.Column(scale=1, min_width=250, elem_id="sidebar"):
553
- gr.Markdown(f"### ⚑ {APP_NAME}")
554
- new_chat_btn = gr.Button("βž• New Chat", variant="primary")
555
-
556
- history_dropdown = gr.Dropdown(choices=[], label="History", interactive=True)
557
- refresh_history_button = gr.Button("πŸ”„ Refresh", size="sm")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
558
 
559
- with gr.Accordion("βš™οΈ Settings", open=False):
560
- code_model = gr.Dropdown(choices=list(CODE_MODELS.keys()), value="Qwen Coder 1.5B", label="Model")
561
- max_tokens = gr.Slider(128, 2048, value=768, step=128, label="Max Tokens")
 
 
 
 
 
 
562
  temperature = gr.Slider(0.1, 1.0, value=0.3, step=0.1, label="Temperature")
563
-
564
- with gr.Accordion("πŸ“ Upload Project", open=False):
565
- project_upload = gr.File(label="Upload ZIP/Files", file_count="multiple", type="filepath")
566
-
567
- # RIGHT MAIN AREA
568
- with gr.Column(scale=4):
569
- with gr.Tabs():
570
- with gr.Tab("πŸ’¬ Chat"):
571
- chatbot = gr.Chatbot(
572
- value=[{"role": "assistant", "content": "Hello! I am ARISE AI. How can I help you today?"}],
573
- height=550,
574
- show_label=False,
575
- elem_id="chatbot-ui"
576
- )
577
- with gr.Row():
578
- code_prompt = gr.Textbox(show_label=False, placeholder="Message ARISE AI...", lines=2, scale=9)
579
- generate_code = gr.Button("πŸš€", variant="primary", scale=1)
580
-
581
- with gr.Row():
582
- stop_button = gr.Button("⏹ Stop", variant="stop", size="sm")
583
- coding_status = gr.Markdown("Ready.")
584
-
585
- # Hidden download boxes (Only visible when file ready)
586
- with gr.Row():
587
- project_zip_download = gr.File(label="Download Project ZIP", visible=False)
588
-
589
- with gr.Tab("🎨 Image Gen"):
590
- image_prompt = gr.Textbox(label="Prompt", placeholder="Describe your image...", lines=3)
591
- generate_button = gr.Button("✨ Generate", variant="primary")
592
- image_output = gr.Image(label="Result", type="pil")
593
-
594
- # =====================================================
595
- # EVENTS
596
- # =====================================================
597
- def chat_and_code(prompt, model_name, max_tokens, temperature, uploaded_files, conversation_id, chat_history, request: gr.Request):
598
- if not prompt.strip(): return
599
- new_history = chat_history + [{"role": "user", "content": prompt}]
600
- yield new_history, conversation_id, "⏳ Analyzing...", gr.update(visible=False), None
601
-
602
- for out in coding_assistant(prompt, model_name, max_tokens, temperature, uploaded_files, conversation_id, request):
603
- resp_text, cid, status, zip_file, _, job_id = out
604
- if new_history[-1]["role"] == "assistant": new_history[-1]["content"] = resp_text
605
- else: new_history.append({"role": "assistant", "content": resp_text})
606
-
607
- # Show download box only if zip_file exists
608
- download_update = gr.update(visible=True, value=zip_file) if zip_file else gr.update(visible=False)
609
- yield new_history, cid, status, download_update, job_id
610
-
611
- generate_code.click(
612
- fn=chat_and_code,
613
- inputs=[code_prompt, code_model, max_tokens, temperature, project_upload, conversation_state, chatbot],
614
- outputs=[chatbot, conversation_state, coding_status, project_zip_download, job_state],
615
- ).then(lambda: "", outputs=code_prompt)
616
-
617
- def load_history_chat(conversation_id, request: gr.Request):
618
- session_id = request.session_hash if request else "default"
619
- if not conversation_id: return [], None, "Select a chat.", None
620
- conv = get_conversation(session_id, conversation_id)
621
- if not conv: return [], None, "Not found.", None
622
- hist = [{"role": i.get("role", "assistant"), "content": i.get("content", "")} for i in conv["history"]]
623
- active = get_active_job(session_id, conversation_id)
624
- return hist, conversation_id, "Loaded", active["id"] if active else None
625
-
626
- history_dropdown.change(fn=load_history_chat, inputs=history_dropdown, outputs=[chatbot, conversation_state, coding_status, job_state])
627
- refresh_history_button.click(fn=refresh_history, outputs=history_dropdown)
628
- new_chat_btn.click(fn=lambda: ([{"role": "assistant", "content": "Hello! How can I help?"}], None, "New Chat", None, gr.update(visible=False)), outputs=[chatbot, conversation_state, coding_status, job_state, project_zip_download])
629
- stop_button.click(fn=stop_job, inputs=job_state, outputs=coding_status)
630
-
631
- # Image Gen
632
- generate_button.click(fn=lambda p: generate_image(p, "", "SDXL Turbo", 512, 512, 4, 0, True)[0], inputs=[image_prompt], outputs=[image_output])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
633
 
634
  # =========================================================
635
  # LAUNCH
636
  # =========================================================
 
637
  if __name__ == "__main__":
638
- demo.queue(default_concurrency_limit=1, max_size=20).launch(
639
- theme=gr.themes.Base(
640
- primary_hue="emerald",
641
- secondary_hue="gray",
642
- neutral_hue="slate"
 
 
 
643
  ),
644
  css=CSS,
645
- allowed_paths=[str(DATA_DIR.resolve())],
646
  show_error=True,
647
  share=False,
648
  )
 
41
  # =========================================================
42
  # CONFIGURATION
43
  # =========================================================
44
+
45
  APP_NAME = "ARISE AI Studio"
46
  DEVELOPER_TELEGRAM = "https://t.me/hardhackar009"
47
 
 
55
  IMAGE_DTYPE = torch.float16
56
 
57
  DATA_DIR = Path(os.getenv("ARISE_DATA_DIR", "/data/arise_ai_studio"))
58
+
59
  try:
60
  DATA_DIR.mkdir(parents=True, exist_ok=True)
61
  test_file = DATA_DIR / ".write_test"
 
70
  PROJECTS_DIR.mkdir(parents=True, exist_ok=True)
71
 
72
  SUPPORTED_TEXT_EXTENSIONS = {
73
+ ".py", ".js", ".jsx", ".ts", ".tsx",
74
+ ".html", ".htm", ".css", ".scss",
75
+ ".json", ".xml", ".yaml", ".yml",
76
+ ".md", ".txt", ".java", ".kt",
77
+ ".gradle", ".properties", ".sh",
78
+ ".bat", ".c", ".cpp", ".h", ".hpp",
79
+ ".php", ".sql", ".go", ".rs",
80
+ ".swift", ".dart", ".vue", ".svelte",
81
+ ".toml", ".ini", ".cfg", ".env.example",
82
+ ".gitignore", ".dockerfile",
83
  }
84
 
85
  EXCLUDED_DIRS = {
86
+ ".git", ".gradle", ".idea", ".vscode",
87
+ "__pycache__", "node_modules", "build",
88
+ "dist", ".venv", "venv", ".next",
89
  }
90
 
91
  IMAGE_MODELS = {
 
111
  # =========================================================
112
  # DATABASE
113
  # =========================================================
114
+
115
  db_lock = threading.RLock()
116
 
117
  def db_connect():
 
124
  connection = db_connect()
125
  connection.execute("""
126
  CREATE TABLE IF NOT EXISTS conversations (
127
+ id TEXT PRIMARY KEY,
128
+ session_id TEXT NOT NULL,
129
+ title TEXT NOT NULL,
130
+ history TEXT NOT NULL,
131
+ created TEXT NOT NULL,
132
+ updated TEXT NOT NULL
133
  )
134
  """)
135
  connection.execute("""
136
  CREATE TABLE IF NOT EXISTS jobs (
137
+ id TEXT PRIMARY KEY,
138
+ session_id TEXT NOT NULL,
139
+ conversation_id TEXT NOT NULL,
140
+ status TEXT NOT NULL,
141
+ prompt TEXT NOT NULL,
142
+ response TEXT NOT NULL,
143
+ error TEXT,
144
+ created TEXT NOT NULL,
145
+ updated TEXT NOT NULL
146
  )
147
  """)
148
  connection.commit()
 
163
  with db_lock:
164
  connection = db_connect()
165
  connection.execute("""
166
+ INSERT INTO conversations
167
+ (id, session_id, title, history, created, updated)
168
  VALUES (?, ?, ?, ?, ?, ?)
169
+ ON CONFLICT(id) DO UPDATE SET
170
+ title=excluded.title,
171
+ history=excluded.history,
172
+ updated=excluded.updated
173
+ """, (conversation_id, session_id, title,
174
+ json.dumps(history, ensure_ascii=False), timestamp, timestamp))
175
  connection.commit()
176
  connection.close()
177
 
178
  def get_conversations(session_id):
179
  with db_lock:
180
  connection = db_connect()
181
+ rows = connection.execute("""
182
+ SELECT id, title, updated FROM conversations
183
+ WHERE session_id=? ORDER BY updated DESC
184
+ """, (session_id,)).fetchall()
185
  connection.close()
186
  return [(f"{row['title']} Β· {row['updated']}", row["id"]) for row in rows]
187
 
188
  def get_conversation(session_id, conversation_id):
189
  with db_lock:
190
  connection = db_connect()
191
+ row = connection.execute("""
192
+ SELECT * FROM conversations WHERE id=? AND session_id=?
193
+ """, (conversation_id, session_id)).fetchone()
194
  connection.close()
195
+ if not row:
196
+ return None
197
+ return {"id": row["id"], "title": row["title"], "history": json.loads(row["history"])}
198
 
199
  def delete_conversations(session_id, conversation_ids):
200
+ if not conversation_ids:
201
+ return
202
  with db_lock:
203
  connection = db_connect()
204
  for cid in conversation_ids:
205
  connection.execute("DELETE FROM conversations WHERE id=? AND session_id=?", (cid, session_id))
206
  connection.execute("DELETE FROM jobs WHERE conversation_id=? AND session_id=?", (cid, session_id))
207
  project_dir = PROJECTS_DIR / cid
208
+ if project_dir.exists():
209
+ shutil.rmtree(project_dir, ignore_errors=True)
210
  connection.commit()
211
  connection.close()
212
 
 
217
  return conversation_id
218
 
219
  def update_job(job_id, **values):
220
+ if not values:
221
+ return
222
  values["updated"] = now_string()
223
  assignments = ", ".join(f"{key}=?" for key in values)
224
  parameters = list(values.values()) + [job_id]
 
251
  def get_active_job(session_id, conversation_id):
252
  with db_lock:
253
  connection = db_connect()
254
+ row = connection.execute("""
255
+ SELECT * FROM jobs WHERE session_id=? AND conversation_id=?
256
+ AND status IN ('queued', 'running') ORDER BY created DESC LIMIT 1
257
+ """, (session_id, conversation_id)).fetchone()
258
  connection.close()
259
  return dict(row) if row else None
260
 
261
  # =========================================================
262
+ # MODEL CACHE
263
  # =========================================================
264
+
265
  image_cache = {"name": None, "pipe": None}
266
  code_cache = {"name": None, "tokenizer": None, "model": None}
267
  image_lock = threading.RLock()
268
  code_lock = threading.RLock()
269
+ job_threads = {}
270
+ job_threads_lock = threading.RLock()
271
+ job_stop_events = {}
272
 
273
  def clear_image_cache():
274
+ old_pipe = image_cache["pipe"]
275
+ image_cache["pipe"] = None
276
+ image_cache["name"] = None
277
+ if old_pipe is not None:
278
+ del old_pipe
279
  gc.collect()
280
+ if torch.cuda.is_available():
281
+ torch.cuda.empty_cache()
282
 
283
  def clear_code_cache():
284
+ old_model = code_cache["model"]
285
+ old_tokenizer = code_cache["tokenizer"]
286
+ code_cache["model"] = None
287
+ code_cache["tokenizer"] = None
288
+ code_cache["name"] = None
289
+ if old_model is not None:
290
+ del old_model
291
+ if old_tokenizer is not None:
292
+ del old_tokenizer
293
  gc.collect()
294
 
295
  def load_image_pipeline(model_id, mode):
296
  cache_key = f"{mode}:{model_id}"
297
  with image_lock:
298
+ if image_cache["name"] == cache_key and image_cache["pipe"] is not None:
299
+ return image_cache["pipe"]
300
  clear_image_cache()
301
+ if mode == "text":
302
+ pipe = DiffusionPipeline.from_pretrained(model_id, torch_dtype=IMAGE_DTYPE, token=False)
303
+ elif mode == "image":
304
+ pipe = AutoPipelineForImage2Image.from_pretrained(model_id, torch_dtype=IMAGE_DTYPE, token=False)
305
+ else:
306
+ raise ValueError("Invalid image mode.")
307
  pipe = pipe.to("cuda")
308
+ if hasattr(pipe, "enable_attention_slicing"):
309
+ pipe.enable_attention_slicing()
310
+ image_cache["pipe"] = pipe
311
+ image_cache["name"] = cache_key
312
  return pipe
313
 
314
  @spaces.GPU(duration=120)
315
  def generate_image(prompt, negative_prompt, model_name, width, height, steps, seed, random_seed):
316
+ if not prompt or not prompt.strip():
317
+ raise gr.Error("Enter an image prompt.")
318
+ if model_name not in IMAGE_MODELS:
319
+ raise gr.Error("Invalid image model.")
320
  config = IMAGE_MODELS[model_name]
321
+ if random_seed:
322
+ seed = random.randint(0, 2147483647)
323
  seed = int(seed or 0)
324
  width = (max(256, min(int(width), 768)) // 8) * 8
325
  height = (max(256, min(int(height), 768)) // 8) * 8
326
  actual_steps = min(max(int(steps), 1), config["max_steps"])
327
+ if model_name in ["SDXL Turbo", "SD Turbo"]:
328
+ actual_steps = min(actual_steps, 4)
329
  try:
330
  with image_lock:
331
  pipe = load_image_pipeline(config["id"], "text")
332
  generator = torch.Generator(device="cuda").manual_seed(seed)
333
+ result = pipe(
334
+ prompt=prompt.strip(),
335
+ negative_prompt=negative_prompt or None,
336
+ width=width, height=height,
337
+ num_inference_steps=actual_steps,
338
+ guidance_scale=config["guidance"],
339
+ generator=generator,
340
+ )
341
  return result.images[0], seed
342
  except Exception as error:
343
+ traceback.print_exc()
344
  raise gr.Error(f"Image generation failed: {error}")
345
 
346
  @spaces.GPU(duration=120)
347
  def generate_image_to_image(input_image, prompt, negative_prompt, model_name, strength, steps, guidance, seed, random_seed):
348
+ if input_image is None:
349
+ raise gr.Error("Upload an image.")
350
+ if not prompt or not prompt.strip():
351
+ raise gr.Error("Enter transformation prompt.")
352
+ if model_name not in IMAGE_TO_IMAGE_MODELS:
353
+ raise gr.Error("Invalid image model.")
354
+ if random_seed:
355
+ seed = random.randint(0, 2147483647)
356
  seed = int(seed or 0)
357
+ strength = max(0.05, min(float(strength), 0.95))
358
+ steps = max(1, min(int(steps), 30))
359
  try:
360
  image = input_image.convert("RGB")
361
  image.thumbnail((768, 768), Image.Resampling.LANCZOS)
362
+ width = max(256, (image.width // 8) * 8)
363
+ height = max(256, (image.height // 8) * 8)
364
  image = image.resize((width, height), Image.Resampling.LANCZOS)
365
+ model_id = IMAGE_TO_IMAGE_MODELS[model_name]
366
  with image_lock:
367
+ pipe = load_image_pipeline(model_id, "image")
368
  generator = torch.Generator(device="cuda").manual_seed(seed)
369
+ result = pipe(
370
+ prompt=prompt.strip(), image=image,
371
+ negative_prompt=negative_prompt or None,
372
+ strength=strength, num_inference_steps=steps,
373
+ guidance_scale=float(guidance), generator=generator,
374
+ )
375
  return result.images[0], seed
376
  except Exception as error:
377
+ traceback.print_exc()
378
  raise gr.Error(f"Image-to-image failed: {error}")
379
 
380
  # =========================================================
381
+ # SYSTEM PROMPT
382
  # =========================================================
383
+
384
  SYSTEM_PROMPT = """
385
  You are ARISE AI, a professional software engineering assistant.
386
+
387
+ You specialize in: Python, Kotlin, Java, Android, Gradle, AAPT2,
388
+ JavaScript, TypeScript, HTML, CSS, React, APIs, databases, Hugging Face,
389
+ Gradio, PyTorch, Diffusers, Transformers, debugging, software architecture
390
+ and code optimization.
391
+
392
+ RULES:
393
+ 1. Understand the complete user request.
394
+ 2. Generate practical working code.
395
+ 3. Preserve existing features.
396
+ 4. Never intentionally omit important code.
397
+ 5. Analyze errors before proposing fixes.
398
+ 6. Return complete files when requested.
399
+ 7. Explain dependencies and limitations.
400
+ 8. Never claim code was tested unless tested.
401
+ 9. Use Markdown.
402
+ 10. Avoid unnecessary changes.
403
+ 11. Maintain environment compatibility.
404
+ 12. Do not invent file contents that were not provided.
405
+
406
+ PROJECT FILE EDITING FORMAT:
407
+ When modifying project files, return every complete modified or new file
408
+ using exactly this format:
409
+
410
  <<<FILE: relative/path/to/file.ext>>>
411
  complete file content here
412
  <<<END FILE>>>
413
+
414
+ Do not include unchanged files in this format.
415
+ Do not use absolute paths.
416
+ Do not use ../ path traversal.
417
+ Do not omit required imports or code.
418
+ Do not put explanatory text inside a file block.
419
+
420
+ When no file changes are needed, explain the answer normally.
421
  """
422
 
423
  def load_code_model(model_name):
424
+ if model_name not in CODE_MODELS:
425
+ raise ValueError("Invalid coding model.")
426
  model_id = CODE_MODELS[model_name]
427
  with code_lock:
428
+ if code_cache["name"] == model_id and code_cache["model"] is not None:
429
+ return code_cache["tokenizer"], code_cache["model"]
430
  clear_code_cache()
431
  tokenizer = AutoTokenizer.from_pretrained(model_id, token=False)
432
+ model = AutoModelForCausalLM.from_pretrained(
433
+ model_id, token=False, torch_dtype=torch.float32, low_cpu_mem_usage=True,
434
+ )
435
+ model.to("cpu")
436
  model.eval()
437
+ code_cache["name"] = model_id
438
+ code_cache["tokenizer"] = tokenizer
439
+ code_cache["model"] = model
440
  return tokenizer, model
441
 
442
+ # =========================================================
443
+ # FILE HELPERS
444
+ # =========================================================
445
+
446
  def safe_relative_path(value):
447
  value = str(value).replace("\\", "/").strip()
448
  path = Path(value)
449
+ if not value or path.is_absolute() or ".." in path.parts or "\x00" in value:
450
+ raise ValueError("Unsafe project file path.")
451
  return path
452
 
453
  def is_text_file(path):
454
+ return (path.suffix.lower() in SUPPORTED_TEXT_EXTENSIONS
455
+ or path.name.lower() in {"dockerfile", "makefile", ".gitignore"})
456
 
457
  def project_files(project_dir):
458
  result = []
 
460
  dirs[:] = [name for name in dirs if name not in EXCLUDED_DIRS]
461
  for filename in files:
462
  full_path = Path(root) / filename
463
+ if full_path.name == "project_index.json":
464
+ continue
465
+ try:
466
+ relative = full_path.relative_to(project_dir)
467
+ size = full_path.stat().st_size
468
+ except Exception:
469
+ continue
470
+ result.append({"path": relative.as_posix(), "size": size, "text": is_text_file(full_path)})
471
  return result
472
 
473
  def build_project_context(project_dir):
 
475
  output = ["PROJECT STRUCTURE:", json.dumps(files, ensure_ascii=False, indent=2), "", "PROJECT FILE CONTENTS:"]
476
  total = 0
477
  for item in files:
478
+ if not item["text"]:
479
+ continue
480
+ path = project_dir / item["path"]
481
+ try:
482
+ content = path.read_text(encoding="utf-8", errors="replace")
483
+ except Exception:
484
+ continue
485
  section = f"\n\n===== FILE: {item['path']} =====\n{content}\n===== END FILE =====\n"
486
  if total + len(section) > MAX_CONTEXT_SIZE:
487
+ output.append("\n[Project context truncated due to configured context limit.]")
488
  break
489
  output.append(section)
490
  total += len(section)
491
  return "\n".join(output), files
492
 
493
+ FILE_BLOCK_PATTERN = re.compile(
494
+ r"<<<FILE:\s*(.*?)>>>\s*(.*?)\s*<<<END FILE>>>",
495
+ re.DOTALL | re.IGNORECASE,
496
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
497
 
498
  def apply_file_changes(response, project_dir):
499
  changed = []
500
  for match in FILE_BLOCK_PATTERN.finditer(response):
501
+ relative_name = match.group(1).strip()
502
+ content = match.group(2)
503
  try:
504
+ relative = safe_relative_path(relative_name)
505
+ except Exception:
506
+ continue
507
+ target = Path(project_dir) / relative
508
+ target.parent.mkdir(parents=True, exist_ok=True)
509
+ target.write_text(content.rstrip() + "\n", encoding="utf-8")
510
+ changed.append(relative.as_posix())
511
  return changed
512
 
513
  def create_project_zip(project_dir):
514
+ project_dir = Path(project_dir)
515
  zip_path = DATA_DIR / ("ARISE_Project_" + uuid.uuid4().hex[:10] + ".zip")
516
  with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as archive:
517
  for root, dirs, files in os.walk(project_dir):
518
  dirs[:] = [name for name in dirs if name not in EXCLUDED_DIRS]
519
+ for filename in files:
520
+ full_path = Path(root) / filename
521
+ if full_path == zip_path:
522
+ continue
523
+ archive.write(full_path, full_path.relative_to(project_dir))
524
  return str(zip_path)
525
 
526
+ def create_single_file_download(project_dir, relative_name):
527
+ relative = safe_relative_path(relative_name)
528
+ source = Path(project_dir) / relative
529
+ if not source.exists() or not source.is_file():
530
+ return None
531
+ download_dir = DATA_DIR / "downloads"
532
+ download_dir.mkdir(exist_ok=True)
533
+ destination = download_dir / (uuid.uuid4().hex[:8] + "_" + source.name)
534
+ shutil.copy2(source, destination)
535
+ return str(destination)
536
+
537
+ def make_html_preview(project_dir):
538
+ project_dir = Path(project_dir)
539
+ html_files = list(project_dir.rglob("index.html")) or list(project_dir.rglob("*.html"))
540
+ if not html_files:
541
+ return "<div style='padding:25px;color:#ddd'>No HTML file found in this project.</div>"
542
+ html_file = html_files[0]
543
+ try:
544
+ html = html_file.read_text(encoding="utf-8", errors="replace")
545
+
546
+ def replace_asset(match):
547
+ asset_name = match.group(1).split("?")[0].split("#")[0]
548
+ asset_path = (html_file.parent / asset_name).resolve()
549
+ try:
550
+ asset_path.relative_to(project_dir.resolve())
551
+ except ValueError:
552
+ return match.group(0)
553
+ if not asset_path.exists():
554
+ return match.group(0)
555
+ content = asset_path.read_text(encoding="utf-8", errors="replace")
556
+ if match.group(0).lower().startswith("<link"):
557
+ return "<style>\n" + content + "\n</style>"
558
+ return "<script>\n" + content + "\n</script>"
559
+
560
+ html = re.sub(r'<link[^>]+href=["\']([^"\']+\.css)["\'][^>]*>', replace_asset, html, flags=re.IGNORECASE)
561
+ html = re.sub(r'<script[^>]+src=["\']([^"\']+\.js)["\'][^>]*>\s*</script>', replace_asset, html, flags=re.IGNORECASE)
562
+
563
+ return f"""
564
+ <iframe sandbox="allow-scripts allow-forms"
565
+ style="width:100%;height:650px;border:1px solid #34415e;border-radius:14px;background:white;"
566
+ srcdoc="{html.replace('&', '&amp;').replace('"', '&quot;').replace('<', '&lt;').replace('>', '&gt;')}"
567
+ ></iframe>
568
+ """
569
+ except Exception as error:
570
+ return f"<div style='padding:20px;color:#ff9999'>Preview error: {error}</div>"
571
+
572
  class StopCriteria(StoppingCriteria):
573
+ def __init__(self, event):
574
+ self.event = event
575
+
576
+ def __call__(self, input_ids, scores, **kwargs):
577
+ return self.event.is_set()
578
 
579
  # =========================================================
580
  # CODING WORKER
581
  # =========================================================
582
+
583
  def run_coding_worker(job_id, session_id, conversation_id, prompt, model_name, max_tokens, temperature, stop_event):
584
  try:
585
  update_job(job_id, status="running", response="")
586
  project_dir = get_project_dir(conversation_id)
587
  project_context, files = build_project_context(project_dir)
588
  tokenizer, model = load_code_model(model_name)
589
+
590
  messages = [{"role": "system", "content": SYSTEM_PROMPT}]
591
  conversation = get_conversation(session_id, conversation_id)
592
  history = conversation["history"] if conversation else []
593
+
594
+ for item in history[-MAX_HISTORY_MESSAGES:]:
595
+ if (isinstance(item, dict) and item.get("role") in ["user", "assistant"]
596
+ and isinstance(item.get("content"), str)):
597
+ messages.append({"role": item["role"], "content": item["content"]})
598
+
599
+ project_prompt = prompt
600
+ if files:
601
+ project_prompt = (
602
+ "PROJECT CONTEXT:\n" + project_context + "\n\nUSER REQUEST:\n" + prompt + "\n\n"
603
+ + "Analyze the supplied project before editing. Make only the requested changes. "
604
+ + "Return every changed/new file using the required <<<FILE: path>>> format."
605
+ )
606
  messages.append({"role": "user", "content": project_prompt})
607
 
608
+ if getattr(tokenizer, "chat_template", None):
609
+ formatted_prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
610
+ else:
611
+ formatted_prompt = "\n\n".join(f"{i['role'].upper()}:\n{i['content']}" for i in messages) + "\n\nASSISTANT:\n"
612
+
613
  inputs = tokenizer(formatted_prompt, return_tensors="pt", truncation=True, max_length=MAX_INPUT_LENGTH)
614
  streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=120)
615
+
616
  generation_kwargs = {
617
+ **inputs,
618
+ "streamer": streamer,
619
+ "max_new_tokens": max(128, min(int(max_tokens), 2048)),
620
+ "do_sample": float(temperature) > 0.05,
621
+ "temperature": max(float(temperature), 0.05),
622
+ "pad_token_id": tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id,
623
+ "stopping_criteria": StoppingCriteriaList([StopCriteria(stop_event)]),
624
  }
625
+
626
  errors = []
627
  def generate():
628
  try:
629
+ with torch.inference_mode():
630
+ model.generate(**generation_kwargs)
631
+ except Exception as error:
632
+ errors.append(str(error))
633
+ traceback.print_exc()
634
+ try:
635
+ streamer.end()
636
+ except Exception:
637
+ pass
638
+
639
+ generation_thread = Thread(target=generate, daemon=True)
640
+ generation_thread.start()
641
 
 
642
  response = ""
643
  for token in streamer:
644
+ if stop_event.is_set():
645
+ break
646
  response += token
647
  update_job(job_id, response=response, status="running")
648
+
649
+ generation_thread.join(timeout=15)
650
+ if generation_thread.is_alive():
651
+ stop_event.set()
652
+ if errors:
653
+ raise RuntimeError(errors[0])
654
+ if stop_event.is_set():
655
+ update_job(job_id, status="stopped", response=response + "\n\nGeneration stopped.")
656
+ return
657
+ if not response.strip():
658
+ response = "No response generated."
659
+
660
  changed_files = apply_file_changes(response, project_dir)
661
+ history = history + [
662
+ {"role": "user", "content": prompt},
663
+ {"role": "assistant", "content": response},
664
+ ]
665
+ title = prompt.strip().replace("\n", " ")[:55] or "ARISE Project"
666
+ save_conversation(session_id, conversation_id, title, history)
667
+
668
+ final_response = response
669
+ if changed_files:
670
+ file_status = "\n".join(
671
+ f"- <span style='color:#35d58a'>βœ“</span> `{name}` β€” Edited" for name in changed_files
672
+ )
673
+ final_response += "\n\n---\n### Project File Updates\n" + file_status
674
+
675
  update_job(job_id, status="completed", response=final_response)
676
+
677
+ except Exception as error:
678
+ traceback.print_exc()
679
+ update_job(job_id, status="error", error=str(error), response=f"**Coding error:** {error}")
680
  finally:
681
  with job_threads_lock:
682
  job_threads.pop(job_id, None)
683
  job_stop_events.pop(job_id, None)
684
 
685
+ def coding_assistant(prompt, model_name, max_tokens, temperature, conversation_id, request: gr.Request):
686
+ if not prompt or not prompt.strip():
687
+ yield ("Please enter your coding request.", conversation_id, "Waiting for prompt.", None, None, None)
688
+ return
689
+
690
  session_id = request.session_hash if request else "default"
691
+
692
+ if not conversation_id:
693
+ conversation_id = create_conversation(session_id, prompt.strip().replace("\n", " ")[:55])
694
+
695
  project_dir = get_project_dir(conversation_id)
696
+
 
697
  job_id = create_job(session_id, conversation_id, prompt.strip())
698
  stop_event = Event()
699
  with job_threads_lock:
700
  job_stop_events[job_id] = stop_event
701
+ worker = Thread(
702
+ target=run_coding_worker,
703
+ args=(job_id, session_id, conversation_id, prompt.strip(),
704
+ model_name, max_tokens, temperature, stop_event),
705
+ daemon=True,
706
+ )
707
+ job_threads[job_id] = worker
708
+ worker.start()
709
+
710
+ yield ("⏳ ARISE AI is analyzing your request...", conversation_id, "Job started.", None, None, job_id)
711
+
712
+ previous_response = ""
713
  while True:
714
  job = get_job(job_id, session_id)
715
+ if not job:
716
+ yield ("Job not found.", conversation_id, "Job unavailable.", None, None, job_id)
717
+ return
718
+
719
+ response = job["response"] or ""
720
+ status = job["status"]
721
+ status_text = {
722
+ "queued": "⏳ Waiting in queue",
723
+ "running": "βš™οΈ ARISE AI is working",
724
+ "completed": "βœ… Coding completed",
725
+ "stopped": "⏹ Generation stopped",
726
+ "error": "❌ Job failed",
727
+ }.get(status, status)
728
+
729
+ if response != previous_response or status not in ["queued", "running"]:
730
+ previous_response = response
731
  zip_file = None
732
+ single_file = None
733
+ if status == "completed":
734
+ zip_file = create_project_zip(project_dir)
735
+ changed = apply_file_changes(response, project_dir)
736
+ if changed:
737
+ single_file = create_single_file_download(project_dir, changed[-1])
738
+ yield (response or "No response yet.", conversation_id, status_text,
739
+ zip_file, single_file, job_id)
740
+
741
+ if status not in ["queued", "running"]:
742
+ return
743
  time.sleep(1)
744
 
745
+ def resume_job(job_id, request: gr.Request):
746
+ session_id = request.session_hash if request else "default"
747
+ if not job_id:
748
+ yield ("No active job selected.", "Nothing to resume.", None, None)
749
+ return
750
+ while True:
751
+ job = get_job(job_id, session_id)
752
+ if not job:
753
+ yield ("Job not found for this session.", "Job unavailable.", None, None)
754
+ return
755
+ status = job["status"]
756
+ response = job["response"] or ""
757
+ yield (response, f"Job status: {status}", None, None)
758
+ if status not in ["queued", "running"]:
759
+ return
760
+ time.sleep(2)
761
 
762
  def stop_job(job_id):
763
+ if not job_id:
764
+ return "No active job."
765
  with job_threads_lock:
766
+ event = job_stop_events.get(job_id)
767
+ if event:
768
+ event.set()
769
+ return "⏹ Stop requested."
770
  return "No running job found."
771
 
772
  # =========================================================
773
+ # HISTORY
774
+ # =========================================================
775
+
776
+ def refresh_history(request: gr.Request):
777
+ session_id = request.session_hash if request else "default"
778
+ return gr.Dropdown(choices=get_conversations(session_id), value=None)
779
+
780
+ def load_selected_history(conversation_id, request: gr.Request):
781
+ session_id = request.session_hash if request else "default"
782
+ if not conversation_id:
783
+ return ("", None, "Select a history item.", None)
784
+ conversation = get_conversation(session_id, conversation_id)
785
+ if not conversation:
786
+ return ("", None, "History not found.", None)
787
+ display = ""
788
+ for item in conversation["history"]:
789
+ role = item.get("role", "assistant").title()
790
+ content = item.get("content", "")
791
+ display += f"\n\n### {role}\n{content}\n"
792
+ active_job = get_active_job(session_id, conversation_id)
793
+ job_id = active_job["id"] if active_job else None
794
+ return (display or "This conversation is empty.", conversation_id,
795
+ f"Loaded: {conversation['title']}", job_id)
796
+
797
+ def delete_selected_history(conversation_ids, request: gr.Request):
798
+ session_id = request.session_hash if request else "default"
799
+ delete_conversations(session_id, conversation_ids or [])
800
+ return (gr.Dropdown(choices=get_conversations(session_id), value=None), "Selected history deleted.")
801
+
802
+ def clear_current_conversation():
803
+ return ("", None, "Ready for a new conversation.", None)
804
+
805
+ def preview_project(conversation_id):
806
+ if not conversation_id:
807
+ return "<p>No project selected.</p>"
808
+ return make_html_preview(get_project_dir(conversation_id))
809
+
810
+ # =========================================================
811
+ # PREMIUM CSS β€” GLOW / ANIMATION / NEON AURORA
812
  # =========================================================
813
+
814
+ CSS = r"""
815
+ @import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;600&display=swap');
816
+
817
+ :root {
818
+ color-scheme: dark;
819
+ --arise-violet: #8b5cf6;
820
+ --arise-cyan: #22d3ee;
821
+ --arise-pink: #f472b6;
822
+ --arise-deep: #06080f;
823
+ }
824
+
825
+ * { box-sizing: border-box; }
826
+
827
  body, .gradio-container {
828
+ font-family: 'Space Grotesk', -apple-system, sans-serif !important;
829
+ }
830
+
831
+ body {
832
+ background:
833
+ radial-gradient(circle at 10% 10%, rgba(139,92,246,0.18), transparent 40%),
834
+ radial-gradient(circle at 90% 20%, rgba(34,211,238,0.14), transparent 40%),
835
+ radial-gradient(circle at 50% 90%, rgba(244,114,182,0.12), transparent 45%),
836
+ #06080f !important;
837
+ min-height: 100vh;
838
+ overflow-x: hidden;
839
+ position: relative;
840
+ }
841
+
842
+ /* === AURORA BACKGROUND === */
843
+ body::before {
844
+ content: '';
845
+ position: fixed;
846
+ top: -50%;
847
+ left: -50%;
848
+ width: 200%;
849
+ height: 200%;
850
+ background:
851
+ conic-gradient(from 0deg at 30% 40%, rgba(139,92,246,0.15), transparent 25%),
852
+ conic-gradient(from 120deg at 70% 60%, rgba(34,211,238,0.12), transparent 25%),
853
+ conic-gradient(from 240deg at 50% 30%, rgba(244,114,182,0.12), transparent 25%);
854
+ animation: auroraRotate 40s linear infinite;
855
+ pointer-events: none;
856
+ z-index: 0;
857
+ filter: blur(80px);
858
+ opacity: 0.7;
859
+ }
860
+
861
+ @keyframes auroraRotate {
862
+ from { transform: rotate(0deg); }
863
+ to { transform: rotate(360deg); }
864
+ }
865
+
866
+ /* === FLOATING PARTICLES === */
867
+ body::after {
868
+ content: '';
869
+ position: fixed;
870
+ inset: 0;
871
+ background-image:
872
+ radial-gradient(1.5px 1.5px at 20% 30%, #fff, transparent),
873
+ radial-gradient(1px 1px at 80% 70%, #8b5cf6, transparent),
874
+ radial-gradient(1.5px 1.5px at 40% 80%, #22d3ee, transparent),
875
+ radial-gradient(1px 1px at 60% 20%, #f472b6, transparent),
876
+ radial-gradient(1px 1px at 90% 40%, #fff, transparent),
877
+ radial-gradient(1.5px 1.5px at 10% 60%, #22d3ee, transparent);
878
+ background-size: 300px 300px, 400px 400px, 500px 500px, 350px 350px, 450px 450px, 550px 550px;
879
+ animation: starsFloat 60s linear infinite;
880
+ pointer-events: none;
881
+ z-index: 0;
882
+ opacity: 0.55;
883
+ }
884
+
885
+ @keyframes starsFloat {
886
+ from { background-position: 0 0, 0 0, 0 0, 0 0, 0 0, 0 0; }
887
+ to { background-position: 300px 600px, -400px 400px, 500px -500px, -350px -350px, 450px 450px, -550px 550px; }
888
+ }
889
+
890
+ /* === CONTAINER === */
891
+ .gradio-container {
892
+ width: 100% !important;
893
+ max-width: 1300px !important;
894
+ margin: auto !important;
895
+ background: transparent !important;
896
+ padding: 14px !important;
897
+ position: relative;
898
+ z-index: 1;
899
+ animation: fadeBoot 1s ease-out;
900
+ }
901
+
902
+ @keyframes fadeBoot {
903
+ from { opacity: 0; transform: translateY(20px); }
904
+ to { opacity: 1; transform: translateY(0); }
905
+ }
906
+
907
+ /* === HEADER BANNER === */
908
+ #main-header {
909
+ position: relative;
910
+ overflow: hidden;
911
+ text-align: center;
912
+ padding: 46px 20px;
913
+ border: 1px solid rgba(139,92,246,0.4);
914
+ border-radius: 26px;
915
+ background:
916
+ linear-gradient(135deg, rgba(45,26,90,0.95) 0%, rgba(9,35,57,0.95) 50%, rgba(30,17,70,0.95) 100%);
917
+ box-shadow:
918
+ 0 0 40px rgba(139,92,246,0.25),
919
+ 0 0 80px rgba(34,211,238,0.12),
920
+ inset 0 1px 0 rgba(255,255,255,0.08);
921
+ animation: bannerPulse 4s ease-in-out infinite alternate;
922
+ }
923
+
924
+ @keyframes bannerPulse {
925
+ from {
926
+ box-shadow: 0 0 30px rgba(139,92,246,0.2), 0 0 60px rgba(34,211,238,0.08), inset 0 1px 0 rgba(255,255,255,0.05);
927
+ }
928
+ to {
929
+ box-shadow: 0 0 50px rgba(139,92,246,0.4), 0 0 100px rgba(34,211,238,0.2), inset 0 1px 0 rgba(255,255,255,0.1);
930
+ }
931
+ }
932
+
933
+ #main-header::before {
934
+ content: '';
935
+ position: absolute;
936
+ inset: -2px;
937
+ border-radius: 26px;
938
+ padding: 2px;
939
+ background: linear-gradient(135deg, #8b5cf6, #22d3ee, #f472b6, #8b5cf6);
940
+ background-size: 300% 300%;
941
+ -webkit-mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0);
942
+ -webkit-mask-composite: xor;
943
+ mask-composite: exclude;
944
+ animation: borderFlow 6s linear infinite;
945
+ pointer-events: none;
946
+ }
947
+
948
+ @keyframes borderFlow {
949
+ 0% { background-position: 0% 50%; }
950
+ 100% { background-position: 300% 50%; }
951
+ }
952
+
953
+ .hero-title {
954
+ font-family: 'Space Grotesk', sans-serif;
955
+ font-size: clamp(32px, 6vw, 62px);
956
+ font-weight: 800;
957
+ letter-spacing: -2px;
958
+ background: linear-gradient(90deg, #fff 0%, #b8a5ff 25%, #56e8ff 50%, #f472b6 75%, #fff 100%);
959
+ background-size: 300% auto;
960
+ -webkit-background-clip: text;
961
+ -webkit-text-fill-color: transparent;
962
+ background-clip: text;
963
+ animation: heroShine 5s linear infinite;
964
+ text-shadow: 0 0 40px rgba(139,92,246,0.4);
965
+ }
966
+
967
+ @keyframes heroShine {
968
+ 0% { background-position: 0% center; }
969
+ 100% { background-position: 300% center; }
970
+ }
971
+
972
+ .hero-subtitle {
973
+ color: #bdc7df;
974
+ font-size: 13px;
975
+ letter-spacing: 4px;
976
+ margin-top: 14px;
977
+ font-weight: 600;
978
+ text-transform: uppercase;
979
+ }
980
+
981
+ .hero-badges span {
982
+ display: inline-flex;
983
+ align-items: center;
984
+ gap: 6px;
985
+ background: rgba(255,255,255,0.06);
986
+ backdrop-filter: blur(10px);
987
+ padding: 8px 16px;
988
+ border-radius: 30px;
989
+ color: #d8d5ff;
990
+ font-size: 12px;
991
+ font-weight: 500;
992
+ margin: 4px;
993
+ border: 1px solid rgba(255,255,255,0.1);
994
+ transition: all 0.3s ease;
995
+ }
996
+
997
+ .hero-badges span:hover {
998
+ background: rgba(139,92,246,0.25);
999
+ border-color: rgba(139,92,246,0.6);
1000
+ box-shadow: 0 0 20px rgba(139,92,246,0.5);
1001
+ transform: translateY(-3px);
1002
+ }
1003
+
1004
+ /* === TABS === */
1005
+ .gradio-container .tab-nav {
1006
+ border: 1px solid rgba(139,92,246,0.3) !important;
1007
+ border-radius: 18px !important;
1008
+ background: rgba(18,24,40,0.85) !important;
1009
+ backdrop-filter: blur(14px);
1010
+ padding: 8px !important;
1011
+ box-shadow: 0 0 30px rgba(139,92,246,0.1);
1012
+ }
1013
+
1014
+ .gradio-container .tab-nav button {
1015
  border-radius: 12px !important;
1016
+ transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
1017
+ font-weight: 600 !important;
1018
+ letter-spacing: 0.3px;
1019
  }
1020
+
1021
+ .gradio-container .tab-nav button:hover {
1022
+ background: rgba(139,92,246,0.15) !important;
1023
+ color: #b8a5ff !important;
1024
+ }
1025
+
1026
+ .gradio-container .tab-nav button.selected {
1027
+ background: linear-gradient(135deg, #7045ed, #168edb) !important;
1028
+ color: #fff !important;
1029
+ box-shadow: 0 0 25px rgba(139,92,246,0.6) !important;
1030
  }
1031
+
1032
+ /* === BUTTONS === */
1033
+ .gradio-container button {
 
1034
  border-radius: 12px !important;
1035
+ transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
1036
+ font-weight: 600 !important;
1037
+ position: relative;
1038
+ overflow: hidden;
1039
+ }
1040
+
1041
+ .gradio-container button::before {
1042
+ content: '';
1043
+ position: absolute;
1044
+ top: 50%;
1045
+ left: 50%;
1046
+ width: 0;
1047
+ height: 0;
1048
+ border-radius: 50%;
1049
+ background: rgba(255,255,255,0.3);
1050
+ transform: translate(-50%, -50%);
1051
+ transition: width 0.6s, height 0.6s;
1052
+ pointer-events: none;
1053
+ }
1054
+
1055
+ .gradio-container button:active::before {
1056
+ width: 300px;
1057
+ height: 300px;
1058
+ }
1059
+
1060
+ .gradio-container button:hover {
1061
+ transform: translateY(-2px);
1062
+ box-shadow: 0 8px 25px rgba(139,92,246,0.4);
1063
+ }
1064
+
1065
+ .primary {
1066
+ background: linear-gradient(135deg, #7045ed 0%, #a855f7 50%, #168edb 100%) !important;
1067
+ background-size: 200% 200% !important;
1068
+ color: white !important;
1069
+ font-weight: 700 !important;
1070
+ letter-spacing: 0.5px;
1071
+ animation: gradientShift 3s ease infinite;
1072
+ box-shadow: 0 4px 20px rgba(139,92,246,0.4) !important;
1073
+ }
1074
+
1075
+ @keyframes gradientShift {
1076
+ 0%, 100% { background-position: 0% 50%; }
1077
+ 50% { background-position: 100% 50%; }
1078
+ }
1079
+
1080
+ .primary:hover {
1081
+ box-shadow: 0 8px 35px rgba(139,92,246,0.7), 0 0 60px rgba(34,211,238,0.3) !important;
1082
+ }
1083
+
1084
+ .stop-btn, button[variant="stop"] {
1085
+ background: linear-gradient(135deg, #dc2626, #f97316) !important;
1086
+ color: white !important;
1087
+ box-shadow: 0 4px 20px rgba(220,38,38,0.4) !important;
1088
  }
1089
+
1090
+ .stop-btn:hover, button[variant="stop"]:hover {
1091
+ box-shadow: 0 8px 30px rgba(220,38,38,0.7) !important;
1092
+ }
1093
+
1094
+ /* === INPUTS === */
1095
+ textarea, input[type="text"], input[type="number"], .gr-box {
1096
+ border-radius: 14px !important;
1097
+ background: rgba(15,20,35,0.7) !important;
1098
+ border: 1px solid rgba(139,92,246,0.2) !important;
1099
+ transition: all 0.3s ease !important;
1100
+ backdrop-filter: blur(10px);
1101
+ }
1102
+
1103
+ textarea:focus, input:focus {
1104
+ border-color: rgba(139,92,246,0.7) !important;
1105
+ box-shadow: 0 0 0 3px rgba(139,92,246,0.2), 0 0 30px rgba(139,92,246,0.3) !important;
1106
+ outline: none !important;
1107
+ }
1108
+
1109
+ /* === CODING OUTPUT β€” the star of the show === */
1110
+ #coding-output {
1111
+ min-height: 320px;
1112
+ padding: 22px;
1113
+ border: 1px solid rgba(34,211,238,0.3);
1114
+ border-radius: 18px;
1115
+ background:
1116
+ linear-gradient(135deg, rgba(9,15,28,0.92), rgba(18,15,40,0.92));
1117
+ backdrop-filter: blur(16px);
1118
+ overflow-wrap: anywhere;
1119
+ position: relative;
1120
+ box-shadow:
1121
+ 0 0 30px rgba(34,211,238,0.15),
1122
+ inset 0 1px 0 rgba(255,255,255,0.05);
1123
+ transition: all 0.4s ease;
1124
+ font-family: 'JetBrains Mono', 'Space Grotesk', monospace;
1125
+ font-size: 14px;
1126
+ line-height: 1.7;
1127
+ }
1128
+
1129
+ #coding-output::before {
1130
+ content: '';
1131
+ position: absolute;
1132
+ top: 0;
1133
+ left: 0;
1134
+ right: 0;
1135
+ height: 2px;
1136
+ background: linear-gradient(90deg, transparent, #22d3ee, #8b5cf6, transparent);
1137
+ border-radius: 18px 18px 0 0;
1138
+ animation: scanline 3s ease-in-out infinite;
1139
+ }
1140
+
1141
+ @keyframes scanline {
1142
+ 0%, 100% { opacity: 0.4; }
1143
+ 50% { opacity: 1; box-shadow: 0 0 15px #22d3ee; }
1144
+ }
1145
+
1146
+ #coding-output pre {
1147
+ max-width: 100%;
1148
+ overflow-x: auto;
1149
+ background: rgba(0,0,0,0.5) !important;
1150
+ padding: 14px !important;
1151
+ border-radius: 10px !important;
1152
+ border: 1px solid rgba(139,92,246,0.15);
1153
+ }
1154
+
1155
+ /* Blinking cursor while streaming */
1156
+ #coding-output.streaming::after {
1157
+ content: 'β–‹';
1158
+ color: #22d3ee;
1159
+ animation: cursorBlink 0.8s step-end infinite;
1160
+ margin-left: 2px;
1161
+ text-shadow: 0 0 10px #22d3ee;
1162
+ }
1163
+
1164
+ @keyframes cursorBlink {
1165
+ 0%, 50% { opacity: 1; }
1166
+ 51%, 100% { opacity: 0; }
1167
+ }
1168
+
1169
+ /* === STATUS BADGE === */
1170
+ #coding-status {
1171
+ display: inline-block;
1172
+ padding: 8px 16px;
1173
+ border-radius: 20px;
1174
+ background: rgba(34,211,238,0.1);
1175
+ border: 1px solid rgba(34,211,238,0.3);
1176
+ color: #a5f3fc;
1177
+ font-size: 12px;
1178
+ font-weight: 600;
1179
+ letter-spacing: 0.5px;
1180
+ animation: statusPulse 2s ease-in-out infinite;
1181
+ }
1182
+
1183
+ @keyframes statusPulse {
1184
+ 0%, 100% { box-shadow: 0 0 10px rgba(34,211,238,0.3); }
1185
+ 50% { box-shadow: 0 0 25px rgba(34,211,238,0.6); }
1186
+ }
1187
+
1188
+ /* === SCROLLBAR === */
1189
+ ::-webkit-scrollbar {
1190
+ width: 8px;
1191
+ height: 8px;
1192
+ }
1193
+
1194
+ ::-webkit-scrollbar-track {
1195
+ background: rgba(255,255,255,0.03);
1196
+ border-radius: 10px;
1197
+ }
1198
+
1199
+ ::-webkit-scrollbar-thumb {
1200
+ background: linear-gradient(180deg, #8b5cf6, #22d3ee);
1201
+ border-radius: 10px;
1202
+ box-shadow: 0 0 10px rgba(139,92,246,0.5);
1203
+ }
1204
+
1205
+ ::-webkit-scrollbar-thumb:hover {
1206
+ background: linear-gradient(180deg, #a855f7, #67e8f9);
1207
+ }
1208
+
1209
+ /* === MENU PANEL === */
1210
+ #menu-panel {
1211
+ border: 1px solid rgba(139,92,246,0.4);
1212
+ background: rgba(16,22,39,0.92);
1213
+ backdrop-filter: blur(20px);
1214
+ border-radius: 16px;
1215
+ padding: 16px;
1216
+ box-shadow: 0 0 40px rgba(139,92,246,0.2);
1217
+ animation: menuSlide 0.4s ease-out;
1218
+ }
1219
+
1220
+ @keyframes menuSlide {
1221
+ from { opacity: 0; transform: translateY(-10px); }
1222
+ to { opacity: 1; transform: translateY(0); }
1223
+ }
1224
+
1225
+ /* === FOOTER === */
1226
+ #footer {
1227
+ text-align: center;
1228
+ color: #8390ad;
1229
+ padding: 30px 20px;
1230
+ border-top: 1px solid rgba(139,92,246,0.15);
1231
+ margin-top: 30px;
1232
+ position: relative;
1233
+ }
1234
+
1235
+ #footer::before {
1236
+ content: '';
1237
+ position: absolute;
1238
+ top: 0;
1239
+ left: 30%;
1240
+ right: 30%;
1241
+ height: 1px;
1242
+ background: linear-gradient(90deg, transparent, #8b5cf6, transparent);
1243
+ animation: footerGlow 3s ease-in-out infinite;
1244
+ }
1245
+
1246
+ @keyframes footerGlow {
1247
+ 0%, 100% { opacity: 0.3; box-shadow: none; }
1248
+ 50% { opacity: 1; box-shadow: 0 0 15px #8b5cf6; }
1249
+ }
1250
+
1251
+ #footer a {
1252
+ color: #a5b4fc;
1253
+ text-decoration: none;
1254
+ transition: all 0.3s;
1255
+ }
1256
+
1257
+ #footer a:hover {
1258
+ color: #67e8f9;
1259
+ text-shadow: 0 0 15px #67e8f9;
1260
+ }
1261
+
1262
+ /* === CARD HOVER EFFECT for blocks === */
1263
+ .gradio-container .block {
1264
+ transition: all 0.3s ease;
1265
+ }
1266
+
1267
+ .gradio-container .block:hover {
1268
+ border-color: rgba(139,92,246,0.4) !important;
1269
+ }
1270
+
1271
+ /* === LOADING SPINNER === */
1272
+ .generating {
1273
+ position: relative;
1274
+ }
1275
+
1276
+ .generating::after {
1277
+ content: '';
1278
+ position: absolute;
1279
+ top: 12px;
1280
+ right: 12px;
1281
+ width: 16px;
1282
+ height: 16px;
1283
+ border: 2px solid rgba(34,211,238,0.3);
1284
+ border-top-color: #22d3ee;
1285
+ border-radius: 50%;
1286
+ animation: spin 0.8s linear infinite;
1287
+ }
1288
+
1289
+ @keyframes spin {
1290
+ to { transform: rotate(360deg); }
1291
+ }
1292
+
1293
+ /* === MOBILE === */
1294
+ @media(max-width: 650px) {
1295
+ .gradio-container { padding: 6px !important; }
1296
+ #main-header { padding: 28px 12px; border-radius: 18px; }
1297
+ .hero-title { font-size: 30px; letter-spacing: -1px; }
1298
+ .hero-subtitle { font-size: 10px; letter-spacing: 2px; }
1299
+ .gradio-container .tab-nav button {
1300
+ font-size: 11px !important;
1301
+ padding: 8px 5px !important;
1302
+ }
1303
+ #coding-output {
1304
+ min-height: 240px;
1305
+ padding: 12px;
1306
+ font-size: 12px;
1307
+ }
1308
+ }
1309
+ """
1310
+
1311
+ # =========================================================
1312
+ # PREMIUM JS β€” TYPING CURSOR + RIPPLE + SMOOTH SCROLL
1313
+ # =========================================================
1314
+
1315
+ PREMIUM_JS = """
1316
+ () => {
1317
+ // Typing cursor effect on streaming output
1318
+ const attachCursor = () => {
1319
+ const output = document.querySelector('#coding-output');
1320
+ if (!output) return;
1321
+ if (output.dataset.cursorAttached) return;
1322
+ output.dataset.cursorAttached = '1';
1323
+
1324
+ let streamTimer = null;
1325
+ const observer = new MutationObserver(() => {
1326
+ output.classList.add('streaming');
1327
+ clearTimeout(streamTimer);
1328
+ streamTimer = setTimeout(() => {
1329
+ output.classList.remove('streaming');
1330
+ }, 1200);
1331
+ });
1332
+ observer.observe(output, { childList: true, subtree: true, characterData: true });
1333
+ };
1334
+
1335
+ // Ripple effect on all buttons
1336
+ const attachRipple = () => {
1337
+ document.querySelectorAll('button').forEach((btn) => {
1338
+ if (btn.dataset.rippleAttached) return;
1339
+ btn.dataset.rippleAttached = '1';
1340
+ btn.style.position = 'relative';
1341
+ btn.style.overflow = 'hidden';
1342
+ });
1343
+ };
1344
+
1345
+ // Smooth auto-scroll for output
1346
+ const attachAutoScroll = () => {
1347
+ const output = document.querySelector('#coding-output');
1348
+ if (!output || output.dataset.scrollAttached) return;
1349
+ output.dataset.scrollAttached = '1';
1350
+ const observer = new MutationObserver(() => {
1351
+ const nearBottom = output.scrollHeight - output.scrollTop - output.clientHeight < 200;
1352
+ if (nearBottom) {
1353
+ output.scrollTop = output.scrollHeight;
1354
+ }
1355
+ });
1356
+ observer.observe(output, { childList: true, subtree: true, characterData: true });
1357
+ };
1358
+
1359
+ // Apply on load
1360
+ attachCursor();
1361
+ attachRipple();
1362
+ attachAutoScroll();
1363
+
1364
+ // Re-apply on Gradio re-renders
1365
+ const globalObserver = new MutationObserver(() => {
1366
+ attachCursor();
1367
+ attachRipple();
1368
+ attachAutoScroll();
1369
+ });
1370
+ globalObserver.observe(document.body, { childList: true, subtree: true });
1371
+
1372
+ // Console signature
1373
+ console.log('%c⚑ ARISE AI STUDIO', 'color:#8b5cf6;font-size:20px;font-weight:bold;text-shadow:0 0 10px #8b5cf6;');
1374
+ console.log('%cPremium AI Workspace Loaded', 'color:#22d3ee;font-size:12px;');
1375
+ }
1376
+ """
1377
+
1378
+ # =========================================================
1379
+ # HEADER
1380
+ # =========================================================
1381
+
1382
+ HEADER = """
1383
+ <div id="main-header">
1384
+ <div style="
1385
+ font-size: 12px;
1386
+ color: #83eaff;
1387
+ letter-spacing: 4px;
1388
+ font-weight: 800;
1389
+ margin-bottom: 14px;
1390
+ text-shadow: 0 0 20px #22d3ee;
1391
+ ">
1392
+ ✦ NEXT GENERATION ARTIFICIAL INTELLIGENCE ✦
1393
+ </div>
1394
+
1395
+ <div class="hero-title">⚑ ARISE AI STUDIO</div>
1396
+
1397
+ <div class="hero-subtitle">
1398
+ CREATE Β· TRANSFORM Β· CODE Β· INNOVATE
1399
+ </div>
1400
+
1401
+ <div class="hero-badges" style="
1402
+ display: flex;
1403
+ justify-content: center;
1404
+ flex-wrap: wrap;
1405
+ gap: 10px;
1406
+ margin-top: 24px;
1407
+ ">
1408
+ <span>🎨 AI Art</span>
1409
+ <span>πŸ–Ό Image Transform</span>
1410
+ <span>πŸ’» AI Coding</span>
1411
+ <span>⚑ Live Stream</span>
1412
+ </div>
1413
+ </div>
1414
  """
1415
 
1416
  # =========================================================
1417
  # GRADIO APP
1418
  # =========================================================
1419
+
1420
  with gr.Blocks(title=APP_NAME) as demo:
1421
+
1422
  conversation_state = gr.State(None)
1423
  job_state = gr.State(None)
1424
 
1425
+ gr.HTML(HEADER)
1426
+
1427
  with gr.Row():
1428
+ menu_button = gr.Button("☰ Menu", size="sm")
1429
+ gr.Markdown(f"[Developer Contact β†—]({DEVELOPER_TELEGRAM})")
1430
+
1431
+ with gr.Column(visible=False, elem_id="menu-panel") as menu_panel:
1432
+ gr.Markdown("### ⚑ ARISE AI Studio Menu")
1433
+ gr.Markdown(f"**Developer Contact:** [Telegram @hardhackar009]({DEVELOPER_TELEGRAM})")
1434
+ gr.Markdown("Open the **History** tab to load, select or delete saved conversations.")
1435
+
1436
+ menu_button.click(lambda: gr.update(visible=True), outputs=menu_panel)
1437
+
1438
+ gr.Markdown("""
1439
+ <div style="text-align:center;color:#9ba9c5;padding:12px;font-size:13px;letter-spacing:1px">
1440
+ ✦ PREMIUM AI WORKSPACE · OPEN MODELS · LIVE GENERATION ✦
1441
+ </div>
1442
+ """)
1443
+
1444
+ with gr.Tabs():
1445
+
1446
+ # --- TEXT TO IMAGE ---
1447
+ with gr.Tab("🎨 Text to Image"):
1448
+ gr.Markdown("## 🎨 Create Images with AI")
1449
+
1450
+ image_model = gr.Dropdown(
1451
+ choices=list(IMAGE_MODELS.keys()),
1452
+ value="SDXL Turbo",
1453
+ label="Select Image Model",
1454
+ )
1455
+ image_prompt = gr.Textbox(
1456
+ label="Image Prompt",
1457
+ placeholder="Describe your image in detail...",
1458
+ lines=4,
1459
+ )
1460
+ negative_prompt = gr.Textbox(label="Negative Prompt", lines=2)
1461
+
1462
+ with gr.Row():
1463
+ width = gr.Slider(256, 768, value=512, step=64, label="Image Width")
1464
+ height = gr.Slider(256, 768, value=512, step=64, label="Image Height")
1465
+
1466
+ steps = gr.Slider(1, 30, value=4, step=1, label="Inference Steps")
1467
+
1468
+ with gr.Row():
1469
+ seed = gr.Number(value=0, precision=0, label="Seed")
1470
+ random_seed = gr.Checkbox(value=True, label="Random Seed")
1471
+
1472
+ generate_button = gr.Button("✨ Generate Image", variant="primary")
1473
+ image_output = gr.Image(label="Generated Artwork", type="pil", height=400)
1474
+ seed_output = gr.Number(label="Used Seed", precision=0)
1475
+
1476
+ generate_button.click(
1477
+ fn=generate_image,
1478
+ inputs=[image_prompt, negative_prompt, image_model, width, height, steps, seed, random_seed],
1479
+ outputs=[image_output, seed_output],
1480
+ )
1481
+
1482
+ # --- IMAGE TO IMAGE ---
1483
+ with gr.Tab("πŸ–Ό Image to Image"):
1484
+ gr.Markdown("## πŸ–Ό Transform Your Images")
1485
+
1486
+ input_image = gr.Image(label="Upload Original Image", type="pil", height=300)
1487
+ img2img_model = gr.Dropdown(
1488
+ choices=list(IMAGE_TO_IMAGE_MODELS.keys()),
1489
+ value="Stable Diffusion 1.5 Img2Img",
1490
+ label="Image-to-Image Model",
1491
+ )
1492
+ img2img_prompt = gr.Textbox(label="Transformation Prompt",
1493
+ placeholder="Describe the new image style...", lines=4)
1494
+ img2img_negative = gr.Textbox(label="Negative Prompt", lines=2)
1495
+ strength = gr.Slider(0.05, 0.95, value=0.70, step=0.05, label="Transformation Strength")
1496
+
1497
+ with gr.Row():
1498
+ img2img_steps = gr.Slider(1, 30, value=25, step=1, label="Inference Steps")
1499
+ img2img_guidance = gr.Slider(1, 15, value=7.5, step=0.5, label="Guidance Scale")
1500
+
1501
+ with gr.Row():
1502
+ img2img_seed = gr.Number(value=0, precision=0, label="Seed")
1503
+ img2img_random = gr.Checkbox(value=True, label="Random Seed")
1504
+
1505
+ img2img_button = gr.Button("πŸͺ„ Transform Image", variant="primary")
1506
+ img2img_output = gr.Image(label="Transformed Image", type="pil", height=400)
1507
+ img2img_seed_output = gr.Number(label="Used Seed", precision=0)
1508
+
1509
+ img2img_button.click(
1510
+ fn=generate_image_to_image,
1511
+ inputs=[input_image, img2img_prompt, img2img_negative, img2img_model,
1512
+ strength, img2img_steps, img2img_guidance, img2img_seed, img2img_random],
1513
+ outputs=[img2img_output, img2img_seed_output],
1514
+ )
1515
+
1516
+ # --- AI CODING ---
1517
+ with gr.Tab("πŸ’» AI Coding"):
1518
+ gr.Markdown("""
1519
+ ## πŸ’» ARISE AI Coding Workspace
1520
+ Describe your changes, and download the updated project.
1521
+ """)
1522
+
1523
+ code_model = gr.Dropdown(
1524
+ choices=list(CODE_MODELS.keys()),
1525
+ value="Qwen Coder 0.5B",
1526
+ label="Select Coding Model",
1527
+ )
1528
 
1529
+ # Note: Upload option removed as requested
1530
+ code_prompt = gr.Textbox(
1531
+ label="Your Coding Request",
1532
+ placeholder="Example: Change the app theme and update the home screen...",
1533
+ lines=5,
1534
+ )
1535
+
1536
+ with gr.Row():
1537
+ max_tokens = gr.Slider(128, 2048, value=768, step=128, label="Maximum Output Tokens")
1538
  temperature = gr.Slider(0.1, 1.0, value=0.3, step=0.1, label="Temperature")
1539
+
1540
+ coding_output = gr.Markdown(
1541
+ value="Ready to work on your project.",
1542
+ elem_id="coding-output",
1543
+ )
1544
+
1545
+ with gr.Row():
1546
+ generate_code = gr.Button("⚑ Start Coding", variant="primary")
1547
+ stop_button = gr.Button("⏹ Stop", variant="stop")
1548
+ new_project_button = gr.Button("οΌ‹ New Project", variant="secondary")
1549
+
1550
+ coding_status = gr.Markdown("Ready.", elem_id="coding-status")
1551
+
1552
+ gr.Markdown("### πŸ“¦ Project Downloads")
1553
+
1554
+ with gr.Row():
1555
+ project_zip_download = gr.File(label="Download Full Project ZIP", interactive=False)
1556
+ single_file_download = gr.File(label="Download Last Edited File", interactive=False)
1557
+
1558
+ preview_button = gr.Button("🌐 Preview HTML Project")
1559
+ html_preview = gr.HTML(
1560
+ value="<div style='padding:15px;color:#aaa'>HTML preview will appear here.</div>"
1561
+ )
1562
+
1563
+ # Updated inputs: removed 'project_upload'
1564
+ generate_code.click(
1565
+ fn=coding_assistant,
1566
+ inputs=[code_prompt, code_model, max_tokens, temperature, conversation_state],
1567
+ outputs=[coding_output, conversation_state, coding_status,
1568
+ project_zip_download, single_file_download, job_state],
1569
+ )
1570
+ stop_button.click(fn=stop_job, inputs=job_state, outputs=coding_status)
1571
+ new_project_button.click(
1572
+ fn=clear_current_conversation,
1573
+ outputs=[coding_output, conversation_state, coding_status, job_state],
1574
+ )
1575
+ preview_button.click(fn=preview_project, inputs=conversation_state, outputs=html_preview)
1576
+
1577
+ # --- HISTORY ---
1578
+ with gr.Tab("πŸ“š History"):
1579
+ gr.Markdown("## πŸ“š Saved Conversations and Projects")
1580
+
1581
+ history_dropdown = gr.Dropdown(choices=[], label="Saved History", interactive=True)
1582
+
1583
+ with gr.Row():
1584
+ refresh_history_button = gr.Button("πŸ”„ Refresh History")
1585
+ load_history_button = gr.Button("πŸ“‚ Open Selected", variant="primary")
1586
+
1587
+ history_output = gr.Markdown("Select a saved conversation.")
1588
+ history_status = gr.Markdown("")
1589
+ resume_button = gr.Button("β–Ά Resume Selected Job")
1590
+
1591
+ with gr.Row():
1592
+ delete_history_button = gr.Button("πŸ—‘ Delete Selected", variant="stop")
1593
+ delete_all_history_button = gr.Button("πŸ—‘ Delete All", variant="stop")
1594
+
1595
+ refresh_history_button.click(fn=refresh_history, outputs=history_dropdown)
1596
+ load_history_button.click(
1597
+ fn=load_selected_history,
1598
+ inputs=history_dropdown,
1599
+ outputs=[history_output, conversation_state, history_status, job_state],
1600
+ )
1601
+ delete_history_button.click(
1602
+ fn=delete_selected_history,
1603
+ inputs=history_dropdown,
1604
+ outputs=[history_dropdown, history_status],
1605
+ )
1606
+
1607
+ def delete_all(request: gr.Request):
1608
+ session_id = request.session_hash if request else "default"
1609
+ choices = get_conversations(session_id)
1610
+ ids = [value for _, value in choices]
1611
+ delete_conversations(session_id, ids)
1612
+ return (gr.Dropdown(choices=[], value=None), "All history deleted.")
1613
+
1614
+ delete_all_history_button.click(
1615
+ fn=delete_all,
1616
+ outputs=[history_dropdown, history_status],
1617
+ )
1618
+ resume_button.click(
1619
+ fn=resume_job,
1620
+ inputs=job_state,
1621
+ outputs=[history_output, history_status, project_zip_download, single_file_download],
1622
+ )
1623
+
1624
+ # --- FOOTER ---
1625
+ gr.HTML(f"""
1626
+ <div id="footer">
1627
+ <div style="font-size:22px;font-weight:800;
1628
+ background:linear-gradient(90deg,#c7b7ff,#67e8f9);
1629
+ -webkit-background-clip:text;-webkit-text-fill-color:transparent;
1630
+ margin-bottom:8px;">
1631
+ ⚑ ARISE AI STUDIO
1632
+ </div>
1633
+ <div style="color:#a5b4fc;font-size:13px;letter-spacing:1px">
1634
+ Premium AI Workspace
1635
+ </div>
1636
+ <div style="margin-top:10px;font-size:12px">
1637
+ Developer: <a href="{DEVELOPER_TELEGRAM}" target="_blank">@hardhackar009</a>
1638
+ </div>
1639
+ <div style="margin-top:8px;font-size:11px;color:#64748b">
1640
+ Powered by Open Source Models and Hugging Face
1641
+ </div>
1642
+ </div>
1643
+ """)
1644
+
1645
+ # Attach premium JS on load
1646
+ demo.load(fn=None, js=PREMIUM_JS)
1647
 
1648
  # =========================================================
1649
  # LAUNCH
1650
  # =========================================================
1651
+
1652
  if __name__ == "__main__":
1653
+ demo.queue(
1654
+ default_concurrency_limit=1,
1655
+ max_size=20,
1656
+ ).launch(
1657
+ theme=gr.themes.Soft(
1658
+ primary_hue="violet",
1659
+ secondary_hue="cyan",
1660
+ neutral_hue="slate",
1661
  ),
1662
  css=CSS,
1663
+ allowed_paths=[str(DATA_DIR.resolve())], # Path Fix Added
1664
  show_error=True,
1665
  share=False,
1666
  )