lastwarning commited on
Commit
5d237f7
Β·
verified Β·
1 Parent(s): 8178189

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1495 -359
app.py CHANGED
@@ -1,18 +1,23 @@
1
 
2
  import os
3
  import gc
 
 
 
 
 
4
  import random
 
 
5
  import threading
6
  import traceback
 
 
7
 
8
  os.environ["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "1"
9
  os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
10
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
11
 
12
- # ==========================================
13
- # IMPORTS
14
- # ==========================================
15
-
16
  import spaces
17
  import gradio as gr
18
  import torch
@@ -35,20 +40,61 @@ from transformers import (
35
  from threading import Thread, Event
36
 
37
 
38
- # ==========================================
39
  # CONFIGURATION
40
- # ==========================================
41
 
42
- APP_NAME = "Tasting AI Studio"
 
43
 
44
  MAX_INPUT_LENGTH = 4096
45
  MAX_HISTORY_MESSAGES = 10
 
 
 
 
46
 
47
  IMAGE_DTYPE = torch.float16
48
 
49
- # ==========================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  # IMAGE MODELS
51
- # ==========================================
52
 
53
  IMAGE_MODELS = {
54
  "SDXL Turbo": {
@@ -57,21 +103,18 @@ IMAGE_MODELS = {
57
  "guidance": 0.0,
58
  "max_steps": 4,
59
  },
60
-
61
  "Stable Diffusion 1.5": {
62
  "id": "stable-diffusion-v1-5/stable-diffusion-v1-5",
63
  "steps": 25,
64
  "guidance": 7.5,
65
  "max_steps": 30,
66
  },
67
-
68
  "SD Turbo": {
69
  "id": "stabilityai/sd-turbo",
70
  "steps": 4,
71
  "guidance": 0.0,
72
  "max_steps": 4,
73
  },
74
-
75
  "Tiny SD": {
76
  "id": "segmind/tiny-sd",
77
  "steps": 20,
@@ -81,19 +124,15 @@ IMAGE_MODELS = {
81
  }
82
 
83
 
84
- # ==========================================
85
- # IMAGE TO IMAGE MODELS
86
- # ==========================================
87
-
88
  IMAGE_TO_IMAGE_MODELS = {
89
  "Stable Diffusion 1.5 Img2Img":
90
  "stable-diffusion-v1-5/stable-diffusion-v1-5",
91
  }
92
 
93
 
94
- # ==========================================
95
  # CODING MODELS
96
- # ==========================================
97
 
98
  CODE_MODELS = {
99
  "Qwen Coder 0.5B":
@@ -116,9 +155,271 @@ CODE_MODELS = {
116
  }
117
 
118
 
119
- # ==========================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  # MODEL CACHE
121
- # ==========================================
122
 
123
  image_cache = {
124
  "name": None,
@@ -134,16 +435,12 @@ code_cache = {
134
  image_lock = threading.RLock()
135
  code_lock = threading.RLock()
136
 
137
- generation_events = {}
138
- generation_events_lock = threading.Lock()
 
139
 
140
 
141
- # ==========================================
142
- # MEMORY CLEANUP
143
- # ==========================================
144
-
145
  def clear_image_cache():
146
-
147
  old_pipe = image_cache["pipe"]
148
 
149
  image_cache["pipe"] = None
@@ -159,7 +456,6 @@ def clear_image_cache():
159
 
160
 
161
  def clear_code_cache():
162
-
163
  old_model = code_cache["model"]
164
  old_tokenizer = code_cache["tokenizer"]
165
 
@@ -176,16 +472,14 @@ def clear_code_cache():
176
  gc.collect()
177
 
178
 
179
- # ==========================================
180
  # IMAGE PIPELINE
181
- # ==========================================
182
 
183
  def load_image_pipeline(model_id, mode):
184
-
185
  cache_key = f"{mode}:{model_id}"
186
 
187
  with image_lock:
188
-
189
  if (
190
  image_cache["name"] == cache_key
191
  and image_cache["pipe"] is not None
@@ -195,7 +489,6 @@ def load_image_pipeline(model_id, mode):
195
  clear_image_cache()
196
 
197
  if mode == "text":
198
-
199
  pipe = DiffusionPipeline.from_pretrained(
200
  model_id,
201
  torch_dtype=IMAGE_DTYPE,
@@ -203,7 +496,6 @@ def load_image_pipeline(model_id, mode):
203
  )
204
 
205
  elif mode == "image":
206
-
207
  pipe = AutoPipelineForImage2Image.from_pretrained(
208
  model_id,
209
  torch_dtype=IMAGE_DTYPE,
@@ -224,9 +516,9 @@ def load_image_pipeline(model_id, mode):
224
  return pipe
225
 
226
 
227
- # ==========================================
228
  # TEXT TO IMAGE
229
- # ==========================================
230
 
231
  @spaces.GPU(duration=120)
232
  def generate_image(
@@ -239,7 +531,6 @@ def generate_image(
239
  seed,
240
  random_seed,
241
  ):
242
-
243
  if not prompt or not prompt.strip():
244
  raise gr.Error("Enter an image prompt.")
245
 
@@ -251,7 +542,7 @@ def generate_image(
251
  if random_seed:
252
  seed = random.randint(0, 2147483647)
253
 
254
- seed = int(seed)
255
 
256
  width = max(256, min(int(width), 768))
257
  height = max(256, min(int(height), 768))
@@ -268,9 +559,7 @@ def generate_image(
268
  actual_steps = min(actual_steps, 4)
269
 
270
  try:
271
-
272
  with image_lock:
273
-
274
  pipe = load_image_pipeline(
275
  config["id"],
276
  "text",
@@ -293,17 +582,13 @@ def generate_image(
293
  return result.images[0], seed
294
 
295
  except Exception as error:
296
-
297
  traceback.print_exc()
298
-
299
- raise gr.Error(
300
- f"Image generation failed: {error}"
301
- )
302
 
303
 
304
- # ==========================================
305
  # IMAGE TO IMAGE
306
- # ==========================================
307
 
308
  @spaces.GPU(duration=120)
309
  def generate_image_to_image(
@@ -317,7 +602,6 @@ def generate_image_to_image(
317
  seed,
318
  random_seed,
319
  ):
320
-
321
  if input_image is None:
322
  raise gr.Error("Upload an image.")
323
 
@@ -330,19 +614,14 @@ def generate_image_to_image(
330
  if random_seed:
331
  seed = random.randint(0, 2147483647)
332
 
333
- seed = int(seed)
334
 
335
  strength = max(0.05, min(float(strength), 0.95))
336
  steps = max(1, min(int(steps), 30))
337
 
338
  try:
339
-
340
  image = input_image.convert("RGB")
341
-
342
- image.thumbnail(
343
- (768, 768),
344
- Image.Resampling.LANCZOS,
345
- )
346
 
347
  width = max(256, (image.width // 8) * 8)
348
  height = max(256, (image.height // 8) * 8)
@@ -355,11 +634,7 @@ def generate_image_to_image(
355
  model_id = IMAGE_TO_IMAGE_MODELS[model_name]
356
 
357
  with image_lock:
358
-
359
- pipe = load_image_pipeline(
360
- model_id,
361
- "image",
362
- )
363
 
364
  generator = torch.Generator(
365
  device="cuda"
@@ -378,23 +653,18 @@ def generate_image_to_image(
378
  return result.images[0], seed
379
 
380
  except Exception as error:
381
-
382
  traceback.print_exc()
 
383
 
384
- raise gr.Error(
385
- f"Image-to-image failed: {error}"
386
- )
387
 
388
-
389
- # ==========================================
390
  # CODING SYSTEM PROMPT
391
- # ==========================================
392
 
393
  SYSTEM_PROMPT = """
394
- You are Tasting AI, a professional software engineering assistant.
395
-
396
- SPECIALIZATIONS:
397
 
 
398
  Python, Kotlin, Java, Android, Gradle, AAPT2,
399
  JavaScript, TypeScript, HTML, CSS, React,
400
  APIs, databases, Hugging Face, Gradio,
@@ -402,43 +672,53 @@ PyTorch, Diffusers, Transformers, debugging,
402
  software architecture and code optimization.
403
 
404
  RULES:
405
-
406
  1. Understand the complete user request.
407
  2. Generate practical working code.
408
- 3. Never intentionally omit important code.
409
- 4. Preserve existing features.
410
- 5. Explain important changes.
411
  6. Return complete files when requested.
412
- 7. Identify dependencies.
413
  8. Never claim code was tested unless tested.
414
  9. Use Markdown.
415
- 10. Prioritize correctness.
416
- 11. Analyze errors before proposing fixes.
417
- 12. Avoid unnecessary changes.
418
- 13. Maintain environment compatibility.
419
- 14. Explain limitations honestly.
420
- 15. Return complete implementations when requested.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
421
  """
422
 
423
 
424
- # ==========================================
425
  # LOAD CODING MODEL
426
- # ==========================================
427
 
428
  def load_code_model(model_name):
429
-
430
  if model_name not in CODE_MODELS:
431
  raise ValueError("Invalid coding model.")
432
 
433
  model_id = CODE_MODELS[model_name]
434
 
435
  with code_lock:
436
-
437
  if (
438
  code_cache["name"] == model_id
439
  and code_cache["model"] is not None
440
  ):
441
-
442
  return (
443
  code_cache["tokenizer"],
444
  code_cache["model"],
@@ -461,19 +741,463 @@ def load_code_model(model_name):
461
  model.to("cpu")
462
  model.eval()
463
 
464
- code_cache["name"] = model_id
465
- code_cache["tokenizer"] = tokenizer
466
- code_cache["model"] = model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
467
 
468
- return tokenizer, model
 
 
 
 
 
469
 
470
 
471
- # ==========================================
472
  # STOP CRITERIA
473
- # ==========================================
474
 
475
  class StopCriteria(StoppingCriteria):
476
-
477
  def __init__(self, event):
478
  self.event = event
479
 
@@ -481,47 +1205,25 @@ class StopCriteria(StoppingCriteria):
481
  return self.event.is_set()
482
 
483
 
484
- # ==========================================
485
- # CODING ASSISTANT
486
- # ==========================================
487
 
488
- def coding_assistant(
 
 
 
489
  prompt,
490
  model_name,
491
  max_tokens,
492
  temperature,
493
- history,
494
- request: gr.Request,
495
  ):
496
-
497
- if not prompt or not prompt.strip():
498
- yield "Please enter your coding request.", history or []
499
- return
500
-
501
- history = list(history or [])
502
-
503
- session_id = (
504
- request.session_hash
505
- if request
506
- else "default"
507
- )
508
-
509
- stop_event = Event()
510
-
511
- with generation_events_lock:
512
-
513
- previous = generation_events.get(session_id)
514
-
515
- if previous:
516
- previous.set()
517
-
518
- generation_events[session_id] = stop_event
519
-
520
- response = ""
521
-
522
  try:
 
523
 
524
- yield "⏳ Loading coding model...", history
 
525
 
526
  tokenizer, model = load_code_model(model_name)
527
 
@@ -529,39 +1231,58 @@ def coding_assistant(
529
  {
530
  "role": "system",
531
  "content": SYSTEM_PROMPT,
532
- }
533
  ]
534
 
535
- for item in history[-MAX_HISTORY_MESSAGES:]:
 
 
 
536
 
537
- if not isinstance(item, dict):
538
- continue
 
 
 
539
 
 
540
  if (
541
- item.get("role") in ["user", "assistant"]
 
542
  and isinstance(item.get("content"), str)
543
  ):
544
-
545
  messages.append({
546
  "role": item["role"],
547
  "content": item["content"],
548
  })
549
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550
  messages.append({
551
  "role": "user",
552
- "content": prompt.strip(),
553
  })
554
 
555
  if getattr(tokenizer, "chat_template", None):
556
-
557
  formatted_prompt = tokenizer.apply_chat_template(
558
  messages,
559
  tokenize=False,
560
  add_generation_prompt=True,
561
  )
562
-
563
  else:
564
-
565
  formatted_prompt = "\n\n".join(
566
  f"{item['role'].upper()}:\n{item['content']}"
567
  for item in messages
@@ -584,7 +1305,7 @@ def coding_assistant(
584
  generation_kwargs = {
585
  **inputs,
586
  "streamer": streamer,
587
- "max_new_tokens": int(max_tokens),
588
  "do_sample": float(temperature) > 0.05,
589
  "temperature": max(float(temperature), 0.05),
590
  "pad_token_id": (
@@ -597,18 +1318,14 @@ def coding_assistant(
597
  ]),
598
  }
599
 
600
- generation_error = []
601
 
602
  def generate():
603
-
604
  try:
605
-
606
  with torch.inference_mode():
607
  model.generate(**generation_kwargs)
608
-
609
  except Exception as error:
610
-
611
- generation_error.append(str(error))
612
  traceback.print_exc()
613
 
614
  try:
@@ -616,40 +1333,54 @@ def coding_assistant(
616
  except Exception:
617
  pass
618
 
619
- thread = Thread(
620
  target=generate,
621
  daemon=True,
622
  )
 
623
 
624
- thread.start()
625
 
626
  for token in streamer:
627
-
628
  if stop_event.is_set():
629
  break
630
 
631
  response += token
632
 
633
- yield response, history
 
 
 
 
634
 
635
- thread.join(timeout=10)
636
 
637
- if thread.is_alive():
638
  stop_event.set()
639
 
640
- if generation_error:
641
- raise RuntimeError(generation_error[0])
642
 
643
  if stop_event.is_set():
644
- response += "\n\n⏹ Generation stopped."
 
 
 
 
 
645
 
646
  if not response.strip():
647
  response = "No response generated."
648
 
649
- new_history = history + [
 
 
 
 
 
650
  {
651
  "role": "user",
652
- "content": prompt.strip(),
653
  },
654
  {
655
  "role": "assistant",
@@ -657,124 +1388,412 @@ def coding_assistant(
657
  },
658
  ]
659
 
660
- yield response, new_history
 
 
661
 
662
- except Exception as error:
 
 
 
 
 
663
 
664
- traceback.print_exc()
665
 
666
- error_text = f"**Coding error:** {error}"
 
 
 
 
667
 
668
- new_history = history + [
669
- {
670
- "role": "user",
671
- "content": prompt.strip(),
672
- },
673
- {
674
- "role": "assistant",
675
- "content": error_text,
676
- },
677
- ]
 
 
 
678
 
679
- yield error_text, new_history
 
 
 
 
 
680
 
681
  finally:
 
 
 
 
682
 
683
- with generation_events_lock:
 
 
684
 
685
- if generation_events.get(session_id) is stop_event:
686
- generation_events.pop(session_id, None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
687
 
 
688
 
689
- # ==========================================
690
- # STOP GENERATION
691
- # ==========================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
692
 
693
- def stop_generation(request: gr.Request):
 
694
 
695
- session_id = (
696
- request.session_hash
697
- if request
698
- else "default"
 
 
 
699
  )
700
 
701
- with generation_events_lock:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
702
 
703
- event = generation_events.get(session_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
704
 
705
  if event:
706
  event.set()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
707
 
708
- return "⏹ Stop requested."
 
 
 
 
 
 
 
709
 
710
 
711
- # ==========================================
712
- # CLEAR HISTORY
713
- # ==========================================
714
 
715
- def clear_history():
716
- return "", [], "Conversation cleared."
 
 
 
 
 
717
 
718
 
719
- # ==========================================
720
  # PREMIUM CSS
721
- # ==========================================
722
 
723
  CSS = r"""
724
- @import url(
725
- 'https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap'
726
- );
 
 
727
 
728
  body {
729
  background:
730
- radial-gradient(circle at 15% 10%,
731
- rgba(105,64,255,.15),transparent 35%),
732
- radial-gradient(circle at 90% 80%,
733
- rgba(0,205,255,.10),transparent 35%),
734
  #080b14 !important;
735
- font-family: Inter,sans-serif !important;
736
  }
737
 
738
  .gradio-container {
 
739
  max-width: 1250px !important;
740
  margin: auto !important;
741
  background: transparent !important;
 
742
  }
743
 
744
  #main-header {
745
  position: relative;
746
  overflow: hidden;
747
  text-align: center;
748
- padding: 55px 20px;
749
  border: 1px solid rgba(139,92,246,.35);
750
- border-radius: 25px;
751
- background: linear-gradient(
752
- 120deg,
753
- rgba(45,26,90,.95),
754
- rgba(9,35,57,.95),
755
- rgba(30,17,70,.95)
756
- );
757
  animation: bannerGlow 5s ease-in-out infinite alternate;
758
  }
759
 
760
  @keyframes bannerGlow {
761
- from {
762
- box-shadow: 0 0 15px rgba(139,92,246,.15);
763
- }
764
  to {
765
- box-shadow:
766
- 0 0 38px rgba(6,214,233,.24),
767
- 0 0 65px rgba(139,92,246,.17);
768
  }
769
  }
770
 
771
  .hero-title {
772
- font-size: clamp(30px,6vw,58px);
773
  font-weight: 900;
774
  letter-spacing: -2px;
775
- background: linear-gradient(
776
- 90deg,#fff,#b8a5ff,#56e8ff,#fff
777
- );
778
  background-size: 300%;
779
  -webkit-background-clip: text;
780
  -webkit-text-fill-color: transparent;
@@ -788,24 +1807,16 @@ body {
788
 
789
  .hero-subtitle {
790
  color: #bdc7df;
791
- font-size: 14px;
792
  letter-spacing: 2px;
793
  margin-top: 12px;
794
- overflow: hidden;
795
- white-space: nowrap;
796
- border-right: 2px solid #56e8ff;
797
- animation:
798
- typing 3.5s steps(42,end),
799
- cursorBlink .8s step-end infinite;
800
  }
801
 
802
- @keyframes typing {
803
- from { max-width: 0; }
804
- to { max-width: 100%; }
805
- }
806
-
807
- @keyframes cursorBlink {
808
- 50% { border-color: transparent; }
809
  }
810
 
811
  .gradio-container .tab-nav {
@@ -826,27 +1837,27 @@ body {
826
  }
827
 
828
  .primary {
829
- background: linear-gradient(
830
- 100deg,#7045ed,#168edb
831
- ) !important;
832
  color: white !important;
833
  font-weight: 800 !important;
834
  }
835
 
836
- textarea,input {
837
  border-radius: 12px !important;
838
  }
839
 
840
  #coding-output {
841
- min-height: 350px;
842
- padding: 18px;
843
  border: 1px solid rgba(6,214,233,.22);
844
  border-radius: 15px;
845
  background: rgba(9,15,28,.8);
 
846
  }
847
 
848
- #coding-output code {
849
- color: #70e7ff;
 
850
  }
851
 
852
  #footer {
@@ -857,44 +1868,54 @@ textarea,input {
857
 
858
  @media(max-width:650px) {
859
  .gradio-container {
860
- padding: 8px !important;
861
  }
862
 
863
  #main-header {
864
- padding: 35px 12px;
 
865
  }
866
 
867
  .hero-title {
868
- font-size: 32px;
 
869
  }
870
 
871
  .hero-subtitle {
872
  font-size: 10px;
 
 
 
 
 
 
 
 
 
 
 
873
  }
874
  }
875
  """
876
 
877
 
878
- # ==========================================
879
  # HEADER
880
- # ==========================================
881
 
882
- HEADER = """
883
  <div id="main-header">
884
-
885
  <div style="
886
- font-size:13px;
887
  color:#83eaff;
888
- letter-spacing:4px;
889
  font-weight:800;
890
  margin-bottom:12px;
891
  ">
892
  NEXT GENERATION ARTIFICIAL INTELLIGENCE
893
  </div>
894
 
895
- <div class="hero-title">
896
- ⚑ TASTING AI STUDIO
897
- </div>
898
 
899
  <div class="hero-subtitle">
900
  CREATE Β· TRANSFORM Β· CODE Β· INNOVATE
@@ -904,63 +1925,63 @@ HEADER = """
904
  display:flex;
905
  justify-content:center;
906
  flex-wrap:wrap;
907
- gap:9px;
908
- margin-top:25px;
909
  ">
910
-
911
- <span style="
912
- background:#ffffff15;
913
- padding:8px 15px;
914
- border-radius:30px;
915
- color:#d8d5ff;
916
- font-size:12px;
917
- ">🎨 AI Art</span>
918
-
919
- <span style="
920
- background:#ffffff15;
921
- padding:8px 15px;
922
- border-radius:30px;
923
- color:#d8d5ff;
924
- font-size:12px;
925
- ">πŸ–Ό Image Transform</span>
926
-
927
- <span style="
928
- background:#ffffff15;
929
- padding:8px 15px;
930
- border-radius:30px;
931
- color:#d8d5ff;
932
- font-size:12px;
933
- ">πŸ’» AI Coding</span>
934
-
935
  </div>
936
-
937
  </div>
938
  """
939
 
940
 
941
- # ==========================================
942
  # GRADIO APPLICATION
943
- # ==========================================
944
 
945
- with gr.Blocks(
946
- title=APP_NAME,
947
- ) as demo:
 
948
 
949
  gr.HTML(HEADER)
950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
951
  gr.Markdown(
952
  """
953
- <div style="text-align:center;color:#9ba9c5;padding:12px">
954
- Premium AI Workspace Β· Public Open Models Β· Live Generation
955
  </div>
956
  """
957
  )
958
 
959
  with gr.Tabs():
960
 
961
- # ==================================
962
  # TEXT TO IMAGE
963
- # ==================================
964
 
965
  with gr.Tab("🎨 Text to Image"):
966
 
@@ -984,30 +2005,28 @@ with gr.Blocks(
984
  )
985
 
986
  with gr.Row():
987
-
988
  width = gr.Slider(
989
- 256,768,
990
  value=512,
991
  step=64,
992
  label="Image Width",
993
  )
994
 
995
  height = gr.Slider(
996
- 256,768,
997
  value=512,
998
  step=64,
999
  label="Image Height",
1000
  )
1001
 
1002
  steps = gr.Slider(
1003
- 1,30,
1004
  value=4,
1005
  step=1,
1006
  label="Inference Steps",
1007
  )
1008
 
1009
  with gr.Row():
1010
-
1011
  seed = gr.Number(
1012
  value=0,
1013
  precision=0,
@@ -1027,7 +2046,7 @@ with gr.Blocks(
1027
  image_output = gr.Image(
1028
  label="Generated Artwork",
1029
  type="pil",
1030
- height=450,
1031
  )
1032
 
1033
  seed_output = gr.Number(
@@ -1053,36 +2072,18 @@ with gr.Blocks(
1053
  ],
1054
  )
1055
 
1056
- # ==================================
1057
  # IMAGE TO IMAGE
1058
- # ==================================
1059
 
1060
  with gr.Tab("πŸ–Ό Image to Image"):
1061
 
1062
- gr.Markdown(
1063
- """
1064
- ## Transform Your Images
1065
-
1066
- Upload an image and describe its new artistic style.
1067
- """
1068
- )
1069
 
1070
  input_image = gr.Image(
1071
  label="Upload Original Image",
1072
  type="pil",
1073
- height=350,
1074
- )
1075
-
1076
- gr.Markdown(
1077
- """
1078
- **Example prompts**
1079
-
1080
- - Hand-painted anime-inspired illustration
1081
- - Soft watercolor fantasy artwork
1082
- - Colorful cartoon illustration
1083
- - Cinematic digital painting
1084
- - Dreamy illustrated landscape
1085
- """
1086
  )
1087
 
1088
  img2img_model = gr.Dropdown(
@@ -1093,7 +2094,7 @@ with gr.Blocks(
1093
 
1094
  img2img_prompt = gr.Textbox(
1095
  label="Transformation Prompt",
1096
- placeholder="Transform this image into a beautiful anime-inspired illustration...",
1097
  lines=4,
1098
  )
1099
 
@@ -1103,30 +2104,28 @@ with gr.Blocks(
1103
  )
1104
 
1105
  strength = gr.Slider(
1106
- 0.05,0.95,
1107
  value=0.70,
1108
  step=0.05,
1109
  label="Transformation Strength",
1110
  )
1111
 
1112
  with gr.Row():
1113
-
1114
  img2img_steps = gr.Slider(
1115
- 1,30,
1116
  value=25,
1117
  step=1,
1118
  label="Inference Steps",
1119
  )
1120
 
1121
  img2img_guidance = gr.Slider(
1122
- 1,15,
1123
  value=7.5,
1124
  step=0.5,
1125
  label="Guidance Scale",
1126
  )
1127
 
1128
  with gr.Row():
1129
-
1130
  img2img_seed = gr.Number(
1131
  value=0,
1132
  precision=0,
@@ -1146,7 +2145,7 @@ with gr.Blocks(
1146
  img2img_output = gr.Image(
1147
  label="Transformed Image",
1148
  type="pil",
1149
- height=450,
1150
  )
1151
 
1152
  img2img_seed_output = gr.Number(
@@ -1173,19 +2172,18 @@ with gr.Blocks(
1173
  ],
1174
  )
1175
 
1176
- # ==================================
1177
  # AI CODING
1178
- # ==================================
1179
 
1180
  with gr.Tab("πŸ’» AI Coding"):
1181
 
1182
  gr.Markdown(
1183
  """
1184
- ## Advanced AI Coding Assistant
1185
 
1186
- <div style="color:#7ddfff">
1187
- Real-time token streaming Β· Multiple coding models
1188
- </div>
1189
  """
1190
  )
1191
 
@@ -1195,39 +2193,41 @@ with gr.Blocks(
1195
  label="Select Coding Model",
1196
  )
1197
 
 
 
 
 
 
 
1198
  code_prompt = gr.Textbox(
1199
  label="Your Coding Request",
1200
- placeholder="Create a complete Python application...",
1201
- lines=6,
1202
  )
1203
 
1204
  with gr.Row():
1205
-
1206
  max_tokens = gr.Slider(
1207
- 128,1024,
1208
- value=512,
1209
  step=128,
1210
  label="Maximum Output Tokens",
1211
  )
1212
 
1213
  temperature = gr.Slider(
1214
- 0.1,1.0,
1215
  value=0.3,
1216
  step=0.1,
1217
  label="Temperature",
1218
  )
1219
 
1220
- coding_history = gr.State([])
1221
-
1222
  coding_output = gr.Markdown(
1223
- label="Live AI Response",
1224
  elem_id="coding-output",
1225
  )
1226
 
1227
  with gr.Row():
1228
-
1229
  generate_code = gr.Button(
1230
- "⚑ Generate Code",
1231
  variant="primary",
1232
  )
1233
 
@@ -1236,13 +2236,32 @@ with gr.Blocks(
1236
  variant="stop",
1237
  )
1238
 
1239
- clear_button = gr.Button(
1240
- "πŸ—‘ Clear History",
1241
  variant="secondary",
1242
  )
1243
 
1244
- coding_status = gr.Markdown(
1245
- "Ready to generate."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1246
  )
1247
 
1248
  generate_code.click(
@@ -1252,61 +2271,178 @@ with gr.Blocks(
1252
  code_model,
1253
  max_tokens,
1254
  temperature,
1255
- coding_history,
 
1256
  ],
1257
  outputs=[
1258
  coding_output,
1259
- coding_history,
 
 
 
 
1260
  ],
1261
  )
1262
 
1263
  stop_button.click(
1264
- fn=stop_generation,
 
1265
  outputs=coding_status,
1266
  )
1267
 
1268
- clear_button.click(
1269
- fn=clear_history,
1270
  outputs=[
1271
  coding_output,
1272
- coding_history,
1273
  coding_status,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1274
  ],
1275
  )
1276
 
1277
- # ======================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1278
  # FOOTER
1279
- # ======================================
1280
 
1281
  gr.HTML(
1282
- """
1283
  <div id="footer">
1284
-
1285
  <div style="
1286
  font-size:19px;
1287
  font-weight:800;
1288
  color:#c7b7ff;
1289
  margin-bottom:8px;
1290
  ">
1291
- ⚑ TASTING AI STUDIO
1292
  </div>
1293
 
1294
- <div>
1295
- Premium AI Workspace Β· Version 2.0
 
 
 
 
 
1296
  </div>
1297
 
1298
  <div style="margin-top:8px;font-size:11px">
1299
  Powered by Open Source Models and Hugging Face
1300
  </div>
1301
-
1302
  </div>
1303
  """
1304
  )
1305
 
1306
 
1307
- # ==========================================
1308
  # LAUNCH
1309
- # ==========================================
1310
 
1311
  if __name__ == "__main__":
1312
 
 
1
 
2
  import os
3
  import gc
4
+ import re
5
+ import json
6
+ import uuid
7
+ import time
8
+ import shutil
9
  import random
10
+ import sqlite3
11
+ import zipfile
12
  import threading
13
  import traceback
14
+ from pathlib import Path
15
+ from datetime import datetime
16
 
17
  os.environ["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "1"
18
  os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
19
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
20
 
 
 
 
 
21
  import spaces
22
  import gradio as gr
23
  import torch
 
40
  from threading import Thread, Event
41
 
42
 
43
+ # =========================================================
44
  # CONFIGURATION
45
+ # =========================================================
46
 
47
+ APP_NAME = "ARISE AI Studio"
48
+ DEVELOPER_TELEGRAM = "https://t.me/hardhackar009"
49
 
50
  MAX_INPUT_LENGTH = 4096
51
  MAX_HISTORY_MESSAGES = 10
52
+ MAX_UPLOAD_FILES = 100
53
+ MAX_FILE_SIZE = 10 * 1024 * 1024
54
+ MAX_PROJECT_SIZE = 100 * 1024 * 1024
55
+ 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:
63
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
64
+ test_file = DATA_DIR / ".write_test"
65
+ test_file.write_text("ok")
66
+ test_file.unlink()
67
+ except Exception:
68
+ DATA_DIR = Path("./arise_ai_studio_data")
69
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
70
+
71
+ DB_PATH = DATA_DIR / "arise_history.db"
72
+ PROJECTS_DIR = DATA_DIR / "projects"
73
+ PROJECTS_DIR.mkdir(parents=True, exist_ok=True)
74
+
75
+ SUPPORTED_TEXT_EXTENSIONS = {
76
+ ".py", ".js", ".jsx", ".ts", ".tsx",
77
+ ".html", ".htm", ".css", ".scss",
78
+ ".json", ".xml", ".yaml", ".yml",
79
+ ".md", ".txt", ".java", ".kt",
80
+ ".gradle", ".properties", ".sh",
81
+ ".bat", ".c", ".cpp", ".h", ".hpp",
82
+ ".php", ".sql", ".go", ".rs",
83
+ ".swift", ".dart", ".vue", ".svelte",
84
+ ".toml", ".ini", ".cfg", ".env.example",
85
+ ".gitignore", ".dockerfile",
86
+ }
87
+
88
+ EXCLUDED_DIRS = {
89
+ ".git", ".gradle", ".idea", ".vscode",
90
+ "__pycache__", "node_modules", "build",
91
+ "dist", ".venv", "venv", ".next",
92
+ }
93
+
94
+
95
+ # =========================================================
96
  # IMAGE MODELS
97
+ # =========================================================
98
 
99
  IMAGE_MODELS = {
100
  "SDXL Turbo": {
 
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,
 
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":
 
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,
182
+ session_id TEXT NOT NULL,
183
+ title TEXT NOT NULL,
184
+ history TEXT NOT NULL,
185
+ created TEXT NOT NULL,
186
+ updated TEXT NOT NULL
187
+ )
188
+ """)
189
+
190
+ connection.execute("""
191
+ CREATE TABLE IF NOT EXISTS jobs (
192
+ id TEXT PRIMARY KEY,
193
+ session_id TEXT NOT NULL,
194
+ conversation_id TEXT NOT NULL,
195
+ status TEXT NOT NULL,
196
+ prompt TEXT NOT NULL,
197
+ response TEXT NOT NULL,
198
+ error TEXT,
199
+ created TEXT NOT NULL,
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)
230
+ VALUES (?, ?, ?, ?, ?, ?)
231
+ ON CONFLICT(id) DO UPDATE SET
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,
 
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
 
456
 
457
 
458
  def clear_code_cache():
 
459
  old_model = code_cache["model"]
460
  old_tokenizer = code_cache["tokenizer"]
461
 
 
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
 
489
  clear_image_cache()
490
 
491
  if mode == "text":
 
492
  pipe = DiffusionPipeline.from_pretrained(
493
  model_id,
494
  torch_dtype=IMAGE_DTYPE,
 
496
  )
497
 
498
  elif mode == "image":
 
499
  pipe = AutoPipelineForImage2Image.from_pretrained(
500
  model_id,
501
  torch_dtype=IMAGE_DTYPE,
 
516
  return pipe
517
 
518
 
519
+ # =========================================================
520
  # TEXT TO IMAGE
521
+ # =========================================================
522
 
523
  @spaces.GPU(duration=120)
524
  def generate_image(
 
531
  seed,
532
  random_seed,
533
  ):
 
534
  if not prompt or not prompt.strip():
535
  raise gr.Error("Enter an image prompt.")
536
 
 
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))
 
559
  actual_steps = min(actual_steps, 4)
560
 
561
  try:
 
562
  with image_lock:
 
563
  pipe = load_image_pipeline(
564
  config["id"],
565
  "text",
 
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(
 
602
  seed,
603
  random_seed,
604
  ):
 
605
  if input_image is None:
606
  raise gr.Error("Upload an image.")
607
 
 
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)
 
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"
 
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,
 
672
  software architecture and code optimization.
673
 
674
  RULES:
 
675
  1. Understand the complete user request.
676
  2. Generate practical working code.
677
+ 3. Preserve existing features.
678
+ 4. Never intentionally omit important code.
679
+ 5. Analyze errors before proposing fixes.
680
  6. Return complete files when requested.
681
+ 7. Explain dependencies and limitations.
682
  8. Never claim code was tested unless tested.
683
  9. Use Markdown.
684
+ 10. Avoid unnecessary changes.
685
+ 11. Maintain environment compatibility.
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
+
693
+ <<<FILE: relative/path/to/file.ext>>>
694
+ complete file content here
695
+ <<<END FILE>>>
696
+
697
+ Do not include unchanged files in this format.
698
+ Do not use absolute paths.
699
+ Do not use ../ path traversal.
700
+ Do not omit required imports or code.
701
+ Do not put explanatory text inside a file block.
702
+
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"],
 
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):
1202
  self.event = event
1203
 
 
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
 
 
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
 
1305
  generation_kwargs = {
1306
  **inputs,
1307
  "streamer": streamer,
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": (
 
1318
  ]),
1319
  }
1320
 
1321
+ errors = []
1322
 
1323
  def generate():
 
1324
  try:
 
1325
  with torch.inference_mode():
1326
  model.generate(**generation_kwargs)
 
1327
  except Exception as error:
1328
+ errors.append(str(error))
 
1329
  traceback.print_exc()
1330
 
1331
  try:
 
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",
 
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",
1550
+ "completed": "βœ… Coding completed",
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;
 
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 {
 
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 {
 
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>
 
 
1919
 
1920
  <div class="hero-subtitle">
1921
  CREATE Β· TRANSFORM Β· CODE Β· INNOVATE
 
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:
1944
+
1945
+ conversation_state = gr.State(None)
1946
+ job_state = gr.State(None)
1947
 
1948
  gr.HTML(HEADER)
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
 
 
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,
 
2046
  image_output = gr.Image(
2047
  label="Generated Artwork",
2048
  type="pil",
2049
+ height=400,
2050
  )
2051
 
2052
  seed_output = gr.Number(
 
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(
 
2094
 
2095
  img2img_prompt = gr.Textbox(
2096
  label="Transformation Prompt",
2097
+ placeholder="Describe the new image style...",
2098
  lines=4,
2099
  )
2100
 
 
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,
 
2145
  img2img_output = gr.Image(
2146
  label="Transformed Image",
2147
  type="pil",
2148
+ height=400,
2149
  )
2150
 
2151
  img2img_seed_output = gr.Number(
 
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
 
 
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...",
2205
+ lines=5,
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.",
2225
  elem_id="coding-output",
2226
  )
2227
 
2228
  with gr.Row():
 
2229
  generate_code = gr.Button(
2230
+ "⚑ Start Coding",
2231
  variant="primary",
2232
  )
2233
 
 
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(
 
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