lastwarning commited on
Commit
290d8c1
Β·
verified Β·
1 Parent(s): cb3e2ab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +763 -1465
app.py CHANGED
@@ -1,4 +1,3 @@
1
-
2
  import os
3
  import gc
4
  import re
@@ -39,7 +38,6 @@ from transformers import (
39
 
40
  from threading import Thread, Event
41
 
42
-
43
  # =========================================================
44
  # CONFIGURATION
45
  # =========================================================
@@ -56,7 +54,6 @@ MAX_CONTEXT_SIZE = 80000
56
 
57
  IMAGE_DTYPE = torch.float16
58
 
59
- # For persistent Hugging Face Storage, mount storage at /data.
60
  DATA_DIR = Path(os.getenv("ARISE_DATA_DIR", "/data/arise_ai_studio"))
61
 
62
  try:
@@ -91,91 +88,40 @@ EXCLUDED_DIRS = {
91
  "dist", ".venv", "venv", ".next",
92
  }
93
 
94
-
95
- # =========================================================
96
- # IMAGE MODELS
97
- # =========================================================
98
-
99
  IMAGE_MODELS = {
100
- "SDXL Turbo": {
101
- "id": "stabilityai/sdxl-turbo",
102
- "steps": 4,
103
- "guidance": 0.0,
104
- "max_steps": 4,
105
- },
106
- "Stable Diffusion 1.5": {
107
- "id": "stable-diffusion-v1-5/stable-diffusion-v1-5",
108
- "steps": 25,
109
- "guidance": 7.5,
110
- "max_steps": 30,
111
- },
112
- "SD Turbo": {
113
- "id": "stabilityai/sd-turbo",
114
- "steps": 4,
115
- "guidance": 0.0,
116
- "max_steps": 4,
117
- },
118
- "Tiny SD": {
119
- "id": "segmind/tiny-sd",
120
- "steps": 20,
121
- "guidance": 7.5,
122
- "max_steps": 30,
123
- },
124
  }
125
 
126
-
127
  IMAGE_TO_IMAGE_MODELS = {
128
- "Stable Diffusion 1.5 Img2Img":
129
- "stable-diffusion-v1-5/stable-diffusion-v1-5",
130
  }
131
 
132
-
133
- # =========================================================
134
- # CODING MODELS
135
- # =========================================================
136
-
137
  CODE_MODELS = {
138
- "Qwen Coder 0.5B":
139
- "Qwen/Qwen2.5-Coder-0.5B-Instruct",
140
-
141
- "Qwen Coder 1.5B":
142
- "Qwen/Qwen2.5-Coder-1.5B-Instruct",
143
-
144
- "DeepSeek Coder 1.3B":
145
- "deepseek-ai/deepseek-coder-1.3b-instruct",
146
-
147
- "Qwen Coder 3B":
148
- "Qwen/Qwen2.5-Coder-3B-Instruct",
149
-
150
- "StarCoder2 3B":
151
- "bigcode/starcoder2-3b",
152
-
153
- "CodeGen 350M":
154
- "Salesforce/codegen-350M-mono",
155
  }
156
 
157
-
158
  # =========================================================
159
  # DATABASE
160
  # =========================================================
161
 
162
  db_lock = threading.RLock()
163
 
164
-
165
  def db_connect():
166
- connection = sqlite3.connect(
167
- str(DB_PATH),
168
- timeout=30,
169
- check_same_thread=False,
170
- )
171
  connection.row_factory = sqlite3.Row
172
  return connection
173
 
174
-
175
  def initialize_database():
176
  with db_lock:
177
  connection = db_connect()
178
-
179
  connection.execute("""
180
  CREATE TABLE IF NOT EXISTS conversations (
181
  id TEXT PRIMARY KEY,
@@ -186,7 +132,6 @@ def initialize_database():
186
  updated TEXT NOT NULL
187
  )
188
  """)
189
-
190
  connection.execute("""
191
  CREATE TABLE IF NOT EXISTS jobs (
192
  id TEXT PRIMARY KEY,
@@ -200,30 +145,23 @@ def initialize_database():
200
  updated TEXT NOT NULL
201
  )
202
  """)
203
-
204
  connection.commit()
205
  connection.close()
206
 
207
-
208
  initialize_database()
209
 
210
-
211
  def now_string():
212
  return datetime.utcnow().isoformat(timespec="seconds")
213
 
214
-
215
  def get_project_dir(conversation_id):
216
  path = PROJECTS_DIR / conversation_id
217
  path.mkdir(parents=True, exist_ok=True)
218
  return path
219
 
220
-
221
  def save_conversation(session_id, conversation_id, title, history):
222
  timestamp = now_string()
223
-
224
  with db_lock:
225
  connection = db_connect()
226
-
227
  connection.execute("""
228
  INSERT INTO conversations
229
  (id, session_id, title, history, created, updated)
@@ -232,444 +170,224 @@ def save_conversation(session_id, conversation_id, title, history):
232
  title=excluded.title,
233
  history=excluded.history,
234
  updated=excluded.updated
235
- """, (
236
- conversation_id,
237
- session_id,
238
- title,
239
- json.dumps(history, ensure_ascii=False),
240
- timestamp,
241
- timestamp,
242
- ))
243
-
244
  connection.commit()
245
  connection.close()
246
 
247
-
248
  def get_conversations(session_id):
249
  with db_lock:
250
  connection = db_connect()
251
-
252
  rows = connection.execute("""
253
- SELECT id, title, updated
254
- FROM conversations
255
- WHERE session_id=?
256
- ORDER BY updated DESC
257
  """, (session_id,)).fetchall()
258
-
259
  connection.close()
260
-
261
- return [
262
- (f"{row['title']} Β· {row['updated']}", row["id"])
263
- for row in rows
264
- ]
265
-
266
 
267
  def get_conversation(session_id, conversation_id):
268
  with db_lock:
269
  connection = db_connect()
270
-
271
  row = connection.execute("""
272
- SELECT *
273
- FROM conversations
274
- WHERE id=? AND session_id=?
275
  """, (conversation_id, session_id)).fetchone()
276
-
277
  connection.close()
278
-
279
  if not row:
280
  return None
281
-
282
- return {
283
- "id": row["id"],
284
- "title": row["title"],
285
- "history": json.loads(row["history"]),
286
- }
287
-
288
 
289
  def delete_conversations(session_id, conversation_ids):
290
  if not conversation_ids:
291
  return
292
-
293
  with db_lock:
294
  connection = db_connect()
295
-
296
- for conversation_id in conversation_ids:
297
- connection.execute("""
298
- DELETE FROM conversations
299
- WHERE id=? AND session_id=?
300
- """, (conversation_id, session_id))
301
-
302
- connection.execute("""
303
- DELETE FROM jobs
304
- WHERE conversation_id=? AND session_id=?
305
- """, (conversation_id, session_id))
306
-
307
- project_dir = PROJECTS_DIR / conversation_id
308
-
309
  if project_dir.exists():
310
  shutil.rmtree(project_dir, ignore_errors=True)
311
-
312
  connection.commit()
313
  connection.close()
314
 
315
-
316
  def create_conversation(session_id, title="New Project"):
317
  conversation_id = uuid.uuid4().hex
318
- save_conversation(
319
- session_id,
320
- conversation_id,
321
- title,
322
- [],
323
- )
324
  get_project_dir(conversation_id)
325
  return conversation_id
326
 
327
-
328
- # =========================================================
329
- # JOB DATABASE
330
- # =========================================================
331
-
332
  def update_job(job_id, **values):
333
  if not values:
334
  return
335
-
336
  values["updated"] = now_string()
337
-
338
- assignments = ", ".join(
339
- f"{key}=?" for key in values
340
- )
341
-
342
  parameters = list(values.values()) + [job_id]
343
-
344
  with db_lock:
345
  connection = db_connect()
346
- connection.execute(
347
- f"UPDATE jobs SET {assignments} WHERE id=?",
348
- parameters,
349
- )
350
  connection.commit()
351
  connection.close()
352
 
353
-
354
  def create_job(session_id, conversation_id, prompt):
355
  job_id = uuid.uuid4().hex
356
  timestamp = now_string()
357
-
358
  with db_lock:
359
  connection = db_connect()
360
-
361
  connection.execute("""
362
- INSERT INTO jobs (
363
- id, session_id, conversation_id,
364
- status, prompt, response, error,
365
- created, updated
366
- )
367
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
368
- """, (
369
- job_id,
370
- session_id,
371
- conversation_id,
372
- "queued",
373
- prompt,
374
- "",
375
- None,
376
- timestamp,
377
- timestamp,
378
- ))
379
-
380
  connection.commit()
381
  connection.close()
382
-
383
  return job_id
384
 
385
-
386
  def get_job(job_id, session_id):
387
  with db_lock:
388
  connection = db_connect()
389
-
390
- row = connection.execute("""
391
- SELECT *
392
- FROM jobs
393
- WHERE id=? AND session_id=?
394
- """, (job_id, session_id)).fetchone()
395
-
396
  connection.close()
397
-
398
  return dict(row) if row else None
399
 
400
-
401
  def get_active_job(session_id, conversation_id):
402
  with db_lock:
403
  connection = db_connect()
404
-
405
  row = connection.execute("""
406
- SELECT *
407
- FROM jobs
408
- WHERE session_id=?
409
- AND conversation_id=?
410
- AND status IN ('queued', 'running')
411
- ORDER BY created DESC
412
- LIMIT 1
413
  """, (session_id, conversation_id)).fetchone()
414
-
415
  connection.close()
416
-
417
  return dict(row) if row else None
418
 
419
-
420
  # =========================================================
421
  # MODEL CACHE
422
  # =========================================================
423
 
424
- image_cache = {
425
- "name": None,
426
- "pipe": None,
427
- }
428
-
429
- code_cache = {
430
- "name": None,
431
- "tokenizer": None,
432
- "model": None,
433
- }
434
-
435
  image_lock = threading.RLock()
436
  code_lock = threading.RLock()
437
-
438
  job_threads = {}
439
  job_threads_lock = threading.RLock()
440
  job_stop_events = {}
441
 
442
-
443
  def clear_image_cache():
444
  old_pipe = image_cache["pipe"]
445
-
446
  image_cache["pipe"] = None
447
  image_cache["name"] = None
448
-
449
  if old_pipe is not None:
450
  del old_pipe
451
-
452
  gc.collect()
453
-
454
  if torch.cuda.is_available():
455
  torch.cuda.empty_cache()
456
 
457
-
458
  def clear_code_cache():
459
  old_model = code_cache["model"]
460
  old_tokenizer = code_cache["tokenizer"]
461
-
462
  code_cache["model"] = None
463
  code_cache["tokenizer"] = None
464
  code_cache["name"] = None
465
-
466
  if old_model is not None:
467
  del old_model
468
-
469
  if old_tokenizer is not None:
470
  del old_tokenizer
471
-
472
  gc.collect()
473
 
474
-
475
- # =========================================================
476
- # IMAGE PIPELINE
477
- # =========================================================
478
-
479
  def load_image_pipeline(model_id, mode):
480
  cache_key = f"{mode}:{model_id}"
481
-
482
  with image_lock:
483
- if (
484
- image_cache["name"] == cache_key
485
- and image_cache["pipe"] is not None
486
- ):
487
  return image_cache["pipe"]
488
-
489
  clear_image_cache()
490
-
491
  if mode == "text":
492
- pipe = DiffusionPipeline.from_pretrained(
493
- model_id,
494
- torch_dtype=IMAGE_DTYPE,
495
- token=False,
496
- )
497
-
498
  elif mode == "image":
499
- pipe = AutoPipelineForImage2Image.from_pretrained(
500
- model_id,
501
- torch_dtype=IMAGE_DTYPE,
502
- token=False,
503
- )
504
-
505
  else:
506
  raise ValueError("Invalid image mode.")
507
-
508
  pipe = pipe.to("cuda")
509
-
510
  if hasattr(pipe, "enable_attention_slicing"):
511
  pipe.enable_attention_slicing()
512
-
513
  image_cache["pipe"] = pipe
514
  image_cache["name"] = cache_key
515
-
516
  return pipe
517
 
518
-
519
- # =========================================================
520
- # TEXT TO IMAGE
521
- # =========================================================
522
-
523
  @spaces.GPU(duration=120)
524
- def generate_image(
525
- prompt,
526
- negative_prompt,
527
- model_name,
528
- width,
529
- height,
530
- steps,
531
- seed,
532
- random_seed,
533
- ):
534
  if not prompt or not prompt.strip():
535
  raise gr.Error("Enter an image prompt.")
536
-
537
  if model_name not in IMAGE_MODELS:
538
  raise gr.Error("Invalid image model.")
539
-
540
  config = IMAGE_MODELS[model_name]
541
-
542
  if random_seed:
543
  seed = random.randint(0, 2147483647)
544
-
545
  seed = int(seed or 0)
546
-
547
- width = max(256, min(int(width), 768))
548
- height = max(256, min(int(height), 768))
549
-
550
- width = (width // 8) * 8
551
- height = (height // 8) * 8
552
-
553
- actual_steps = min(
554
- max(int(steps), 1),
555
- config["max_steps"],
556
- )
557
-
558
  if model_name in ["SDXL Turbo", "SD Turbo"]:
559
  actual_steps = min(actual_steps, 4)
560
-
561
  try:
562
  with image_lock:
563
- pipe = load_image_pipeline(
564
- config["id"],
565
- "text",
566
- )
567
-
568
- generator = torch.Generator(
569
- device="cuda"
570
- ).manual_seed(seed)
571
-
572
  result = pipe(
573
  prompt=prompt.strip(),
574
  negative_prompt=negative_prompt or None,
575
- width=width,
576
- height=height,
577
  num_inference_steps=actual_steps,
578
  guidance_scale=config["guidance"],
579
  generator=generator,
580
  )
581
-
582
  return result.images[0], seed
583
-
584
  except Exception as error:
585
  traceback.print_exc()
586
  raise gr.Error(f"Image generation failed: {error}")
587
 
588
-
589
- # =========================================================
590
- # IMAGE TO IMAGE
591
- # =========================================================
592
-
593
  @spaces.GPU(duration=120)
594
- def generate_image_to_image(
595
- input_image,
596
- prompt,
597
- negative_prompt,
598
- model_name,
599
- strength,
600
- steps,
601
- guidance,
602
- seed,
603
- random_seed,
604
- ):
605
  if input_image is None:
606
  raise gr.Error("Upload an image.")
607
-
608
  if not prompt or not prompt.strip():
609
  raise gr.Error("Enter transformation prompt.")
610
-
611
  if model_name not in IMAGE_TO_IMAGE_MODELS:
612
  raise gr.Error("Invalid image model.")
613
-
614
  if random_seed:
615
  seed = random.randint(0, 2147483647)
616
-
617
  seed = int(seed or 0)
618
-
619
  strength = max(0.05, min(float(strength), 0.95))
620
  steps = max(1, min(int(steps), 30))
621
-
622
  try:
623
  image = input_image.convert("RGB")
624
  image.thumbnail((768, 768), Image.Resampling.LANCZOS)
625
-
626
  width = max(256, (image.width // 8) * 8)
627
  height = max(256, (image.height // 8) * 8)
628
-
629
- image = image.resize(
630
- (width, height),
631
- Image.Resampling.LANCZOS,
632
- )
633
-
634
  model_id = IMAGE_TO_IMAGE_MODELS[model_name]
635
-
636
  with image_lock:
637
  pipe = load_image_pipeline(model_id, "image")
638
-
639
- generator = torch.Generator(
640
- device="cuda"
641
- ).manual_seed(seed)
642
-
643
  result = pipe(
644
- prompt=prompt.strip(),
645
- image=image,
646
  negative_prompt=negative_prompt or None,
647
- strength=strength,
648
- num_inference_steps=steps,
649
- guidance_scale=float(guidance),
650
- generator=generator,
651
  )
652
-
653
  return result.images[0], seed
654
-
655
  except Exception as error:
656
  traceback.print_exc()
657
  raise gr.Error(f"Image-to-image failed: {error}")
658
 
659
-
660
  # =========================================================
661
- # CODING SYSTEM PROMPT
662
  # =========================================================
663
 
664
  SYSTEM_PROMPT = """
665
  You are ARISE AI, a professional software engineering assistant.
666
 
667
- You specialize in:
668
- Python, Kotlin, Java, Android, Gradle, AAPT2,
669
- JavaScript, TypeScript, HTML, CSS, React,
670
- APIs, databases, Hugging Face, Gradio,
671
- PyTorch, Diffusers, Transformers, debugging,
672
- software architecture and code optimization.
673
 
674
  RULES:
675
  1. Understand the complete user request.
@@ -686,7 +404,6 @@ RULES:
686
  12. Do not invent file contents that were not provided.
687
 
688
  PROJECT FILE EDITING FORMAT:
689
-
690
  When modifying project files, return every complete modified or new file
691
  using exactly this format:
692
 
@@ -703,499 +420,235 @@ Do not put explanatory text inside a file block.
703
  When no file changes are needed, explain the answer normally.
704
  """
705
 
706
-
707
- # =========================================================
708
- # LOAD CODING MODEL
709
- # =========================================================
710
-
711
  def load_code_model(model_name):
712
  if model_name not in CODE_MODELS:
713
  raise ValueError("Invalid coding model.")
714
-
715
  model_id = CODE_MODELS[model_name]
716
-
717
  with code_lock:
718
- if (
719
- code_cache["name"] == model_id
720
- and code_cache["model"] is not None
721
- ):
722
- return (
723
- code_cache["tokenizer"],
724
- code_cache["model"],
725
- )
726
-
727
  clear_code_cache()
728
-
729
- tokenizer = AutoTokenizer.from_pretrained(
730
- model_id,
731
- token=False,
732
- )
733
-
734
  model = AutoModelForCausalLM.from_pretrained(
735
- model_id,
736
- token=False,
737
- torch_dtype=torch.float32,
738
- low_cpu_mem_usage=True,
739
  )
740
-
741
  model.to("cpu")
742
  model.eval()
743
-
744
  code_cache["name"] = model_id
745
  code_cache["tokenizer"] = tokenizer
746
  code_cache["model"] = model
747
-
748
  return tokenizer, model
749
 
750
-
751
  # =========================================================
752
- # SAFE FILE HELPERS
753
  # =========================================================
754
 
755
  def safe_relative_path(value):
756
  value = str(value).replace("\\", "/").strip()
757
  path = Path(value)
758
-
759
- if (
760
- not value
761
- or path.is_absolute()
762
- or ".." in path.parts
763
- or "\x00" in value
764
- ):
765
  raise ValueError("Unsafe project file path.")
766
-
767
  return path
768
 
769
-
770
  def is_text_file(path):
771
- return (
772
- path.suffix.lower() in SUPPORTED_TEXT_EXTENSIONS
773
- or path.name.lower() in {
774
- "dockerfile", "makefile", ".gitignore"
775
- }
776
- )
777
-
778
 
779
  def project_files(project_dir):
780
  result = []
781
-
782
  for root, dirs, files in os.walk(project_dir):
783
- dirs[:] = [
784
- name for name in dirs
785
- if name not in EXCLUDED_DIRS
786
- ]
787
-
788
  for filename in files:
789
  full_path = Path(root) / filename
790
-
791
  if full_path.name == "project_index.json":
792
  continue
793
-
794
  try:
795
  relative = full_path.relative_to(project_dir)
796
  size = full_path.stat().st_size
797
  except Exception:
798
  continue
799
-
800
- result.append({
801
- "path": relative.as_posix(),
802
- "size": size,
803
- "text": is_text_file(full_path),
804
- })
805
-
806
  return result
807
 
808
-
809
  def build_project_context(project_dir):
810
  files = project_files(project_dir)
811
-
812
- output = [
813
- "PROJECT STRUCTURE:",
814
- json.dumps(files, ensure_ascii=False, indent=2),
815
- "",
816
- "PROJECT FILE CONTENTS:",
817
- ]
818
-
819
  total = 0
820
-
821
  for item in files:
822
  if not item["text"]:
823
  continue
824
-
825
  path = project_dir / item["path"]
826
-
827
  try:
828
- content = path.read_text(
829
- encoding="utf-8",
830
- errors="replace",
831
- )
832
  except Exception:
833
  continue
834
-
835
- section = (
836
- f"\n\n===== FILE: {item['path']} =====\n"
837
- f"{content}\n"
838
- f"===== END FILE =====\n"
839
- )
840
-
841
  if total + len(section) > MAX_CONTEXT_SIZE:
842
- output.append(
843
- "\n[Project context truncated due to configured context limit.]"
844
- )
845
  break
846
-
847
  output.append(section)
848
  total += len(section)
849
-
850
  return "\n".join(output), files
851
 
852
-
853
- # =========================================================
854
- # ZIP EXTRACTION
855
- # =========================================================
856
-
857
  def extract_zip_safely(zip_path, destination):
858
  destination = Path(destination)
859
  destination.mkdir(parents=True, exist_ok=True)
860
-
861
  total_size = 0
862
  extracted = 0
863
-
864
  with zipfile.ZipFile(zip_path, "r") as archive:
865
  entries = archive.infolist()
866
-
867
  if len(entries) > MAX_UPLOAD_FILES:
868
  raise ValueError("ZIP contains too many files.")
869
-
870
  for item in entries:
871
  relative = safe_relative_path(item.filename)
872
-
873
  if item.is_dir():
874
  continue
875
-
876
  if item.file_size > MAX_FILE_SIZE:
877
- raise ValueError(
878
- f"File too large in ZIP: {item.filename}"
879
- )
880
-
881
  total_size += item.file_size
882
-
883
  if total_size > MAX_PROJECT_SIZE:
884
  raise ValueError("ZIP project exceeds size limit.")
885
-
886
  target = destination / relative
887
  target.parent.mkdir(parents=True, exist_ok=True)
888
-
889
  with archive.open(item, "r") as source:
890
  with target.open("wb") as output:
891
  shutil.copyfileobj(source, output)
892
-
893
  extracted += 1
894
-
895
  return extracted
896
 
897
-
898
- # =========================================================
899
- # IMAGE OCR
900
- # =========================================================
901
-
902
  def extract_image_text(image_path):
903
  try:
904
  import pytesseract
905
-
906
  image = Image.open(image_path).convert("RGB")
907
  return pytesseract.image_to_string(image).strip()
908
-
909
  except ImportError:
910
- return (
911
- "OCR is not configured. Install pytesseract and the "
912
- "Tesseract system package to extract image text."
913
- )
914
-
915
  except Exception as error:
916
  return f"Image OCR could not run: {error}"
917
 
918
-
919
- # =========================================================
920
- # UPLOAD PROCESSING
921
- # =========================================================
922
-
923
  def process_uploads(uploaded_files, project_dir):
924
  if not uploaded_files:
925
  return "No new files uploaded."
926
-
927
  project_dir = Path(project_dir)
928
  project_dir.mkdir(parents=True, exist_ok=True)
929
-
930
  messages = []
931
-
932
  for uploaded in uploaded_files:
933
- source = Path(
934
- getattr(uploaded, "name", uploaded)
935
- )
936
-
937
  if not source.exists():
938
  continue
939
-
940
  if source.stat().st_size > MAX_FILE_SIZE:
941
- messages.append(
942
- f"Skipped {source.name}: file exceeds upload limit."
943
- )
944
  continue
945
-
946
  if source.suffix.lower() == ".zip":
947
  try:
948
- count = extract_zip_safely(
949
- source,
950
- project_dir,
951
- )
952
- messages.append(
953
- f"Extracted {source.name}: {count} files."
954
- )
955
  except Exception as error:
956
- messages.append(
957
- f"ZIP extraction failed for {source.name}: {error}"
958
- )
959
-
960
- elif source.suffix.lower() in {
961
- ".png", ".jpg", ".jpeg", ".webp", ".bmp"
962
- }:
963
  image_dir = project_dir / "uploaded_images"
964
  image_dir.mkdir(exist_ok=True)
965
-
966
  target = image_dir / source.name
967
  shutil.copy2(source, target)
968
-
969
  extracted_text = extract_image_text(target)
970
-
971
- ocr_path = image_dir / (
972
- source.stem + "_ocr.txt"
973
- )
974
-
975
- ocr_path.write_text(
976
- extracted_text,
977
- encoding="utf-8",
978
- )
979
-
980
- messages.append(
981
- f"Image added: {source.name}. OCR text saved."
982
- )
983
-
984
  else:
985
  target = project_dir / source.name
986
-
987
  if target.exists():
988
- target = project_dir / (
989
- source.stem + "_" + uuid.uuid4().hex[:6]
990
- + source.suffix
991
- )
992
-
993
  shutil.copy2(source, target)
994
  messages.append(f"File added: {target.name}")
995
-
996
- # Save a first-analysis project index.
997
  index_path = project_dir / "project_index.json"
998
-
999
  if not index_path.exists():
1000
  context, files = build_project_context(project_dir)
1001
-
1002
- index_path.write_text(
1003
- json.dumps({
1004
- "first_analysis": now_string(),
1005
- "files": files,
1006
- "analysis_note": (
1007
- "Initial file inventory created. "
1008
- "Detailed code understanding is performed "
1009
- "when the coding model receives the project."
1010
- ),
1011
- }, ensure_ascii=False, indent=2),
1012
- encoding="utf-8",
1013
- )
1014
-
1015
  return "\n".join(messages)
1016
 
1017
-
1018
- # =========================================================
1019
- # APPLY MODEL FILE CHANGES
1020
- # =========================================================
1021
-
1022
  FILE_BLOCK_PATTERN = re.compile(
1023
  r"<<<FILE:\s*(.*?)>>>\s*(.*?)\s*<<<END FILE>>>",
1024
  re.DOTALL | re.IGNORECASE,
1025
  )
1026
 
1027
-
1028
  def apply_file_changes(response, project_dir):
1029
  changed = []
1030
-
1031
  for match in FILE_BLOCK_PATTERN.finditer(response):
1032
  relative_name = match.group(1).strip()
1033
  content = match.group(2)
1034
-
1035
  try:
1036
  relative = safe_relative_path(relative_name)
1037
  except Exception:
1038
  continue
1039
-
1040
  target = Path(project_dir) / relative
1041
  target.parent.mkdir(parents=True, exist_ok=True)
1042
-
1043
- target.write_text(
1044
- content.rstrip() + "\n",
1045
- encoding="utf-8",
1046
- )
1047
-
1048
  changed.append(relative.as_posix())
1049
-
1050
  return changed
1051
 
1052
-
1053
- # =========================================================
1054
- # PROJECT DOWNLOADS
1055
- # =========================================================
1056
-
1057
  def create_project_zip(project_dir):
1058
  project_dir = Path(project_dir)
1059
-
1060
- zip_path = DATA_DIR / (
1061
- "ARISE_Project_" + uuid.uuid4().hex[:10] + ".zip"
1062
- )
1063
-
1064
- with zipfile.ZipFile(
1065
- zip_path,
1066
- "w",
1067
- zipfile.ZIP_DEFLATED,
1068
- ) as archive:
1069
-
1070
  for root, dirs, files in os.walk(project_dir):
1071
- dirs[:] = [
1072
- name for name in dirs
1073
- if name not in EXCLUDED_DIRS
1074
- ]
1075
-
1076
  for filename in files:
1077
  full_path = Path(root) / filename
1078
-
1079
  if full_path == zip_path:
1080
  continue
1081
-
1082
- archive.write(
1083
- full_path,
1084
- full_path.relative_to(project_dir),
1085
- )
1086
-
1087
  return str(zip_path)
1088
 
1089
-
1090
  def create_single_file_download(project_dir, relative_name):
1091
  relative = safe_relative_path(relative_name)
1092
  source = Path(project_dir) / relative
1093
-
1094
  if not source.exists() or not source.is_file():
1095
  return None
1096
-
1097
  download_dir = DATA_DIR / "downloads"
1098
  download_dir.mkdir(exist_ok=True)
1099
-
1100
- destination = download_dir / (
1101
- uuid.uuid4().hex[:8] + "_" + source.name
1102
- )
1103
-
1104
  shutil.copy2(source, destination)
1105
  return str(destination)
1106
 
1107
-
1108
- # =========================================================
1109
- # HTML PREVIEW
1110
- # =========================================================
1111
-
1112
  def make_html_preview(project_dir):
1113
  project_dir = Path(project_dir)
1114
-
1115
- html_files = list(project_dir.rglob("index.html"))
1116
-
1117
- if not html_files:
1118
- html_files = list(project_dir.rglob("*.html"))
1119
-
1120
  if not html_files:
1121
- return (
1122
- "<div style='padding:25px;color:#ddd'>"
1123
- "No HTML file found in this project."
1124
- "</div>"
1125
- )
1126
-
1127
  html_file = html_files[0]
1128
-
1129
  try:
1130
- html = html_file.read_text(
1131
- encoding="utf-8",
1132
- errors="replace",
1133
- )
1134
 
1135
- # Inline local CSS and JavaScript for a basic preview.
1136
  def replace_asset(match):
1137
  asset_name = match.group(1).split("?")[0].split("#")[0]
1138
- asset_path = (
1139
- html_file.parent / asset_name
1140
- ).resolve()
1141
-
1142
  try:
1143
  asset_path.relative_to(project_dir.resolve())
1144
  except ValueError:
1145
  return match.group(0)
1146
-
1147
  if not asset_path.exists():
1148
  return match.group(0)
1149
-
1150
- content = asset_path.read_text(
1151
- encoding="utf-8",
1152
- errors="replace",
1153
- )
1154
-
1155
  if match.group(0).lower().startswith("<link"):
1156
  return "<style>\n" + content + "\n</style>"
1157
-
1158
  return "<script>\n" + content + "\n</script>"
1159
 
1160
- html = re.sub(
1161
- r'<link[^>]+href=["\']([^"\']+\.css)["\'][^>]*>',
1162
- replace_asset,
1163
- html,
1164
- flags=re.IGNORECASE,
1165
- )
1166
-
1167
- html = re.sub(
1168
- r'<script[^>]+src=["\']([^"\']+\.js)["\'][^>]*>\s*</script>',
1169
- replace_asset,
1170
- html,
1171
- flags=re.IGNORECASE,
1172
- )
1173
 
1174
  return f"""
1175
- <iframe
1176
- sandbox="allow-scripts allow-forms"
1177
- style="
1178
- width:100%;
1179
- height:650px;
1180
- border:1px solid #34415e;
1181
- border-radius:14px;
1182
- background:white;
1183
- "
1184
  srcdoc="{html.replace('&', '&amp;').replace('"', '&quot;').replace('<', '&lt;').replace('>', '&gt;')}"
1185
  ></iframe>
1186
  """
1187
-
1188
  except Exception as error:
1189
- return (
1190
- "<div style='padding:20px;color:#ff9999'>"
1191
- f"Preview error: {error}"
1192
- "</div>"
1193
- )
1194
-
1195
-
1196
- # =========================================================
1197
- # STOP CRITERIA
1198
- # =========================================================
1199
 
1200
  class StopCriteria(StoppingCriteria):
1201
  def __init__(self, event):
@@ -1204,103 +657,42 @@ class StopCriteria(StoppingCriteria):
1204
  def __call__(self, input_ids, scores, **kwargs):
1205
  return self.event.is_set()
1206
 
1207
-
1208
  # =========================================================
1209
- # BACKGROUND CODING WORKER
1210
  # =========================================================
1211
 
1212
- def run_coding_worker(
1213
- job_id,
1214
- session_id,
1215
- conversation_id,
1216
- prompt,
1217
- model_name,
1218
- max_tokens,
1219
- temperature,
1220
- stop_event,
1221
- ):
1222
  try:
1223
  update_job(job_id, status="running", response="")
1224
-
1225
  project_dir = get_project_dir(conversation_id)
1226
  project_context, files = build_project_context(project_dir)
1227
-
1228
  tokenizer, model = load_code_model(model_name)
1229
 
1230
- messages = [
1231
- {
1232
- "role": "system",
1233
- "content": SYSTEM_PROMPT,
1234
- },
1235
- ]
1236
-
1237
- conversation = get_conversation(
1238
- session_id,
1239
- conversation_id,
1240
- )
1241
-
1242
- history = (
1243
- conversation["history"]
1244
- if conversation
1245
- else []
1246
- )
1247
 
1248
  for item in history[-MAX_HISTORY_MESSAGES:]:
1249
- if (
1250
- isinstance(item, dict)
1251
- and item.get("role") in ["user", "assistant"]
1252
- and isinstance(item.get("content"), str)
1253
- ):
1254
- messages.append({
1255
- "role": item["role"],
1256
- "content": item["content"],
1257
- })
1258
 
1259
  project_prompt = prompt
1260
-
1261
  if files:
1262
  project_prompt = (
1263
- "PROJECT CONTEXT:\n"
1264
- + project_context
1265
- + "\n\nUSER REQUEST:\n"
1266
- + prompt
1267
- + "\n\n"
1268
- + "Analyze the supplied project before editing. "
1269
- + "Make only the requested changes. "
1270
- + "Return every changed/new file using the required "
1271
- + "<<<FILE: path>>> format."
1272
  )
1273
-
1274
- messages.append({
1275
- "role": "user",
1276
- "content": project_prompt,
1277
- })
1278
 
1279
  if getattr(tokenizer, "chat_template", None):
1280
- formatted_prompt = tokenizer.apply_chat_template(
1281
- messages,
1282
- tokenize=False,
1283
- add_generation_prompt=True,
1284
- )
1285
  else:
1286
- formatted_prompt = "\n\n".join(
1287
- f"{item['role'].upper()}:\n{item['content']}"
1288
- for item in messages
1289
- ) + "\n\nASSISTANT:\n"
1290
-
1291
- inputs = tokenizer(
1292
- formatted_prompt,
1293
- return_tensors="pt",
1294
- truncation=True,
1295
- max_length=MAX_INPUT_LENGTH,
1296
- )
1297
 
1298
- streamer = TextIteratorStreamer(
1299
- tokenizer,
1300
- skip_prompt=True,
1301
- skip_special_tokens=True,
1302
- timeout=120,
1303
- )
1304
 
1305
  generation_kwargs = {
1306
  **inputs,
@@ -1308,18 +700,11 @@ def run_coding_worker(
1308
  "max_new_tokens": max(128, min(int(max_tokens), 2048)),
1309
  "do_sample": float(temperature) > 0.05,
1310
  "temperature": max(float(temperature), 0.05),
1311
- "pad_token_id": (
1312
- tokenizer.pad_token_id
1313
- if tokenizer.pad_token_id is not None
1314
- else tokenizer.eos_token_id
1315
- ),
1316
- "stopping_criteria": StoppingCriteriaList([
1317
- StopCriteria(stop_event)
1318
- ]),
1319
  }
1320
 
1321
  errors = []
1322
-
1323
  def generate():
1324
  try:
1325
  with torch.inference_mode():
@@ -1327,223 +712,101 @@ def run_coding_worker(
1327
  except Exception as error:
1328
  errors.append(str(error))
1329
  traceback.print_exc()
1330
-
1331
  try:
1332
  streamer.end()
1333
  except Exception:
1334
  pass
1335
 
1336
- generation_thread = Thread(
1337
- target=generate,
1338
- daemon=True,
1339
- )
1340
  generation_thread.start()
1341
 
1342
  response = ""
1343
-
1344
  for token in streamer:
1345
  if stop_event.is_set():
1346
  break
1347
-
1348
  response += token
1349
-
1350
- update_job(
1351
- job_id,
1352
- response=response,
1353
- status="running",
1354
- )
1355
 
1356
  generation_thread.join(timeout=15)
1357
-
1358
  if generation_thread.is_alive():
1359
  stop_event.set()
1360
-
1361
  if errors:
1362
  raise RuntimeError(errors[0])
1363
-
1364
  if stop_event.is_set():
1365
- update_job(
1366
- job_id,
1367
- status="stopped",
1368
- response=response + "\n\nGeneration stopped.",
1369
- )
1370
  return
1371
-
1372
  if not response.strip():
1373
  response = "No response generated."
1374
 
1375
- changed_files = apply_file_changes(
1376
- response,
1377
- project_dir,
1378
- )
1379
-
1380
  history = history + [
1381
- {
1382
- "role": "user",
1383
- "content": prompt,
1384
- },
1385
- {
1386
- "role": "assistant",
1387
- "content": response,
1388
- },
1389
  ]
1390
-
1391
- title = prompt.strip().replace("\n", " ")[:55]
1392
- if not title:
1393
- title = "ARISE Project"
1394
-
1395
- save_conversation(
1396
- session_id,
1397
- conversation_id,
1398
- title,
1399
- history,
1400
- )
1401
 
1402
  final_response = response
1403
-
1404
  if changed_files:
1405
  file_status = "\n".join(
1406
- f"- <span style='color:#35d58a'>βœ“</span> `{name}` β€” Edited"
1407
- for name in changed_files
1408
  )
 
1409
 
1410
- final_response += (
1411
- "\n\n---\n### Project File Updates\n"
1412
- + file_status
1413
- )
1414
-
1415
- update_job(
1416
- job_id,
1417
- status="completed",
1418
- response=final_response,
1419
- )
1420
 
1421
  except Exception as error:
1422
  traceback.print_exc()
1423
-
1424
- update_job(
1425
- job_id,
1426
- status="error",
1427
- error=str(error),
1428
- response=f"**Coding error:** {error}",
1429
- )
1430
-
1431
  finally:
1432
  with job_threads_lock:
1433
  job_threads.pop(job_id, None)
1434
  job_stop_events.pop(job_id, None)
1435
 
1436
-
1437
- # =========================================================
1438
- # START / MONITOR CODING JOB
1439
- # =========================================================
1440
-
1441
- def coding_assistant(
1442
- prompt,
1443
- model_name,
1444
- max_tokens,
1445
- temperature,
1446
- uploaded_files,
1447
- conversation_id,
1448
- request: gr.Request,
1449
- ):
1450
  if not prompt or not prompt.strip():
1451
- yield (
1452
- "Please enter your coding request.",
1453
- conversation_id,
1454
- "Waiting for prompt.",
1455
- None,
1456
- None,
1457
- None,
1458
- )
1459
  return
1460
 
1461
  session_id = request.session_hash if request else "default"
1462
 
1463
  if not conversation_id:
1464
- conversation_id = create_conversation(
1465
- session_id,
1466
- prompt.strip().replace("\n", " ")[:55],
1467
- )
1468
 
1469
  project_dir = get_project_dir(conversation_id)
1470
-
1471
  upload_status = ""
1472
-
1473
  if uploaded_files:
1474
  try:
1475
- upload_status = process_uploads(
1476
- uploaded_files,
1477
- project_dir,
1478
- )
1479
  except Exception as error:
1480
- yield (
1481
- f"Upload error: {error}",
1482
- conversation_id,
1483
- "Upload failed.",
1484
- None,
1485
- None,
1486
- None,
1487
- )
1488
  return
1489
 
1490
- job_id = create_job(
1491
- session_id,
1492
- conversation_id,
1493
- prompt.strip(),
1494
- )
1495
-
1496
  stop_event = Event()
1497
-
1498
  with job_threads_lock:
1499
  job_stop_events[job_id] = stop_event
1500
-
1501
  worker = Thread(
1502
  target=run_coding_worker,
1503
- args=(
1504
- job_id,
1505
- session_id,
1506
- conversation_id,
1507
- prompt.strip(),
1508
- model_name,
1509
- max_tokens,
1510
- temperature,
1511
- stop_event,
1512
- ),
1513
  daemon=True,
1514
  )
1515
-
1516
  job_threads[job_id] = worker
1517
  worker.start()
1518
 
1519
- yield (
1520
- "⏳ ARISE AI is analyzing your request...",
1521
- conversation_id,
1522
- upload_status or "Job started.",
1523
- None,
1524
- None,
1525
- job_id,
1526
- )
1527
 
1528
  previous_response = ""
1529
-
1530
  while True:
1531
  job = get_job(job_id, session_id)
1532
-
1533
  if not job:
1534
- yield (
1535
- "Job not found.",
1536
- conversation_id,
1537
- "Job unavailable.",
1538
- None,
1539
- None,
1540
- job_id,
1541
- )
1542
  return
1543
 
1544
  response = job["response"] or ""
1545
  status = job["status"]
1546
-
1547
  status_text = {
1548
  "queued": "⏳ Waiting in queue",
1549
  "running": "βš™οΈ ARISE AI is working",
@@ -1551,368 +814,673 @@ def coding_assistant(
1551
  "stopped": "⏹ Generation stopped",
1552
  "error": "❌ Job failed",
1553
  }.get(status, status)
1554
-
1555
  if upload_status:
1556
  status_text += "\n\n" + upload_status
1557
 
1558
- if response != previous_response or status not in [
1559
- "queued", "running"
1560
- ]:
1561
  previous_response = response
1562
-
1563
  zip_file = None
1564
  single_file = None
1565
- preview = None
1566
-
1567
  if status == "completed":
1568
  zip_file = create_project_zip(project_dir)
1569
-
1570
- changed = apply_file_changes(
1571
- response,
1572
- project_dir,
1573
- )
1574
-
1575
  if changed:
1576
- single_file = create_single_file_download(
1577
- project_dir,
1578
- changed[-1],
1579
- )
1580
-
1581
- preview = make_html_preview(project_dir)
1582
-
1583
- yield (
1584
- response or "No response yet.",
1585
- conversation_id,
1586
- status_text,
1587
- zip_file,
1588
- single_file,
1589
- job_id,
1590
- )
1591
 
1592
  if status not in ["queued", "running"]:
1593
  return
1594
-
1595
  time.sleep(1)
1596
 
1597
-
1598
  def resume_job(job_id, request: gr.Request):
1599
  session_id = request.session_hash if request else "default"
1600
-
1601
  if not job_id:
1602
- yield (
1603
- "No active job selected.",
1604
- "Nothing to resume.",
1605
- None,
1606
- None,
1607
- )
1608
  return
1609
-
1610
  while True:
1611
  job = get_job(job_id, session_id)
1612
-
1613
  if not job:
1614
- yield (
1615
- "Job not found for this session.",
1616
- "Job unavailable.",
1617
- None,
1618
- None,
1619
- )
1620
  return
1621
-
1622
  status = job["status"]
1623
  response = job["response"] or ""
1624
-
1625
- yield (
1626
- response,
1627
- f"Job status: {status}",
1628
- None,
1629
- None,
1630
- )
1631
-
1632
  if status not in ["queued", "running"]:
1633
  return
1634
-
1635
  time.sleep(2)
1636
 
1637
-
1638
  def stop_job(job_id):
1639
  if not job_id:
1640
  return "No active job."
1641
-
1642
  with job_threads_lock:
1643
  event = job_stop_events.get(job_id)
1644
-
1645
  if event:
1646
  event.set()
1647
  return "⏹ Stop requested."
1648
-
1649
  return "No running job found."
1650
 
1651
-
1652
  # =========================================================
1653
- # HISTORY FUNCTIONS
1654
  # =========================================================
1655
 
1656
  def refresh_history(request: gr.Request):
1657
  session_id = request.session_hash if request else "default"
1658
- choices = get_conversations(session_id)
1659
-
1660
- return gr.Dropdown(
1661
- choices=choices,
1662
- value=None,
1663
- )
1664
-
1665
 
1666
  def load_selected_history(conversation_id, request: gr.Request):
1667
  session_id = request.session_hash if request else "default"
1668
-
1669
  if not conversation_id:
1670
- return (
1671
- "",
1672
- None,
1673
- "Select a history item.",
1674
- None,
1675
- )
1676
-
1677
- conversation = get_conversation(
1678
- session_id,
1679
- conversation_id,
1680
- )
1681
-
1682
  if not conversation:
1683
- return (
1684
- "",
1685
- None,
1686
- "History not found.",
1687
- None,
1688
- )
1689
-
1690
- history = conversation["history"]
1691
  display = ""
1692
-
1693
- for item in history:
1694
  role = item.get("role", "assistant").title()
1695
  content = item.get("content", "")
1696
  display += f"\n\n### {role}\n{content}\n"
1697
-
1698
- active_job = get_active_job(
1699
- session_id,
1700
- conversation_id,
1701
- )
1702
-
1703
  job_id = active_job["id"] if active_job else None
1704
-
1705
- return (
1706
- display or "This conversation is empty.",
1707
- conversation_id,
1708
- f"Loaded: {conversation['title']}",
1709
- job_id,
1710
- )
1711
-
1712
 
1713
  def delete_selected_history(conversation_ids, request: gr.Request):
1714
  session_id = request.session_hash if request else "default"
1715
-
1716
- ids = conversation_ids or []
1717
- delete_conversations(session_id, ids)
1718
-
1719
- return (
1720
- gr.Dropdown(choices=get_conversations(session_id), value=None),
1721
- "Selected history deleted.",
1722
- )
1723
-
1724
 
1725
  def clear_current_conversation():
1726
- return (
1727
- "",
1728
- None,
1729
- "Ready for a new conversation.",
1730
- None,
1731
- )
1732
-
1733
-
1734
- # =========================================================
1735
- # HTML PREVIEW REFRESH
1736
- # =========================================================
1737
 
1738
  def preview_project(conversation_id):
1739
  if not conversation_id:
1740
  return "<p>No project selected.</p>"
1741
-
1742
- return make_html_preview(
1743
- get_project_dir(conversation_id)
1744
- )
1745
-
1746
 
1747
  # =========================================================
1748
- # PREMIUM CSS
1749
  # =========================================================
1750
 
1751
  CSS = r"""
1752
- @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap');
1753
 
1754
  :root {
1755
  color-scheme: dark;
 
 
 
 
 
 
 
 
 
 
1756
  }
1757
 
1758
  body {
1759
  background:
1760
- radial-gradient(circle at 15% 10%, rgba(105,64,255,.15), transparent 35%),
1761
- radial-gradient(circle at 90% 80%, rgba(0,205,255,.10), transparent 35%),
1762
- #080b14 !important;
1763
- font-family: Inter, sans-serif !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1764
  }
1765
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1766
  .gradio-container {
1767
  width: 100% !important;
1768
- max-width: 1250px !important;
1769
  margin: auto !important;
1770
  background: transparent !important;
1771
- padding: 12px !important;
 
 
 
1772
  }
1773
 
 
 
 
 
 
 
1774
  #main-header {
1775
  position: relative;
1776
  overflow: hidden;
1777
  text-align: center;
1778
- padding: 38px 16px;
1779
- border: 1px solid rgba(139,92,246,.35);
1780
- border-radius: 22px;
1781
- background: linear-gradient(120deg, rgba(45,26,90,.95), rgba(9,35,57,.95), rgba(30,17,70,.95));
1782
- animation: bannerGlow 5s ease-in-out infinite alternate;
 
 
 
 
 
1783
  }
1784
 
1785
- @keyframes bannerGlow {
1786
- from { box-shadow: 0 0 15px rgba(139,92,246,.15); }
 
 
1787
  to {
1788
- box-shadow: 0 0 38px rgba(6,214,233,.24), 0 0 65px rgba(139,92,246,.17);
1789
  }
1790
  }
1791
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1792
  .hero-title {
1793
- font-size: clamp(29px, 6vw, 56px);
1794
- font-weight: 900;
 
1795
  letter-spacing: -2px;
1796
- background: linear-gradient(90deg,#fff,#b8a5ff,#56e8ff,#fff);
1797
- background-size: 300%;
1798
  -webkit-background-clip: text;
1799
  -webkit-text-fill-color: transparent;
1800
- animation: textGradient 5s linear infinite;
 
 
1801
  }
1802
 
1803
- @keyframes textGradient {
1804
- 0% { background-position: 0%; }
1805
- 100% { background-position: 300%; }
1806
  }
1807
 
1808
  .hero-subtitle {
1809
  color: #bdc7df;
1810
  font-size: 13px;
1811
- letter-spacing: 2px;
1812
- margin-top: 12px;
 
 
1813
  }
1814
 
1815
- #menu-panel {
1816
- border: 1px solid rgba(139,92,246,.35);
1817
- background: rgba(16,22,39,.95);
1818
- border-radius: 14px;
1819
- padding: 12px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1820
  }
1821
 
 
1822
  .gradio-container .tab-nav {
1823
- border: 1px solid rgba(139,92,246,.25);
1824
- border-radius: 15px;
1825
- background: rgba(18,24,40,.8);
1826
- padding: 7px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1827
  }
1828
 
 
1829
  .gradio-container button {
1830
  border-radius: 12px !important;
1831
- transition: all .25s ease !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1832
  }
1833
 
1834
  .gradio-container button:hover {
1835
  transform: translateY(-2px);
1836
- box-shadow: 0 0 20px rgba(139,92,246,.35);
1837
  }
1838
 
1839
  .primary {
1840
- background: linear-gradient(100deg,#7045ed,#168edb) !important;
 
1841
  color: white !important;
1842
- font-weight: 800 !important;
 
 
 
1843
  }
1844
 
1845
- textarea, input {
1846
- border-radius: 12px !important;
 
1847
  }
1848
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1849
  #coding-output {
1850
- min-height: 300px;
1851
- padding: 15px;
1852
- border: 1px solid rgba(6,214,233,.22);
1853
- border-radius: 15px;
1854
- background: rgba(9,15,28,.8);
 
 
1855
  overflow-wrap: anywhere;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1856
  }
1857
 
1858
  #coding-output pre {
1859
  max-width: 100%;
1860
  overflow-x: auto;
 
 
 
 
 
 
 
 
 
 
 
 
 
1861
  }
1862
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1863
  #footer {
1864
  text-align: center;
1865
  color: #8390ad;
1866
- padding: 20px;
 
 
 
1867
  }
1868
 
1869
- @media(max-width:650px) {
1870
- .gradio-container {
1871
- padding: 6px !important;
1872
- }
 
 
 
 
 
 
1873
 
1874
- #main-header {
1875
- padding: 28px 10px;
1876
- border-radius: 16px;
1877
- }
1878
 
1879
- .hero-title {
1880
- font-size: 30px;
1881
- letter-spacing: -1px;
1882
- }
 
1883
 
1884
- .hero-subtitle {
1885
- font-size: 10px;
1886
- letter-spacing: 1px;
1887
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1888
 
 
 
 
 
 
 
1889
  .gradio-container .tab-nav button {
1890
  font-size: 11px !important;
1891
  padding: 8px 5px !important;
1892
  }
1893
-
1894
  #coding-output {
1895
- min-height: 230px;
1896
- padding: 10px;
 
1897
  }
1898
  }
1899
  """
1900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1901
 
1902
  # =========================================================
1903
  # HEADER
1904
  # =========================================================
1905
 
1906
- HEADER = f"""
1907
  <div id="main-header">
1908
  <div style="
1909
- font-size:12px;
1910
- color:#83eaff;
1911
- letter-spacing:3px;
1912
- font-weight:800;
1913
- margin-bottom:12px;
 
1914
  ">
1915
- NEXT GENERATION ARTIFICIAL INTELLIGENCE
1916
  </div>
1917
 
1918
  <div class="hero-title">⚑ ARISE AI STUDIO</div>
@@ -1921,23 +1489,23 @@ HEADER = f"""
1921
  CREATE Β· TRANSFORM Β· CODE Β· INNOVATE
1922
  </div>
1923
 
1924
- <div style="
1925
- display:flex;
1926
- justify-content:center;
1927
- flex-wrap:wrap;
1928
- gap:8px;
1929
- margin-top:22px;
1930
  ">
1931
- <span style="background:#ffffff15;padding:8px 13px;border-radius:30px;color:#d8d5ff;font-size:12px">🎨 AI Art</span>
1932
- <span style="background:#ffffff15;padding:8px 13px;border-radius:30px;color:#d8d5ff;font-size:12px">πŸ–Ό Image Transform</span>
1933
- <span style="background:#ffffff15;padding:8px 13px;border-radius:30px;color:#d8d5ff;font-size:12px">πŸ’» AI Coding</span>
 
1934
  </div>
1935
  </div>
1936
  """
1937
 
1938
-
1939
  # =========================================================
1940
- # GRADIO APPLICATION
1941
  # =========================================================
1942
 
1943
  with gr.Blocks(title=APP_NAME) as demo:
@@ -1949,256 +1517,111 @@ with gr.Blocks(title=APP_NAME) as demo:
1949
 
1950
  with gr.Row():
1951
  menu_button = gr.Button("☰ Menu", size="sm")
1952
- gr.Markdown(
1953
- f"[Developer Contact β†—]({DEVELOPER_TELEGRAM})"
1954
- )
1955
 
1956
  with gr.Column(visible=False, elem_id="menu-panel") as menu_panel:
1957
- gr.Markdown("### ARISE AI Studio Menu")
1958
-
1959
- gr.Markdown(
1960
- f"**Developer Contact:** [Telegram @hardhackar009]({DEVELOPER_TELEGRAM})"
1961
- )
1962
-
1963
- gr.Markdown(
1964
- "Open the History tab to load, select or delete saved conversations."
1965
- )
1966
 
1967
- menu_button.click(
1968
- lambda: gr.update(visible=True),
1969
- outputs=menu_panel,
1970
- )
1971
 
1972
- gr.Markdown(
1973
- """
1974
- <div style="text-align:center;color:#9ba9c5;padding:10px">
1975
- Premium AI Workspace Β· Open Models Β· Live Generation
1976
- </div>
1977
- """
1978
- )
1979
 
1980
  with gr.Tabs():
1981
 
1982
- # =================================================
1983
- # TEXT TO IMAGE
1984
- # =================================================
1985
-
1986
  with gr.Tab("🎨 Text to Image"):
1987
-
1988
- gr.Markdown("## Create Images with AI")
1989
 
1990
  image_model = gr.Dropdown(
1991
  choices=list(IMAGE_MODELS.keys()),
1992
  value="SDXL Turbo",
1993
  label="Select Image Model",
1994
  )
1995
-
1996
  image_prompt = gr.Textbox(
1997
  label="Image Prompt",
1998
- placeholder="Describe your image...",
1999
  lines=4,
2000
  )
2001
-
2002
- negative_prompt = gr.Textbox(
2003
- label="Negative Prompt",
2004
- lines=2,
2005
- )
2006
 
2007
  with gr.Row():
2008
- width = gr.Slider(
2009
- 256, 768,
2010
- value=512,
2011
- step=64,
2012
- label="Image Width",
2013
- )
2014
-
2015
- height = gr.Slider(
2016
- 256, 768,
2017
- value=512,
2018
- step=64,
2019
- label="Image Height",
2020
- )
2021
-
2022
- steps = gr.Slider(
2023
- 1, 30,
2024
- value=4,
2025
- step=1,
2026
- label="Inference Steps",
2027
- )
2028
 
2029
- with gr.Row():
2030
- seed = gr.Number(
2031
- value=0,
2032
- precision=0,
2033
- label="Seed",
2034
- )
2035
-
2036
- random_seed = gr.Checkbox(
2037
- value=True,
2038
- label="Random Seed",
2039
- )
2040
-
2041
- generate_button = gr.Button(
2042
- "✨ Generate Image",
2043
- variant="primary",
2044
- )
2045
 
2046
- image_output = gr.Image(
2047
- label="Generated Artwork",
2048
- type="pil",
2049
- height=400,
2050
- )
2051
 
2052
- seed_output = gr.Number(
2053
- label="Used Seed",
2054
- precision=0,
2055
- )
2056
 
2057
  generate_button.click(
2058
  fn=generate_image,
2059
- inputs=[
2060
- image_prompt,
2061
- negative_prompt,
2062
- image_model,
2063
- width,
2064
- height,
2065
- steps,
2066
- seed,
2067
- random_seed,
2068
- ],
2069
- outputs=[
2070
- image_output,
2071
- seed_output,
2072
- ],
2073
  )
2074
 
2075
- # =================================================
2076
- # IMAGE TO IMAGE
2077
- # =================================================
2078
-
2079
  with gr.Tab("πŸ–Ό Image to Image"):
 
2080
 
2081
- gr.Markdown("## Transform Your Images")
2082
-
2083
- input_image = gr.Image(
2084
- label="Upload Original Image",
2085
- type="pil",
2086
- height=300,
2087
- )
2088
-
2089
  img2img_model = gr.Dropdown(
2090
  choices=list(IMAGE_TO_IMAGE_MODELS.keys()),
2091
  value="Stable Diffusion 1.5 Img2Img",
2092
  label="Image-to-Image Model",
2093
  )
2094
-
2095
- img2img_prompt = gr.Textbox(
2096
- label="Transformation Prompt",
2097
- placeholder="Describe the new image style...",
2098
- lines=4,
2099
- )
2100
-
2101
- img2img_negative = gr.Textbox(
2102
- label="Negative Prompt",
2103
- lines=2,
2104
- )
2105
-
2106
- strength = gr.Slider(
2107
- 0.05, 0.95,
2108
- value=0.70,
2109
- step=0.05,
2110
- label="Transformation Strength",
2111
- )
2112
 
2113
  with gr.Row():
2114
- img2img_steps = gr.Slider(
2115
- 1, 30,
2116
- value=25,
2117
- step=1,
2118
- label="Inference Steps",
2119
- )
2120
-
2121
- img2img_guidance = gr.Slider(
2122
- 1, 15,
2123
- value=7.5,
2124
- step=0.5,
2125
- label="Guidance Scale",
2126
- )
2127
 
2128
  with gr.Row():
2129
- img2img_seed = gr.Number(
2130
- value=0,
2131
- precision=0,
2132
- label="Seed",
2133
- )
2134
-
2135
- img2img_random = gr.Checkbox(
2136
- value=True,
2137
- label="Random Seed",
2138
- )
2139
-
2140
- img2img_button = gr.Button(
2141
- "πŸͺ„ Transform Image",
2142
- variant="primary",
2143
- )
2144
 
2145
- img2img_output = gr.Image(
2146
- label="Transformed Image",
2147
- type="pil",
2148
- height=400,
2149
- )
2150
-
2151
- img2img_seed_output = gr.Number(
2152
- label="Used Seed",
2153
- precision=0,
2154
- )
2155
 
2156
  img2img_button.click(
2157
  fn=generate_image_to_image,
2158
- inputs=[
2159
- input_image,
2160
- img2img_prompt,
2161
- img2img_negative,
2162
- img2img_model,
2163
- strength,
2164
- img2img_steps,
2165
- img2img_guidance,
2166
- img2img_seed,
2167
- img2img_random,
2168
- ],
2169
- outputs=[
2170
- img2img_output,
2171
- img2img_seed_output,
2172
- ],
2173
  )
2174
 
2175
- # =================================================
2176
- # AI CODING
2177
- # =================================================
2178
-
2179
  with gr.Tab("πŸ’» AI Coding"):
2180
-
2181
- gr.Markdown(
2182
- """
2183
- ## ARISE AI Coding Workspace
2184
-
2185
- Upload an existing project, describe your changes,
2186
- and download the updated project.
2187
- """
2188
- )
2189
 
2190
  code_model = gr.Dropdown(
2191
  choices=list(CODE_MODELS.keys()),
2192
  value="Qwen Coder 0.5B",
2193
  label="Select Coding Model",
2194
  )
2195
-
2196
  project_upload = gr.File(
2197
  label="οΌ‹ Upload ZIP, Images or Project Files",
2198
  file_count="multiple",
2199
  type="filepath",
2200
  )
2201
-
2202
  code_prompt = gr.Textbox(
2203
  label="Your Coding Request",
2204
  placeholder="Example: Change the app theme and update the home screen...",
@@ -2206,19 +1629,8 @@ with gr.Blocks(title=APP_NAME) as demo:
2206
  )
2207
 
2208
  with gr.Row():
2209
- max_tokens = gr.Slider(
2210
- 128, 2048,
2211
- value=768,
2212
- step=128,
2213
- label="Maximum Output Tokens",
2214
- )
2215
-
2216
- temperature = gr.Slider(
2217
- 0.1, 1.0,
2218
- value=0.3,
2219
- step=0.1,
2220
- label="Temperature",
2221
- )
2222
 
2223
  coding_output = gr.Markdown(
2224
  value="Ready to work on your project.",
@@ -2226,226 +1638,112 @@ with gr.Blocks(title=APP_NAME) as demo:
2226
  )
2227
 
2228
  with gr.Row():
2229
- generate_code = gr.Button(
2230
- "⚑ Start Coding",
2231
- variant="primary",
2232
- )
2233
 
2234
- stop_button = gr.Button(
2235
- "⏹ Stop",
2236
- variant="stop",
2237
- )
2238
 
2239
- new_project_button = gr.Button(
2240
- "οΌ‹ New Project",
2241
- variant="secondary",
2242
- )
2243
-
2244
- coding_status = gr.Markdown("Ready.")
2245
-
2246
- gr.Markdown("### Project Downloads")
2247
 
2248
  with gr.Row():
2249
- project_zip_download = gr.File(
2250
- label="Download Full Project ZIP",
2251
- interactive=False,
2252
- )
2253
-
2254
- single_file_download = gr.File(
2255
- label="Download Last Edited File",
2256
- interactive=False,
2257
- )
2258
-
2259
- preview_button = gr.Button(
2260
- "🌐 Preview HTML Project",
2261
- )
2262
 
 
2263
  html_preview = gr.HTML(
2264
  value="<div style='padding:15px;color:#aaa'>HTML preview will appear here.</div>"
2265
  )
2266
 
2267
  generate_code.click(
2268
  fn=coding_assistant,
2269
- inputs=[
2270
- code_prompt,
2271
- code_model,
2272
- max_tokens,
2273
- temperature,
2274
- project_upload,
2275
- conversation_state,
2276
- ],
2277
- outputs=[
2278
- coding_output,
2279
- conversation_state,
2280
- coding_status,
2281
- project_zip_download,
2282
- single_file_download,
2283
- job_state,
2284
- ],
2285
  )
2286
-
2287
- stop_button.click(
2288
- fn=stop_job,
2289
- inputs=job_state,
2290
- outputs=coding_status,
2291
- )
2292
-
2293
  new_project_button.click(
2294
  fn=clear_current_conversation,
2295
- outputs=[
2296
- coding_output,
2297
- conversation_state,
2298
- coding_status,
2299
- job_state,
2300
- ],
2301
- )
2302
-
2303
- preview_button.click(
2304
- fn=preview_project,
2305
- inputs=conversation_state,
2306
- outputs=html_preview,
2307
  )
 
2308
 
2309
- # =================================================
2310
- # HISTORY
2311
- # =================================================
2312
-
2313
  with gr.Tab("πŸ“š History"):
 
2314
 
2315
- gr.Markdown("## Saved Conversations and Projects")
2316
-
2317
- history_dropdown = gr.Dropdown(
2318
- choices=[],
2319
- label="Saved History",
2320
- interactive=True,
2321
- )
2322
 
2323
  with gr.Row():
2324
- refresh_history_button = gr.Button(
2325
- "πŸ”„ Refresh History",
2326
- )
2327
-
2328
- load_history_button = gr.Button(
2329
- "πŸ“‚ Open Selected",
2330
- variant="primary",
2331
- )
2332
-
2333
- history_output = gr.Markdown(
2334
- "Select a saved conversation."
2335
- )
2336
 
 
2337
  history_status = gr.Markdown("")
2338
-
2339
- resume_button = gr.Button(
2340
- "β–Ά Resume Selected Job",
2341
- )
2342
 
2343
  with gr.Row():
2344
- delete_history_button = gr.Button(
2345
- "πŸ—‘ Delete Selected",
2346
- variant="stop",
2347
- )
2348
-
2349
- delete_all_history_button = gr.Button(
2350
- "πŸ—‘ Delete All",
2351
- variant="stop",
2352
- )
2353
-
2354
- refresh_history_button.click(
2355
- fn=refresh_history,
2356
- outputs=history_dropdown,
2357
- )
2358
 
 
2359
  load_history_button.click(
2360
  fn=load_selected_history,
2361
  inputs=history_dropdown,
2362
- outputs=[
2363
- history_output,
2364
- conversation_state,
2365
- history_status,
2366
- job_state,
2367
- ],
2368
  )
2369
-
2370
  delete_history_button.click(
2371
  fn=delete_selected_history,
2372
  inputs=history_dropdown,
2373
- outputs=[
2374
- history_dropdown,
2375
- history_status,
2376
- ],
2377
  )
2378
 
2379
  def delete_all(request: gr.Request):
2380
  session_id = request.session_hash if request else "default"
2381
  choices = get_conversations(session_id)
2382
  ids = [value for _, value in choices]
2383
-
2384
  delete_conversations(session_id, ids)
2385
-
2386
- return (
2387
- gr.Dropdown(choices=[], value=None),
2388
- "All history deleted.",
2389
- )
2390
 
2391
  delete_all_history_button.click(
2392
  fn=delete_all,
2393
- outputs=[
2394
- history_dropdown,
2395
- history_status,
2396
- ],
2397
  )
2398
-
2399
  resume_button.click(
2400
  fn=resume_job,
2401
  inputs=job_state,
2402
- outputs=[
2403
- history_output,
2404
- history_status,
2405
- project_zip_download,
2406
- single_file_download,
2407
- ],
2408
  )
2409
 
2410
- # =====================================================
2411
- # FOOTER
2412
- # =====================================================
2413
-
2414
- gr.HTML(
2415
- f"""
2416
- <div id="footer">
2417
- <div style="
2418
- font-size:19px;
2419
- font-weight:800;
2420
- color:#c7b7ff;
2421
- margin-bottom:8px;
2422
- ">
2423
- ⚑ ARISE AI STUDIO
2424
- </div>
2425
-
2426
- <div>Premium AI Workspace</div>
2427
-
2428
- <div style="margin-top:8px;font-size:12px">
2429
- Developer:
2430
- <a href="{DEVELOPER_TELEGRAM}" target="_blank">
2431
- @hardhackar009
2432
- </a>
2433
- </div>
2434
-
2435
- <div style="margin-top:8px;font-size:11px">
2436
- Powered by Open Source Models and Hugging Face
2437
- </div>
2438
  </div>
2439
- """
2440
- )
 
 
 
 
 
 
 
 
 
2441
 
 
 
2442
 
2443
  # =========================================================
2444
  # LAUNCH
2445
  # =========================================================
2446
 
2447
  if __name__ == "__main__":
2448
-
2449
  demo.queue(
2450
  default_concurrency_limit=1,
2451
  max_size=20,
@@ -2458,4 +1756,4 @@ if __name__ == "__main__":
2458
  css=CSS,
2459
  show_error=True,
2460
  share=False,
2461
- )
 
 
1
  import os
2
  import gc
3
  import re
 
38
 
39
  from threading import Thread, Event
40
 
 
41
  # =========================================================
42
  # CONFIGURATION
43
  # =========================================================
 
54
 
55
  IMAGE_DTYPE = torch.float16
56
 
 
57
  DATA_DIR = Path(os.getenv("ARISE_DATA_DIR", "/data/arise_ai_studio"))
58
 
59
  try:
 
88
  "dist", ".venv", "venv", ".next",
89
  }
90
 
 
 
 
 
 
91
  IMAGE_MODELS = {
92
+ "SDXL Turbo": {"id": "stabilityai/sdxl-turbo", "steps": 4, "guidance": 0.0, "max_steps": 4},
93
+ "Stable Diffusion 1.5": {"id": "stable-diffusion-v1-5/stable-diffusion-v1-5", "steps": 25, "guidance": 7.5, "max_steps": 30},
94
+ "SD Turbo": {"id": "stabilityai/sd-turbo", "steps": 4, "guidance": 0.0, "max_steps": 4},
95
+ "Tiny SD": {"id": "segmind/tiny-sd", "steps": 20, "guidance": 7.5, "max_steps": 30},
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  }
97
 
 
98
  IMAGE_TO_IMAGE_MODELS = {
99
+ "Stable Diffusion 1.5 Img2Img": "stable-diffusion-v1-5/stable-diffusion-v1-5",
 
100
  }
101
 
 
 
 
 
 
102
  CODE_MODELS = {
103
+ "Qwen Coder 0.5B": "Qwen/Qwen2.5-Coder-0.5B-Instruct",
104
+ "Qwen Coder 1.5B": "Qwen/Qwen2.5-Coder-1.5B-Instruct",
105
+ "DeepSeek Coder 1.3B": "deepseek-ai/deepseek-coder-1.3b-instruct",
106
+ "Qwen Coder 3B": "Qwen/Qwen2.5-Coder-3B-Instruct",
107
+ "StarCoder2 3B": "bigcode/starcoder2-3b",
108
+ "CodeGen 350M": "Salesforce/codegen-350M-mono",
 
 
 
 
 
 
 
 
 
 
 
109
  }
110
 
 
111
  # =========================================================
112
  # DATABASE
113
  # =========================================================
114
 
115
  db_lock = threading.RLock()
116
 
 
117
  def db_connect():
118
+ connection = sqlite3.connect(str(DB_PATH), timeout=30, check_same_thread=False)
 
 
 
 
119
  connection.row_factory = sqlite3.Row
120
  return connection
121
 
 
122
  def initialize_database():
123
  with db_lock:
124
  connection = db_connect()
 
125
  connection.execute("""
126
  CREATE TABLE IF NOT EXISTS conversations (
127
  id TEXT PRIMARY KEY,
 
132
  updated TEXT NOT NULL
133
  )
134
  """)
 
135
  connection.execute("""
136
  CREATE TABLE IF NOT EXISTS jobs (
137
  id TEXT PRIMARY KEY,
 
145
  updated TEXT NOT NULL
146
  )
147
  """)
 
148
  connection.commit()
149
  connection.close()
150
 
 
151
  initialize_database()
152
 
 
153
  def now_string():
154
  return datetime.utcnow().isoformat(timespec="seconds")
155
 
 
156
  def get_project_dir(conversation_id):
157
  path = PROJECTS_DIR / conversation_id
158
  path.mkdir(parents=True, exist_ok=True)
159
  return path
160
 
 
161
  def save_conversation(session_id, conversation_id, title, history):
162
  timestamp = now_string()
 
163
  with db_lock:
164
  connection = db_connect()
 
165
  connection.execute("""
166
  INSERT INTO conversations
167
  (id, session_id, title, history, created, updated)
 
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
 
 
213
  def create_conversation(session_id, title="New Project"):
214
  conversation_id = uuid.uuid4().hex
215
+ save_conversation(session_id, conversation_id, title, [])
 
 
 
 
 
216
  get_project_dir(conversation_id)
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]
 
225
  with db_lock:
226
  connection = db_connect()
227
+ connection.execute(f"UPDATE jobs SET {assignments} WHERE id=?", parameters)
 
 
 
228
  connection.commit()
229
  connection.close()
230
 
 
231
  def create_job(session_id, conversation_id, prompt):
232
  job_id = uuid.uuid4().hex
233
  timestamp = now_string()
 
234
  with db_lock:
235
  connection = db_connect()
 
236
  connection.execute("""
237
+ INSERT INTO jobs (id, session_id, conversation_id, status, prompt, response, error, created, updated)
 
 
 
 
238
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
239
+ """, (job_id, session_id, conversation_id, "queued", prompt, "", None, timestamp, timestamp))
 
 
 
 
 
 
 
 
 
 
 
240
  connection.commit()
241
  connection.close()
 
242
  return job_id
243
 
 
244
  def get_job(job_id, session_id):
245
  with db_lock:
246
  connection = db_connect()
247
+ row = connection.execute("SELECT * FROM jobs WHERE id=? AND session_id=?", (job_id, session_id)).fetchone()
 
 
 
 
 
 
248
  connection.close()
 
249
  return dict(row) if row else None
250
 
 
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.
 
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
 
 
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 = []
 
459
  for root, dirs, files in os.walk(project_dir):
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):
474
  files = project_files(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
  def extract_zip_safely(zip_path, destination):
494
  destination = Path(destination)
495
  destination.mkdir(parents=True, exist_ok=True)
 
496
  total_size = 0
497
  extracted = 0
 
498
  with zipfile.ZipFile(zip_path, "r") as archive:
499
  entries = archive.infolist()
 
500
  if len(entries) > MAX_UPLOAD_FILES:
501
  raise ValueError("ZIP contains too many files.")
 
502
  for item in entries:
503
  relative = safe_relative_path(item.filename)
 
504
  if item.is_dir():
505
  continue
 
506
  if item.file_size > MAX_FILE_SIZE:
507
+ raise ValueError(f"File too large in ZIP: {item.filename}")
 
 
 
508
  total_size += item.file_size
 
509
  if total_size > MAX_PROJECT_SIZE:
510
  raise ValueError("ZIP project exceeds size limit.")
 
511
  target = destination / relative
512
  target.parent.mkdir(parents=True, exist_ok=True)
 
513
  with archive.open(item, "r") as source:
514
  with target.open("wb") as output:
515
  shutil.copyfileobj(source, output)
 
516
  extracted += 1
 
517
  return extracted
518
 
 
 
 
 
 
519
  def extract_image_text(image_path):
520
  try:
521
  import pytesseract
 
522
  image = Image.open(image_path).convert("RGB")
523
  return pytesseract.image_to_string(image).strip()
 
524
  except ImportError:
525
+ return "OCR is not configured. Install pytesseract and the Tesseract system package to extract image text."
 
 
 
 
526
  except Exception as error:
527
  return f"Image OCR could not run: {error}"
528
 
 
 
 
 
 
529
  def process_uploads(uploaded_files, project_dir):
530
  if not uploaded_files:
531
  return "No new files uploaded."
 
532
  project_dir = Path(project_dir)
533
  project_dir.mkdir(parents=True, exist_ok=True)
 
534
  messages = []
 
535
  for uploaded in uploaded_files:
536
+ source = Path(getattr(uploaded, "name", uploaded))
 
 
 
537
  if not source.exists():
538
  continue
 
539
  if source.stat().st_size > MAX_FILE_SIZE:
540
+ messages.append(f"Skipped {source.name}: file exceeds upload limit.")
 
 
541
  continue
 
542
  if source.suffix.lower() == ".zip":
543
  try:
544
+ count = extract_zip_safely(source, project_dir)
545
+ messages.append(f"Extracted {source.name}: {count} files.")
 
 
 
 
 
546
  except Exception as error:
547
+ messages.append(f"ZIP extraction failed for {source.name}: {error}")
548
+ elif source.suffix.lower() in {".png", ".jpg", ".jpeg", ".webp", ".bmp"}:
 
 
 
 
 
549
  image_dir = project_dir / "uploaded_images"
550
  image_dir.mkdir(exist_ok=True)
 
551
  target = image_dir / source.name
552
  shutil.copy2(source, target)
 
553
  extracted_text = extract_image_text(target)
554
+ ocr_path = image_dir / (source.stem + "_ocr.txt")
555
+ ocr_path.write_text(extracted_text, encoding="utf-8")
556
+ messages.append(f"Image added: {source.name}. OCR text saved.")
 
 
 
 
 
 
 
 
 
 
 
557
  else:
558
  target = project_dir / source.name
 
559
  if target.exists():
560
+ target = project_dir / (source.stem + "_" + uuid.uuid4().hex[:6] + source.suffix)
 
 
 
 
561
  shutil.copy2(source, target)
562
  messages.append(f"File added: {target.name}")
 
 
563
  index_path = project_dir / "project_index.json"
 
564
  if not index_path.exists():
565
  context, files = build_project_context(project_dir)
566
+ index_path.write_text(json.dumps({
567
+ "first_analysis": now_string(),
568
+ "files": files,
569
+ "analysis_note": "Initial file inventory created.",
570
+ }, ensure_ascii=False, indent=2), encoding="utf-8")
 
 
 
 
 
 
 
 
 
571
  return "\n".join(messages)
572
 
573
+ # FIXED regex β€” was (.?) which captured only 1 char
 
 
 
 
574
  FILE_BLOCK_PATTERN = re.compile(
575
  r"<<<FILE:\s*(.*?)>>>\s*(.*?)\s*<<<END FILE>>>",
576
  re.DOTALL | re.IGNORECASE,
577
  )
578
 
 
579
  def apply_file_changes(response, project_dir):
580
  changed = []
 
581
  for match in FILE_BLOCK_PATTERN.finditer(response):
582
  relative_name = match.group(1).strip()
583
  content = match.group(2)
 
584
  try:
585
  relative = safe_relative_path(relative_name)
586
  except Exception:
587
  continue
 
588
  target = Path(project_dir) / relative
589
  target.parent.mkdir(parents=True, exist_ok=True)
590
+ target.write_text(content.rstrip() + "\n", encoding="utf-8")
 
 
 
 
 
591
  changed.append(relative.as_posix())
 
592
  return changed
593
 
 
 
 
 
 
594
  def create_project_zip(project_dir):
595
  project_dir = Path(project_dir)
596
+ zip_path = DATA_DIR / ("ARISE_Project_" + uuid.uuid4().hex[:10] + ".zip")
597
+ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as archive:
 
 
 
 
 
 
 
 
 
598
  for root, dirs, files in os.walk(project_dir):
599
+ dirs[:] = [name for name in dirs if name not in EXCLUDED_DIRS]
 
 
 
 
600
  for filename in files:
601
  full_path = Path(root) / filename
 
602
  if full_path == zip_path:
603
  continue
604
+ archive.write(full_path, full_path.relative_to(project_dir))
 
 
 
 
 
605
  return str(zip_path)
606
 
 
607
  def create_single_file_download(project_dir, relative_name):
608
  relative = safe_relative_path(relative_name)
609
  source = Path(project_dir) / relative
 
610
  if not source.exists() or not source.is_file():
611
  return None
 
612
  download_dir = DATA_DIR / "downloads"
613
  download_dir.mkdir(exist_ok=True)
614
+ destination = download_dir / (uuid.uuid4().hex[:8] + "_" + source.name)
 
 
 
 
615
  shutil.copy2(source, destination)
616
  return str(destination)
617
 
 
 
 
 
 
618
  def make_html_preview(project_dir):
619
  project_dir = Path(project_dir)
620
+ html_files = list(project_dir.rglob("index.html")) or list(project_dir.rglob("*.html"))
 
 
 
 
 
621
  if not html_files:
622
+ return "<div style='padding:25px;color:#ddd'>No HTML file found in this project.</div>"
 
 
 
 
 
623
  html_file = html_files[0]
 
624
  try:
625
+ html = html_file.read_text(encoding="utf-8", errors="replace")
 
 
 
626
 
 
627
  def replace_asset(match):
628
  asset_name = match.group(1).split("?")[0].split("#")[0]
629
+ asset_path = (html_file.parent / asset_name).resolve()
 
 
 
630
  try:
631
  asset_path.relative_to(project_dir.resolve())
632
  except ValueError:
633
  return match.group(0)
 
634
  if not asset_path.exists():
635
  return match.group(0)
636
+ content = asset_path.read_text(encoding="utf-8", errors="replace")
 
 
 
 
 
637
  if match.group(0).lower().startswith("<link"):
638
  return "<style>\n" + content + "\n</style>"
 
639
  return "<script>\n" + content + "\n</script>"
640
 
641
+ html = re.sub(r'<link[^>]+href=["\']([^"\']+\.css)["\'][^>]*>', replace_asset, html, flags=re.IGNORECASE)
642
+ html = re.sub(r'<script[^>]+src=["\']([^"\']+\.js)["\'][^>]*>\s*</script>', replace_asset, html, flags=re.IGNORECASE)
 
 
 
 
 
 
 
 
 
 
 
643
 
644
  return f"""
645
+ <iframe sandbox="allow-scripts allow-forms"
646
+ style="width:100%;height:650px;border:1px solid #34415e;border-radius:14px;background:white;"
 
 
 
 
 
 
 
647
  srcdoc="{html.replace('&', '&amp;').replace('"', '&quot;').replace('<', '&lt;').replace('>', '&gt;')}"
648
  ></iframe>
649
  """
 
650
  except Exception as error:
651
+ return f"<div style='padding:20px;color:#ff9999'>Preview error: {error}</div>"
 
 
 
 
 
 
 
 
 
652
 
653
  class StopCriteria(StoppingCriteria):
654
  def __init__(self, event):
 
657
  def __call__(self, input_ids, scores, **kwargs):
658
  return self.event.is_set()
659
 
 
660
  # =========================================================
661
+ # CODING WORKER
662
  # =========================================================
663
 
664
+ def run_coding_worker(job_id, session_id, conversation_id, prompt, model_name, max_tokens, temperature, stop_event):
 
 
 
 
 
 
 
 
 
665
  try:
666
  update_job(job_id, status="running", response="")
 
667
  project_dir = get_project_dir(conversation_id)
668
  project_context, files = build_project_context(project_dir)
 
669
  tokenizer, model = load_code_model(model_name)
670
 
671
+ messages = [{"role": "system", "content": SYSTEM_PROMPT}]
672
+ conversation = get_conversation(session_id, conversation_id)
673
+ history = conversation["history"] if conversation else []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
674
 
675
  for item in history[-MAX_HISTORY_MESSAGES:]:
676
+ if (isinstance(item, dict) and item.get("role") in ["user", "assistant"]
677
+ and isinstance(item.get("content"), str)):
678
+ messages.append({"role": item["role"], "content": item["content"]})
 
 
 
 
 
 
679
 
680
  project_prompt = prompt
 
681
  if files:
682
  project_prompt = (
683
+ "PROJECT CONTEXT:\n" + project_context + "\n\nUSER REQUEST:\n" + prompt + "\n\n"
684
+ + "Analyze the supplied project before editing. Make only the requested changes. "
685
+ + "Return every changed/new file using the required <<<FILE: path>>> format."
 
 
 
 
 
 
686
  )
687
+ messages.append({"role": "user", "content": project_prompt})
 
 
 
 
688
 
689
  if getattr(tokenizer, "chat_template", None):
690
+ formatted_prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
 
 
 
 
691
  else:
692
+ formatted_prompt = "\n\n".join(f"{i['role'].upper()}:\n{i['content']}" for i in messages) + "\n\nASSISTANT:\n"
 
 
 
 
 
 
 
 
 
 
693
 
694
+ inputs = tokenizer(formatted_prompt, return_tensors="pt", truncation=True, max_length=MAX_INPUT_LENGTH)
695
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=120)
 
 
 
 
696
 
697
  generation_kwargs = {
698
  **inputs,
 
700
  "max_new_tokens": max(128, min(int(max_tokens), 2048)),
701
  "do_sample": float(temperature) > 0.05,
702
  "temperature": max(float(temperature), 0.05),
703
+ "pad_token_id": tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id,
704
+ "stopping_criteria": StoppingCriteriaList([StopCriteria(stop_event)]),
 
 
 
 
 
 
705
  }
706
 
707
  errors = []
 
708
  def generate():
709
  try:
710
  with torch.inference_mode():
 
712
  except Exception as error:
713
  errors.append(str(error))
714
  traceback.print_exc()
 
715
  try:
716
  streamer.end()
717
  except Exception:
718
  pass
719
 
720
+ generation_thread = Thread(target=generate, daemon=True)
 
 
 
721
  generation_thread.start()
722
 
723
  response = ""
 
724
  for token in streamer:
725
  if stop_event.is_set():
726
  break
 
727
  response += token
728
+ update_job(job_id, response=response, status="running")
 
 
 
 
 
729
 
730
  generation_thread.join(timeout=15)
 
731
  if generation_thread.is_alive():
732
  stop_event.set()
 
733
  if errors:
734
  raise RuntimeError(errors[0])
 
735
  if stop_event.is_set():
736
+ update_job(job_id, status="stopped", response=response + "\n\nGeneration stopped.")
 
 
 
 
737
  return
 
738
  if not response.strip():
739
  response = "No response generated."
740
 
741
+ changed_files = apply_file_changes(response, project_dir)
 
 
 
 
742
  history = history + [
743
+ {"role": "user", "content": prompt},
744
+ {"role": "assistant", "content": response},
 
 
 
 
 
 
745
  ]
746
+ title = prompt.strip().replace("\n", " ")[:55] or "ARISE Project"
747
+ save_conversation(session_id, conversation_id, title, history)
 
 
 
 
 
 
 
 
 
748
 
749
  final_response = response
 
750
  if changed_files:
751
  file_status = "\n".join(
752
+ f"- <span style='color:#35d58a'>βœ“</span> `{name}` β€” Edited" for name in changed_files
 
753
  )
754
+ final_response += "\n\n---\n### Project File Updates\n" + file_status
755
 
756
+ update_job(job_id, status="completed", response=final_response)
 
 
 
 
 
 
 
 
 
757
 
758
  except Exception as error:
759
  traceback.print_exc()
760
+ update_job(job_id, status="error", error=str(error), response=f"**Coding error:** {error}")
 
 
 
 
 
 
 
761
  finally:
762
  with job_threads_lock:
763
  job_threads.pop(job_id, None)
764
  job_stop_events.pop(job_id, None)
765
 
766
+ def coding_assistant(prompt, model_name, max_tokens, temperature, uploaded_files, conversation_id, request: gr.Request):
 
 
 
 
 
 
 
 
 
 
 
 
 
767
  if not prompt or not prompt.strip():
768
+ yield ("Please enter your coding request.", conversation_id, "Waiting for prompt.", None, None, None)
 
 
 
 
 
 
 
769
  return
770
 
771
  session_id = request.session_hash if request else "default"
772
 
773
  if not conversation_id:
774
+ conversation_id = create_conversation(session_id, prompt.strip().replace("\n", " ")[:55])
 
 
 
775
 
776
  project_dir = get_project_dir(conversation_id)
 
777
  upload_status = ""
 
778
  if uploaded_files:
779
  try:
780
+ upload_status = process_uploads(uploaded_files, project_dir)
 
 
 
781
  except Exception as error:
782
+ yield (f"Upload error: {error}", conversation_id, "Upload failed.", None, None, None)
 
 
 
 
 
 
 
783
  return
784
 
785
+ job_id = create_job(session_id, conversation_id, prompt.strip())
 
 
 
 
 
786
  stop_event = Event()
 
787
  with job_threads_lock:
788
  job_stop_events[job_id] = stop_event
 
789
  worker = Thread(
790
  target=run_coding_worker,
791
+ args=(job_id, session_id, conversation_id, prompt.strip(),
792
+ model_name, max_tokens, temperature, stop_event),
 
 
 
 
 
 
 
 
793
  daemon=True,
794
  )
 
795
  job_threads[job_id] = worker
796
  worker.start()
797
 
798
+ yield ("⏳ ARISE AI is analyzing your request...", conversation_id,
799
+ upload_status or "Job started.", None, None, job_id)
 
 
 
 
 
 
800
 
801
  previous_response = ""
 
802
  while True:
803
  job = get_job(job_id, session_id)
 
804
  if not job:
805
+ yield ("Job not found.", conversation_id, "Job unavailable.", None, None, job_id)
 
 
 
 
 
 
 
806
  return
807
 
808
  response = job["response"] or ""
809
  status = job["status"]
 
810
  status_text = {
811
  "queued": "⏳ Waiting in queue",
812
  "running": "βš™οΈ ARISE AI is working",
 
814
  "stopped": "⏹ Generation stopped",
815
  "error": "❌ Job failed",
816
  }.get(status, status)
 
817
  if upload_status:
818
  status_text += "\n\n" + upload_status
819
 
820
+ if response != previous_response or status not in ["queued", "running"]:
 
 
821
  previous_response = response
 
822
  zip_file = None
823
  single_file = None
 
 
824
  if status == "completed":
825
  zip_file = create_project_zip(project_dir)
826
+ changed = apply_file_changes(response, project_dir)
 
 
 
 
 
827
  if changed:
828
+ single_file = create_single_file_download(project_dir, changed[-1])
829
+ yield (response or "No response yet.", conversation_id, status_text,
830
+ zip_file, single_file, job_id)
 
 
 
 
 
 
 
 
 
 
 
 
831
 
832
  if status not in ["queued", "running"]:
833
  return
 
834
  time.sleep(1)
835
 
 
836
  def resume_job(job_id, request: gr.Request):
837
  session_id = request.session_hash if request else "default"
 
838
  if not job_id:
839
+ yield ("No active job selected.", "Nothing to resume.", None, None)
 
 
 
 
 
840
  return
 
841
  while True:
842
  job = get_job(job_id, session_id)
 
843
  if not job:
844
+ yield ("Job not found for this session.", "Job unavailable.", None, None)
 
 
 
 
 
845
  return
 
846
  status = job["status"]
847
  response = job["response"] or ""
848
+ yield (response, f"Job status: {status}", None, None)
 
 
 
 
 
 
 
849
  if status not in ["queued", "running"]:
850
  return
 
851
  time.sleep(2)
852
 
 
853
  def stop_job(job_id):
854
  if not job_id:
855
  return "No active job."
 
856
  with job_threads_lock:
857
  event = job_stop_events.get(job_id)
 
858
  if event:
859
  event.set()
860
  return "⏹ Stop requested."
 
861
  return "No running job found."
862
 
 
863
  # =========================================================
864
+ # HISTORY
865
  # =========================================================
866
 
867
  def refresh_history(request: gr.Request):
868
  session_id = request.session_hash if request else "default"
869
+ return gr.Dropdown(choices=get_conversations(session_id), value=None)
 
 
 
 
 
 
870
 
871
  def load_selected_history(conversation_id, request: gr.Request):
872
  session_id = request.session_hash if request else "default"
 
873
  if not conversation_id:
874
+ return ("", None, "Select a history item.", None)
875
+ conversation = get_conversation(session_id, conversation_id)
 
 
 
 
 
 
 
 
 
 
876
  if not conversation:
877
+ return ("", None, "History not found.", None)
 
 
 
 
 
 
 
878
  display = ""
879
+ for item in conversation["history"]:
 
880
  role = item.get("role", "assistant").title()
881
  content = item.get("content", "")
882
  display += f"\n\n### {role}\n{content}\n"
883
+ active_job = get_active_job(session_id, conversation_id)
 
 
 
 
 
884
  job_id = active_job["id"] if active_job else None
885
+ return (display or "This conversation is empty.", conversation_id,
886
+ f"Loaded: {conversation['title']}", job_id)
 
 
 
 
 
 
887
 
888
  def delete_selected_history(conversation_ids, request: gr.Request):
889
  session_id = request.session_hash if request else "default"
890
+ delete_conversations(session_id, conversation_ids or [])
891
+ return (gr.Dropdown(choices=get_conversations(session_id), value=None), "Selected history deleted.")
 
 
 
 
 
 
 
892
 
893
  def clear_current_conversation():
894
+ return ("", None, "Ready for a new conversation.", None)
 
 
 
 
 
 
 
 
 
 
895
 
896
  def preview_project(conversation_id):
897
  if not conversation_id:
898
  return "<p>No project selected.</p>"
899
+ return make_html_preview(get_project_dir(conversation_id))
 
 
 
 
900
 
901
  # =========================================================
902
+ # PREMIUM CSS β€” GLOW / ANIMATION / NEON AURORA
903
  # =========================================================
904
 
905
  CSS = r"""
906
+ @import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;600&display=swap');
907
 
908
  :root {
909
  color-scheme: dark;
910
+ --arise-violet: #8b5cf6;
911
+ --arise-cyan: #22d3ee;
912
+ --arise-pink: #f472b6;
913
+ --arise-deep: #06080f;
914
+ }
915
+
916
+ * { box-sizing: border-box; }
917
+
918
+ body, .gradio-container {
919
+ font-family: 'Space Grotesk', -apple-system, sans-serif !important;
920
  }
921
 
922
  body {
923
  background:
924
+ radial-gradient(circle at 10% 10%, rgba(139,92,246,0.18), transparent 40%),
925
+ radial-gradient(circle at 90% 20%, rgba(34,211,238,0.14), transparent 40%),
926
+ radial-gradient(circle at 50% 90%, rgba(244,114,182,0.12), transparent 45%),
927
+ #06080f !important;
928
+ min-height: 100vh;
929
+ overflow-x: hidden;
930
+ position: relative;
931
+ }
932
+
933
+ /* === AURORA BACKGROUND === */
934
+ body::before {
935
+ content: '';
936
+ position: fixed;
937
+ top: -50%;
938
+ left: -50%;
939
+ width: 200%;
940
+ height: 200%;
941
+ background:
942
+ conic-gradient(from 0deg at 30% 40%, rgba(139,92,246,0.15), transparent 25%),
943
+ conic-gradient(from 120deg at 70% 60%, rgba(34,211,238,0.12), transparent 25%),
944
+ conic-gradient(from 240deg at 50% 30%, rgba(244,114,182,0.12), transparent 25%);
945
+ animation: auroraRotate 40s linear infinite;
946
+ pointer-events: none;
947
+ z-index: 0;
948
+ filter: blur(80px);
949
+ opacity: 0.7;
950
  }
951
 
952
+ @keyframes auroraRotate {
953
+ from { transform: rotate(0deg); }
954
+ to { transform: rotate(360deg); }
955
+ }
956
+
957
+ /* === FLOATING PARTICLES === */
958
+ body::after {
959
+ content: '';
960
+ position: fixed;
961
+ inset: 0;
962
+ background-image:
963
+ radial-gradient(1.5px 1.5px at 20% 30%, #fff, transparent),
964
+ radial-gradient(1px 1px at 80% 70%, #8b5cf6, transparent),
965
+ radial-gradient(1.5px 1.5px at 40% 80%, #22d3ee, transparent),
966
+ radial-gradient(1px 1px at 60% 20%, #f472b6, transparent),
967
+ radial-gradient(1px 1px at 90% 40%, #fff, transparent),
968
+ radial-gradient(1.5px 1.5px at 10% 60%, #22d3ee, transparent);
969
+ background-size: 300px 300px, 400px 400px, 500px 500px, 350px 350px, 450px 450px, 550px 550px;
970
+ animation: starsFloat 60s linear infinite;
971
+ pointer-events: none;
972
+ z-index: 0;
973
+ opacity: 0.55;
974
+ }
975
+
976
+ @keyframes starsFloat {
977
+ from { background-position: 0 0, 0 0, 0 0, 0 0, 0 0, 0 0; }
978
+ to { background-position: 300px 600px, -400px 400px, 500px -500px, -350px -350px, 450px 450px, -550px 550px; }
979
+ }
980
+
981
+ /* === CONTAINER === */
982
  .gradio-container {
983
  width: 100% !important;
984
+ max-width: 1300px !important;
985
  margin: auto !important;
986
  background: transparent !important;
987
+ padding: 14px !important;
988
+ position: relative;
989
+ z-index: 1;
990
+ animation: fadeBoot 1s ease-out;
991
  }
992
 
993
+ @keyframes fadeBoot {
994
+ from { opacity: 0; transform: translateY(20px); }
995
+ to { opacity: 1; transform: translateY(0); }
996
+ }
997
+
998
+ /* === HEADER BANNER === */
999
  #main-header {
1000
  position: relative;
1001
  overflow: hidden;
1002
  text-align: center;
1003
+ padding: 46px 20px;
1004
+ border: 1px solid rgba(139,92,246,0.4);
1005
+ border-radius: 26px;
1006
+ background:
1007
+ linear-gradient(135deg, rgba(45,26,90,0.95) 0%, rgba(9,35,57,0.95) 50%, rgba(30,17,70,0.95) 100%);
1008
+ box-shadow:
1009
+ 0 0 40px rgba(139,92,246,0.25),
1010
+ 0 0 80px rgba(34,211,238,0.12),
1011
+ inset 0 1px 0 rgba(255,255,255,0.08);
1012
+ animation: bannerPulse 4s ease-in-out infinite alternate;
1013
  }
1014
 
1015
+ @keyframes bannerPulse {
1016
+ from {
1017
+ 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);
1018
+ }
1019
  to {
1020
+ 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);
1021
  }
1022
  }
1023
 
1024
+ #main-header::before {
1025
+ content: '';
1026
+ position: absolute;
1027
+ inset: -2px;
1028
+ border-radius: 26px;
1029
+ padding: 2px;
1030
+ background: linear-gradient(135deg, #8b5cf6, #22d3ee, #f472b6, #8b5cf6);
1031
+ background-size: 300% 300%;
1032
+ -webkit-mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0);
1033
+ -webkit-mask-composite: xor;
1034
+ mask-composite: exclude;
1035
+ animation: borderFlow 6s linear infinite;
1036
+ pointer-events: none;
1037
+ }
1038
+
1039
+ @keyframes borderFlow {
1040
+ 0% { background-position: 0% 50%; }
1041
+ 100% { background-position: 300% 50%; }
1042
+ }
1043
+
1044
  .hero-title {
1045
+ font-family: 'Space Grotesk', sans-serif;
1046
+ font-size: clamp(32px, 6vw, 62px);
1047
+ font-weight: 800;
1048
  letter-spacing: -2px;
1049
+ background: linear-gradient(90deg, #fff 0%, #b8a5ff 25%, #56e8ff 50%, #f472b6 75%, #fff 100%);
1050
+ background-size: 300% auto;
1051
  -webkit-background-clip: text;
1052
  -webkit-text-fill-color: transparent;
1053
+ background-clip: text;
1054
+ animation: heroShine 5s linear infinite;
1055
+ text-shadow: 0 0 40px rgba(139,92,246,0.4);
1056
  }
1057
 
1058
+ @keyframes heroShine {
1059
+ 0% { background-position: 0% center; }
1060
+ 100% { background-position: 300% center; }
1061
  }
1062
 
1063
  .hero-subtitle {
1064
  color: #bdc7df;
1065
  font-size: 13px;
1066
+ letter-spacing: 4px;
1067
+ margin-top: 14px;
1068
+ font-weight: 600;
1069
+ text-transform: uppercase;
1070
  }
1071
 
1072
+ .hero-badges span {
1073
+ display: inline-flex;
1074
+ align-items: center;
1075
+ gap: 6px;
1076
+ background: rgba(255,255,255,0.06);
1077
+ backdrop-filter: blur(10px);
1078
+ padding: 8px 16px;
1079
+ border-radius: 30px;
1080
+ color: #d8d5ff;
1081
+ font-size: 12px;
1082
+ font-weight: 500;
1083
+ margin: 4px;
1084
+ border: 1px solid rgba(255,255,255,0.1);
1085
+ transition: all 0.3s ease;
1086
+ }
1087
+
1088
+ .hero-badges span:hover {
1089
+ background: rgba(139,92,246,0.25);
1090
+ border-color: rgba(139,92,246,0.6);
1091
+ box-shadow: 0 0 20px rgba(139,92,246,0.5);
1092
+ transform: translateY(-3px);
1093
  }
1094
 
1095
+ /* === TABS === */
1096
  .gradio-container .tab-nav {
1097
+ border: 1px solid rgba(139,92,246,0.3) !important;
1098
+ border-radius: 18px !important;
1099
+ background: rgba(18,24,40,0.85) !important;
1100
+ backdrop-filter: blur(14px);
1101
+ padding: 8px !important;
1102
+ box-shadow: 0 0 30px rgba(139,92,246,0.1);
1103
+ }
1104
+
1105
+ .gradio-container .tab-nav button {
1106
+ border-radius: 12px !important;
1107
+ transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
1108
+ font-weight: 600 !important;
1109
+ letter-spacing: 0.3px;
1110
+ }
1111
+
1112
+ .gradio-container .tab-nav button:hover {
1113
+ background: rgba(139,92,246,0.15) !important;
1114
+ color: #b8a5ff !important;
1115
+ }
1116
+
1117
+ .gradio-container .tab-nav button.selected {
1118
+ background: linear-gradient(135deg, #7045ed, #168edb) !important;
1119
+ color: #fff !important;
1120
+ box-shadow: 0 0 25px rgba(139,92,246,0.6) !important;
1121
  }
1122
 
1123
+ /* === BUTTONS === */
1124
  .gradio-container button {
1125
  border-radius: 12px !important;
1126
+ transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
1127
+ font-weight: 600 !important;
1128
+ position: relative;
1129
+ overflow: hidden;
1130
+ }
1131
+
1132
+ .gradio-container button::before {
1133
+ content: '';
1134
+ position: absolute;
1135
+ top: 50%;
1136
+ left: 50%;
1137
+ width: 0;
1138
+ height: 0;
1139
+ border-radius: 50%;
1140
+ background: rgba(255,255,255,0.3);
1141
+ transform: translate(-50%, -50%);
1142
+ transition: width 0.6s, height 0.6s;
1143
+ pointer-events: none;
1144
+ }
1145
+
1146
+ .gradio-container button:active::before {
1147
+ width: 300px;
1148
+ height: 300px;
1149
  }
1150
 
1151
  .gradio-container button:hover {
1152
  transform: translateY(-2px);
1153
+ box-shadow: 0 8px 25px rgba(139,92,246,0.4);
1154
  }
1155
 
1156
  .primary {
1157
+ background: linear-gradient(135deg, #7045ed 0%, #a855f7 50%, #168edb 100%) !important;
1158
+ background-size: 200% 200% !important;
1159
  color: white !important;
1160
+ font-weight: 700 !important;
1161
+ letter-spacing: 0.5px;
1162
+ animation: gradientShift 3s ease infinite;
1163
+ box-shadow: 0 4px 20px rgba(139,92,246,0.4) !important;
1164
  }
1165
 
1166
+ @keyframes gradientShift {
1167
+ 0%, 100% { background-position: 0% 50%; }
1168
+ 50% { background-position: 100% 50%; }
1169
  }
1170
 
1171
+ .primary:hover {
1172
+ box-shadow: 0 8px 35px rgba(139,92,246,0.7), 0 0 60px rgba(34,211,238,0.3) !important;
1173
+ }
1174
+
1175
+ .stop-btn, button[variant="stop"] {
1176
+ background: linear-gradient(135deg, #dc2626, #f97316) !important;
1177
+ color: white !important;
1178
+ box-shadow: 0 4px 20px rgba(220,38,38,0.4) !important;
1179
+ }
1180
+
1181
+ .stop-btn:hover, button[variant="stop"]:hover {
1182
+ box-shadow: 0 8px 30px rgba(220,38,38,0.7) !important;
1183
+ }
1184
+
1185
+ /* === INPUTS === */
1186
+ textarea, input[type="text"], input[type="number"], .gr-box {
1187
+ border-radius: 14px !important;
1188
+ background: rgba(15,20,35,0.7) !important;
1189
+ border: 1px solid rgba(139,92,246,0.2) !important;
1190
+ transition: all 0.3s ease !important;
1191
+ backdrop-filter: blur(10px);
1192
+ }
1193
+
1194
+ textarea:focus, input:focus {
1195
+ border-color: rgba(139,92,246,0.7) !important;
1196
+ box-shadow: 0 0 0 3px rgba(139,92,246,0.2), 0 0 30px rgba(139,92,246,0.3) !important;
1197
+ outline: none !important;
1198
+ }
1199
+
1200
+ /* === CODING OUTPUT β€” the star of the show === */
1201
  #coding-output {
1202
+ min-height: 320px;
1203
+ padding: 22px;
1204
+ border: 1px solid rgba(34,211,238,0.3);
1205
+ border-radius: 18px;
1206
+ background:
1207
+ linear-gradient(135deg, rgba(9,15,28,0.92), rgba(18,15,40,0.92));
1208
+ backdrop-filter: blur(16px);
1209
  overflow-wrap: anywhere;
1210
+ position: relative;
1211
+ box-shadow:
1212
+ 0 0 30px rgba(34,211,238,0.15),
1213
+ inset 0 1px 0 rgba(255,255,255,0.05);
1214
+ transition: all 0.4s ease;
1215
+ font-family: 'JetBrains Mono', 'Space Grotesk', monospace;
1216
+ font-size: 14px;
1217
+ line-height: 1.7;
1218
+ }
1219
+
1220
+ #coding-output::before {
1221
+ content: '';
1222
+ position: absolute;
1223
+ top: 0;
1224
+ left: 0;
1225
+ right: 0;
1226
+ height: 2px;
1227
+ background: linear-gradient(90deg, transparent, #22d3ee, #8b5cf6, transparent);
1228
+ border-radius: 18px 18px 0 0;
1229
+ animation: scanline 3s ease-in-out infinite;
1230
+ }
1231
+
1232
+ @keyframes scanline {
1233
+ 0%, 100% { opacity: 0.4; }
1234
+ 50% { opacity: 1; box-shadow: 0 0 15px #22d3ee; }
1235
  }
1236
 
1237
  #coding-output pre {
1238
  max-width: 100%;
1239
  overflow-x: auto;
1240
+ background: rgba(0,0,0,0.5) !important;
1241
+ padding: 14px !important;
1242
+ border-radius: 10px !important;
1243
+ border: 1px solid rgba(139,92,246,0.15);
1244
+ }
1245
+
1246
+ /* Blinking cursor while streaming */
1247
+ #coding-output.streaming::after {
1248
+ content: 'β–‹';
1249
+ color: #22d3ee;
1250
+ animation: cursorBlink 0.8s step-end infinite;
1251
+ margin-left: 2px;
1252
+ text-shadow: 0 0 10px #22d3ee;
1253
  }
1254
 
1255
+ @keyframes cursorBlink {
1256
+ 0%, 50% { opacity: 1; }
1257
+ 51%, 100% { opacity: 0; }
1258
+ }
1259
+
1260
+ /* === STATUS BADGE === */
1261
+ #coding-status {
1262
+ display: inline-block;
1263
+ padding: 8px 16px;
1264
+ border-radius: 20px;
1265
+ background: rgba(34,211,238,0.1);
1266
+ border: 1px solid rgba(34,211,238,0.3);
1267
+ color: #a5f3fc;
1268
+ font-size: 12px;
1269
+ font-weight: 600;
1270
+ letter-spacing: 0.5px;
1271
+ animation: statusPulse 2s ease-in-out infinite;
1272
+ }
1273
+
1274
+ @keyframes statusPulse {
1275
+ 0%, 100% { box-shadow: 0 0 10px rgba(34,211,238,0.3); }
1276
+ 50% { box-shadow: 0 0 25px rgba(34,211,238,0.6); }
1277
+ }
1278
+
1279
+ /* === SCROLLBAR === */
1280
+ ::-webkit-scrollbar {
1281
+ width: 8px;
1282
+ height: 8px;
1283
+ }
1284
+
1285
+ ::-webkit-scrollbar-track {
1286
+ background: rgba(255,255,255,0.03);
1287
+ border-radius: 10px;
1288
+ }
1289
+
1290
+ ::-webkit-scrollbar-thumb {
1291
+ background: linear-gradient(180deg, #8b5cf6, #22d3ee);
1292
+ border-radius: 10px;
1293
+ box-shadow: 0 0 10px rgba(139,92,246,0.5);
1294
+ }
1295
+
1296
+ ::-webkit-scrollbar-thumb:hover {
1297
+ background: linear-gradient(180deg, #a855f7, #67e8f9);
1298
+ }
1299
+
1300
+ /* === MENU PANEL === */
1301
+ #menu-panel {
1302
+ border: 1px solid rgba(139,92,246,0.4);
1303
+ background: rgba(16,22,39,0.92);
1304
+ backdrop-filter: blur(20px);
1305
+ border-radius: 16px;
1306
+ padding: 16px;
1307
+ box-shadow: 0 0 40px rgba(139,92,246,0.2);
1308
+ animation: menuSlide 0.4s ease-out;
1309
+ }
1310
+
1311
+ @keyframes menuSlide {
1312
+ from { opacity: 0; transform: translateY(-10px); }
1313
+ to { opacity: 1; transform: translateY(0); }
1314
+ }
1315
+
1316
+ /* === FOOTER === */
1317
  #footer {
1318
  text-align: center;
1319
  color: #8390ad;
1320
+ padding: 30px 20px;
1321
+ border-top: 1px solid rgba(139,92,246,0.15);
1322
+ margin-top: 30px;
1323
+ position: relative;
1324
  }
1325
 
1326
+ #footer::before {
1327
+ content: '';
1328
+ position: absolute;
1329
+ top: 0;
1330
+ left: 30%;
1331
+ right: 30%;
1332
+ height: 1px;
1333
+ background: linear-gradient(90deg, transparent, #8b5cf6, transparent);
1334
+ animation: footerGlow 3s ease-in-out infinite;
1335
+ }
1336
 
1337
+ @keyframes footerGlow {
1338
+ 0%, 100% { opacity: 0.3; box-shadow: none; }
1339
+ 50% { opacity: 1; box-shadow: 0 0 15px #8b5cf6; }
1340
+ }
1341
 
1342
+ #footer a {
1343
+ color: #a5b4fc;
1344
+ text-decoration: none;
1345
+ transition: all 0.3s;
1346
+ }
1347
 
1348
+ #footer a:hover {
1349
+ color: #67e8f9;
1350
+ text-shadow: 0 0 15px #67e8f9;
1351
+ }
1352
+
1353
+ /* === CARD HOVER EFFECT for blocks === */
1354
+ .gradio-container .block {
1355
+ transition: all 0.3s ease;
1356
+ }
1357
+
1358
+ .gradio-container .block:hover {
1359
+ border-color: rgba(139,92,246,0.4) !important;
1360
+ }
1361
+
1362
+ /* === LOADING SPINNER === */
1363
+ .generating {
1364
+ position: relative;
1365
+ }
1366
+
1367
+ .generating::after {
1368
+ content: '';
1369
+ position: absolute;
1370
+ top: 12px;
1371
+ right: 12px;
1372
+ width: 16px;
1373
+ height: 16px;
1374
+ border: 2px solid rgba(34,211,238,0.3);
1375
+ border-top-color: #22d3ee;
1376
+ border-radius: 50%;
1377
+ animation: spin 0.8s linear infinite;
1378
+ }
1379
+
1380
+ @keyframes spin {
1381
+ to { transform: rotate(360deg); }
1382
+ }
1383
 
1384
+ /* === MOBILE === */
1385
+ @media(max-width: 650px) {
1386
+ .gradio-container { padding: 6px !important; }
1387
+ #main-header { padding: 28px 12px; border-radius: 18px; }
1388
+ .hero-title { font-size: 30px; letter-spacing: -1px; }
1389
+ .hero-subtitle { font-size: 10px; letter-spacing: 2px; }
1390
  .gradio-container .tab-nav button {
1391
  font-size: 11px !important;
1392
  padding: 8px 5px !important;
1393
  }
 
1394
  #coding-output {
1395
+ min-height: 240px;
1396
+ padding: 12px;
1397
+ font-size: 12px;
1398
  }
1399
  }
1400
  """
1401
 
1402
+ # =========================================================
1403
+ # PREMIUM JS β€” TYPING CURSOR + RIPPLE + SMOOTH SCROLL
1404
+ # =========================================================
1405
+
1406
+ PREMIUM_JS = """
1407
+ () => {
1408
+ // Typing cursor effect on streaming output
1409
+ const attachCursor = () => {
1410
+ const output = document.querySelector('#coding-output');
1411
+ if (!output) return;
1412
+ if (output.dataset.cursorAttached) return;
1413
+ output.dataset.cursorAttached = '1';
1414
+
1415
+ let streamTimer = null;
1416
+ const observer = new MutationObserver(() => {
1417
+ output.classList.add('streaming');
1418
+ clearTimeout(streamTimer);
1419
+ streamTimer = setTimeout(() => {
1420
+ output.classList.remove('streaming');
1421
+ }, 1200);
1422
+ });
1423
+ observer.observe(output, { childList: true, subtree: true, characterData: true });
1424
+ };
1425
+
1426
+ // Ripple effect on all buttons
1427
+ const attachRipple = () => {
1428
+ document.querySelectorAll('button').forEach((btn) => {
1429
+ if (btn.dataset.rippleAttached) return;
1430
+ btn.dataset.rippleAttached = '1';
1431
+ btn.style.position = 'relative';
1432
+ btn.style.overflow = 'hidden';
1433
+ });
1434
+ };
1435
+
1436
+ // Smooth auto-scroll for output
1437
+ const attachAutoScroll = () => {
1438
+ const output = document.querySelector('#coding-output');
1439
+ if (!output || output.dataset.scrollAttached) return;
1440
+ output.dataset.scrollAttached = '1';
1441
+ const observer = new MutationObserver(() => {
1442
+ const nearBottom = output.scrollHeight - output.scrollTop - output.clientHeight < 200;
1443
+ if (nearBottom) {
1444
+ output.scrollTop = output.scrollHeight;
1445
+ }
1446
+ });
1447
+ observer.observe(output, { childList: true, subtree: true, characterData: true });
1448
+ };
1449
+
1450
+ // Apply on load
1451
+ attachCursor();
1452
+ attachRipple();
1453
+ attachAutoScroll();
1454
+
1455
+ // Re-apply on Gradio re-renders
1456
+ const globalObserver = new MutationObserver(() => {
1457
+ attachCursor();
1458
+ attachRipple();
1459
+ attachAutoScroll();
1460
+ });
1461
+ globalObserver.observe(document.body, { childList: true, subtree: true });
1462
+
1463
+ // Console signature
1464
+ console.log('%c⚑ ARISE AI STUDIO', 'color:#8b5cf6;font-size:20px;font-weight:bold;text-shadow:0 0 10px #8b5cf6;');
1465
+ console.log('%cPremium AI Workspace Loaded', 'color:#22d3ee;font-size:12px;');
1466
+ }
1467
+ """
1468
 
1469
  # =========================================================
1470
  # HEADER
1471
  # =========================================================
1472
 
1473
+ HEADER = """
1474
  <div id="main-header">
1475
  <div style="
1476
+ font-size: 12px;
1477
+ color: #83eaff;
1478
+ letter-spacing: 4px;
1479
+ font-weight: 800;
1480
+ margin-bottom: 14px;
1481
+ text-shadow: 0 0 20px #22d3ee;
1482
  ">
1483
+ ✦ NEXT GENERATION ARTIFICIAL INTELLIGENCE ✦
1484
  </div>
1485
 
1486
  <div class="hero-title">⚑ ARISE AI STUDIO</div>
 
1489
  CREATE Β· TRANSFORM Β· CODE Β· INNOVATE
1490
  </div>
1491
 
1492
+ <div class="hero-badges" style="
1493
+ display: flex;
1494
+ justify-content: center;
1495
+ flex-wrap: wrap;
1496
+ gap: 10px;
1497
+ margin-top: 24px;
1498
  ">
1499
+ <span>🎨 AI Art</span>
1500
+ <span>πŸ–Ό Image Transform</span>
1501
+ <span>πŸ’» AI Coding</span>
1502
+ <span>⚑ Live Stream</span>
1503
  </div>
1504
  </div>
1505
  """
1506
 
 
1507
  # =========================================================
1508
+ # GRADIO APP
1509
  # =========================================================
1510
 
1511
  with gr.Blocks(title=APP_NAME) as demo:
 
1517
 
1518
  with gr.Row():
1519
  menu_button = gr.Button("☰ Menu", size="sm")
1520
+ gr.Markdown(f"[Developer Contact β†—]({DEVELOPER_TELEGRAM})")
 
 
1521
 
1522
  with gr.Column(visible=False, elem_id="menu-panel") as menu_panel:
1523
+ gr.Markdown("### ⚑ ARISE AI Studio Menu")
1524
+ gr.Markdown(f"**Developer Contact:** [Telegram @hardhackar009]({DEVELOPER_TELEGRAM})")
1525
+ gr.Markdown("Open the **History** tab to load, select or delete saved conversations.")
 
 
 
 
 
 
1526
 
1527
+ menu_button.click(lambda: gr.update(visible=True), outputs=menu_panel)
 
 
 
1528
 
1529
+ gr.Markdown("""
1530
+ <div style="text-align:center;color:#9ba9c5;padding:12px;font-size:13px;letter-spacing:1px">
1531
+ ✦ PREMIUM AI WORKSPACE · OPEN MODELS · LIVE GENERATION ✦
1532
+ </div>
1533
+ """)
 
 
1534
 
1535
  with gr.Tabs():
1536
 
1537
+ # --- TEXT TO IMAGE ---
 
 
 
1538
  with gr.Tab("🎨 Text to Image"):
1539
+ gr.Markdown("## 🎨 Create Images with AI")
 
1540
 
1541
  image_model = gr.Dropdown(
1542
  choices=list(IMAGE_MODELS.keys()),
1543
  value="SDXL Turbo",
1544
  label="Select Image Model",
1545
  )
 
1546
  image_prompt = gr.Textbox(
1547
  label="Image Prompt",
1548
+ placeholder="Describe your image in detail...",
1549
  lines=4,
1550
  )
1551
+ negative_prompt = gr.Textbox(label="Negative Prompt", lines=2)
 
 
 
 
1552
 
1553
  with gr.Row():
1554
+ width = gr.Slider(256, 768, value=512, step=64, label="Image Width")
1555
+ height = gr.Slider(256, 768, value=512, step=64, label="Image Height")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1556
 
1557
+ steps = gr.Slider(1, 30, value=4, step=1, label="Inference Steps")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1558
 
1559
+ with gr.Row():
1560
+ seed = gr.Number(value=0, precision=0, label="Seed")
1561
+ random_seed = gr.Checkbox(value=True, label="Random Seed")
 
 
1562
 
1563
+ generate_button = gr.Button("✨ Generate Image", variant="primary")
1564
+ image_output = gr.Image(label="Generated Artwork", type="pil", height=400)
1565
+ seed_output = gr.Number(label="Used Seed", precision=0)
 
1566
 
1567
  generate_button.click(
1568
  fn=generate_image,
1569
+ inputs=[image_prompt, negative_prompt, image_model, width, height, steps, seed, random_seed],
1570
+ outputs=[image_output, seed_output],
 
 
 
 
 
 
 
 
 
 
 
 
1571
  )
1572
 
1573
+ # --- IMAGE TO IMAGE ---
 
 
 
1574
  with gr.Tab("πŸ–Ό Image to Image"):
1575
+ gr.Markdown("## πŸ–Ό Transform Your Images")
1576
 
1577
+ input_image = gr.Image(label="Upload Original Image", type="pil", height=300)
 
 
 
 
 
 
 
1578
  img2img_model = gr.Dropdown(
1579
  choices=list(IMAGE_TO_IMAGE_MODELS.keys()),
1580
  value="Stable Diffusion 1.5 Img2Img",
1581
  label="Image-to-Image Model",
1582
  )
1583
+ img2img_prompt = gr.Textbox(label="Transformation Prompt",
1584
+ placeholder="Describe the new image style...", lines=4)
1585
+ img2img_negative = gr.Textbox(label="Negative Prompt", lines=2)
1586
+ strength = gr.Slider(0.05, 0.95, value=0.70, step=0.05, label="Transformation Strength")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1587
 
1588
  with gr.Row():
1589
+ img2img_steps = gr.Slider(1, 30, value=25, step=1, label="Inference Steps")
1590
+ img2img_guidance = gr.Slider(1, 15, value=7.5, step=0.5, label="Guidance Scale")
 
 
 
 
 
 
 
 
 
 
 
1591
 
1592
  with gr.Row():
1593
+ img2img_seed = gr.Number(value=0, precision=0, label="Seed")
1594
+ img2img_random = gr.Checkbox(value=True, label="Random Seed")
 
 
 
 
 
 
 
 
 
 
 
 
 
1595
 
1596
+ img2img_button = gr.Button("πŸͺ„ Transform Image", variant="primary")
1597
+ img2img_output = gr.Image(label="Transformed Image", type="pil", height=400)
1598
+ img2img_seed_output = gr.Number(label="Used Seed", precision=0)
 
 
 
 
 
 
 
1599
 
1600
  img2img_button.click(
1601
  fn=generate_image_to_image,
1602
+ inputs=[input_image, img2img_prompt, img2img_negative, img2img_model,
1603
+ strength, img2img_steps, img2img_guidance, img2img_seed, img2img_random],
1604
+ outputs=[img2img_output, img2img_seed_output],
 
 
 
 
 
 
 
 
 
 
 
 
1605
  )
1606
 
1607
+ # --- AI CODING ---
 
 
 
1608
  with gr.Tab("πŸ’» AI Coding"):
1609
+ gr.Markdown("""
1610
+ ## πŸ’» ARISE AI Coding Workspace
1611
+ Upload an existing project, describe your changes,
1612
+ and download the updated project.
1613
+ """)
 
 
 
 
1614
 
1615
  code_model = gr.Dropdown(
1616
  choices=list(CODE_MODELS.keys()),
1617
  value="Qwen Coder 0.5B",
1618
  label="Select Coding Model",
1619
  )
 
1620
  project_upload = gr.File(
1621
  label="οΌ‹ Upload ZIP, Images or Project Files",
1622
  file_count="multiple",
1623
  type="filepath",
1624
  )
 
1625
  code_prompt = gr.Textbox(
1626
  label="Your Coding Request",
1627
  placeholder="Example: Change the app theme and update the home screen...",
 
1629
  )
1630
 
1631
  with gr.Row():
1632
+ max_tokens = gr.Slider(128, 2048, value=768, step=128, label="Maximum Output Tokens")
1633
+ temperature = gr.Slider(0.1, 1.0, value=0.3, step=0.1, label="Temperature")
 
 
 
 
 
 
 
 
 
 
 
1634
 
1635
  coding_output = gr.Markdown(
1636
  value="Ready to work on your project.",
 
1638
  )
1639
 
1640
  with gr.Row():
1641
+ generate_code = gr.Button("⚑ Start Coding", variant="primary")
1642
+ stop_button = gr.Button("⏹ Stop", variant="stop")
1643
+ new_project_button = gr.Button("οΌ‹ New Project", variant="secondary")
 
1644
 
1645
+ coding_status = gr.Markdown("Ready.", elem_id="coding-status")
 
 
 
1646
 
1647
+ gr.Markdown("### πŸ“¦ Project Downloads")
 
 
 
 
 
 
 
1648
 
1649
  with gr.Row():
1650
+ project_zip_download = gr.File(label="Download Full Project ZIP", interactive=False)
1651
+ single_file_download = gr.File(label="Download Last Edited File", interactive=False)
 
 
 
 
 
 
 
 
 
 
 
1652
 
1653
+ preview_button = gr.Button("🌐 Preview HTML Project")
1654
  html_preview = gr.HTML(
1655
  value="<div style='padding:15px;color:#aaa'>HTML preview will appear here.</div>"
1656
  )
1657
 
1658
  generate_code.click(
1659
  fn=coding_assistant,
1660
+ inputs=[code_prompt, code_model, max_tokens, temperature, project_upload, conversation_state],
1661
+ outputs=[coding_output, conversation_state, coding_status,
1662
+ project_zip_download, single_file_download, job_state],
 
 
 
 
 
 
 
 
 
 
 
 
 
1663
  )
1664
+ stop_button.click(fn=stop_job, inputs=job_state, outputs=coding_status)
 
 
 
 
 
 
1665
  new_project_button.click(
1666
  fn=clear_current_conversation,
1667
+ outputs=[coding_output, conversation_state, coding_status, job_state],
 
 
 
 
 
 
 
 
 
 
 
1668
  )
1669
+ preview_button.click(fn=preview_project, inputs=conversation_state, outputs=html_preview)
1670
 
1671
+ # --- HISTORY ---
 
 
 
1672
  with gr.Tab("πŸ“š History"):
1673
+ gr.Markdown("## πŸ“š Saved Conversations and Projects")
1674
 
1675
+ history_dropdown = gr.Dropdown(choices=[], label="Saved History", interactive=True)
 
 
 
 
 
 
1676
 
1677
  with gr.Row():
1678
+ refresh_history_button = gr.Button("πŸ”„ Refresh History")
1679
+ load_history_button = gr.Button("πŸ“‚ Open Selected", variant="primary")
 
 
 
 
 
 
 
 
 
 
1680
 
1681
+ history_output = gr.Markdown("Select a saved conversation.")
1682
  history_status = gr.Markdown("")
1683
+ resume_button = gr.Button("β–Ά Resume Selected Job")
 
 
 
1684
 
1685
  with gr.Row():
1686
+ delete_history_button = gr.Button("πŸ—‘ Delete Selected", variant="stop")
1687
+ delete_all_history_button = gr.Button("πŸ—‘ Delete All", variant="stop")
 
 
 
 
 
 
 
 
 
 
 
 
1688
 
1689
+ refresh_history_button.click(fn=refresh_history, outputs=history_dropdown)
1690
  load_history_button.click(
1691
  fn=load_selected_history,
1692
  inputs=history_dropdown,
1693
+ outputs=[history_output, conversation_state, history_status, job_state],
 
 
 
 
 
1694
  )
 
1695
  delete_history_button.click(
1696
  fn=delete_selected_history,
1697
  inputs=history_dropdown,
1698
+ outputs=[history_dropdown, history_status],
 
 
 
1699
  )
1700
 
1701
  def delete_all(request: gr.Request):
1702
  session_id = request.session_hash if request else "default"
1703
  choices = get_conversations(session_id)
1704
  ids = [value for _, value in choices]
 
1705
  delete_conversations(session_id, ids)
1706
+ return (gr.Dropdown(choices=[], value=None), "All history deleted.")
 
 
 
 
1707
 
1708
  delete_all_history_button.click(
1709
  fn=delete_all,
1710
+ outputs=[history_dropdown, history_status],
 
 
 
1711
  )
 
1712
  resume_button.click(
1713
  fn=resume_job,
1714
  inputs=job_state,
1715
+ outputs=[history_output, history_status, project_zip_download, single_file_download],
 
 
 
 
 
1716
  )
1717
 
1718
+ # --- FOOTER ---
1719
+ gr.HTML(f"""
1720
+ <div id="footer">
1721
+ <div style="font-size:22px;font-weight:800;
1722
+ background:linear-gradient(90deg,#c7b7ff,#67e8f9);
1723
+ -webkit-background-clip:text;-webkit-text-fill-color:transparent;
1724
+ margin-bottom:8px;">
1725
+ ⚑ ARISE AI STUDIO
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1726
  </div>
1727
+ <div style="color:#a5b4fc;font-size:13px;letter-spacing:1px">
1728
+ Premium AI Workspace
1729
+ </div>
1730
+ <div style="margin-top:10px;font-size:12px">
1731
+ Developer: <a href="{DEVELOPER_TELEGRAM}" target="_blank">@hardhackar009</a>
1732
+ </div>
1733
+ <div style="margin-top:8px;font-size:11px;color:#64748b">
1734
+ Powered by Open Source Models and Hugging Face
1735
+ </div>
1736
+ </div>
1737
+ """)
1738
 
1739
+ # Attach premium JS on load
1740
+ demo.load(fn=None, js=PREMIUM_JS)
1741
 
1742
  # =========================================================
1743
  # LAUNCH
1744
  # =========================================================
1745
 
1746
  if __name__ == "__main__":
 
1747
  demo.queue(
1748
  default_concurrency_limit=1,
1749
  max_size=20,
 
1756
  css=CSS,
1757
  show_error=True,
1758
  share=False,
1759
+ )