Sjwjne commited on
Commit
866daf3
Β·
verified Β·
1 Parent(s): aae0687

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -34
app.py CHANGED
@@ -7,28 +7,30 @@ import gradio as gr
7
  from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
8
  from threading import Thread
9
 
10
- # --- AI Setup (Qwen 1.5B - Very Stable) ---
11
  MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct"
12
 
13
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
14
  model = AutoModelForCausalLM.from_pretrained(
15
  MODEL_ID,
16
- torch_dtype="auto",
17
- device_map="cpu"
18
- )
19
 
20
  @spaces.GPU
21
  def chat_fn(message, history):
 
22
  messages = []
23
  for h in history:
24
- messages.append({"role": "user", "content": h[0]})
25
- messages.append({"role": "assistant", "content": h[1]})
 
26
  messages.append({"role": "user", "content": message})
27
 
28
  model.to("cuda")
29
  input_ids = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to("cuda")
30
- streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
31
 
 
32
  thread = Thread(target=model.generate, kwargs=dict(input_ids=input_ids, streamer=streamer, max_new_tokens=512))
33
  thread.start()
34
 
@@ -37,66 +39,59 @@ def chat_fn(message, history):
37
  response += new_text
38
  yield response
39
 
40
- # --- React Preview Logic ---
41
  BUILD_DIR = "web_app"
42
 
43
  def handle_zip_upload(zip_file):
44
  if zip_file is None:
45
- return "❌ Please upload a ZIP file first."
46
 
47
  if os.path.exists(BUILD_DIR):
48
  shutil.rmtree(BUILD_DIR)
49
  os.makedirs(BUILD_DIR)
50
 
51
  try:
52
- # Extracting
53
  yield "πŸ“¦ Extracting files..."
54
  shutil.unpack_archive(zip_file.name, BUILD_DIR)
55
 
56
- # Finding root folder with package.json
57
  root_path = BUILD_DIR
58
  for root, dirs, files in os.walk(BUILD_DIR):
59
  if "package.json" in files:
60
  root_path = root
61
  break
62
 
63
- # NPM Install
64
- yield "πŸ”¨ Installing dependencies (npm install)... This may take a minute."
65
  subprocess.run(["npm", "install"], cwd=root_path, check=True)
66
 
67
- # NPM Build
68
- yield "πŸ—οΈ Building project (npm run build)..."
69
  subprocess.run(["npm", "run", "build"], cwd=root_path, check=True)
70
 
71
  dist_path = os.path.join(root_path, "dist")
72
  if os.path.exists(dist_path):
73
- yield "βœ… Build Successful! Your files are ready in the 'dist' folder."
74
  else:
75
- yield "⚠️ Build finished but 'dist' folder was not found. Check your vite.config settings."
76
 
77
  except Exception as e:
78
  yield f"❌ Error: {str(e)}"
79
 
80
- # --- Gradio UI ---
81
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
82
- gr.HTML("<h1 style='text-align:center;'>πŸš€ AI Chat + React Previewer</h1>")
83
 
84
  with gr.Tabs():
85
- # Tab 1: AI Chat
86
- with gr.TabItem("πŸ’¬ Smart Chat"):
87
- gr.ChatInterface(fn=chat_fn, type="messages")
88
 
89
- # Tab 2: React Build
90
- with gr.TabItem("βš›οΈ React Zip Preview"):
91
- gr.Markdown("### Upload Vite/React Project ZIP")
92
- with gr.Row():
93
- zip_input = gr.File(label="Upload ZIP File", file_types=[".zip"])
94
- status_output = gr.Markdown("Status: Ready")
95
 
96
- build_btn = gr.Button("Build Project", variant="primary")
97
  build_btn.click(handle_zip_upload, inputs=zip_input, outputs=status_output)
98
-
99
- gr.Markdown("Note: Static previews on ZeroGPU are limited. Check build logs for errors.")
100
 
101
- if __name__ == "__main__":
102
- demo.launch()
 
7
  from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
8
  from threading import Thread
9
 
10
+ # --- AI Setup ---
11
  MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct"
12
 
13
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
14
  model = AutoModelForCausalLM.from_pretrained(
15
  MODEL_ID,
16
+ torch_dtype=torch.bfloat16,
17
+ device_map=None
18
+ ).to("cpu")
19
 
20
  @spaces.GPU
21
  def chat_fn(message, history):
22
+ # Naye Gradio mein history format badal gaya hai, hum use handle karenge
23
  messages = []
24
  for h in history:
25
+ messages.append({"role": "user", "content": h["human"] if isinstance(h, dict) else h[0]})
26
+ messages.append({"role": "assistant", "content": h["ai"] if isinstance(h, dict) else h[1]})
27
+
28
  messages.append({"role": "user", "content": message})
29
 
30
  model.to("cuda")
31
  input_ids = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to("cuda")
 
32
 
33
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
34
  thread = Thread(target=model.generate, kwargs=dict(input_ids=input_ids, streamer=streamer, max_new_tokens=512))
35
  thread.start()
36
 
 
39
  response += new_text
40
  yield response
41
 
42
+ # --- React Build Logic ---
43
  BUILD_DIR = "web_app"
44
 
45
  def handle_zip_upload(zip_file):
46
  if zip_file is None:
47
+ return "❌ Please upload a ZIP file."
48
 
49
  if os.path.exists(BUILD_DIR):
50
  shutil.rmtree(BUILD_DIR)
51
  os.makedirs(BUILD_DIR)
52
 
53
  try:
 
54
  yield "πŸ“¦ Extracting files..."
55
  shutil.unpack_archive(zip_file.name, BUILD_DIR)
56
 
57
+ # Root folder find karna jisme package.json ho
58
  root_path = BUILD_DIR
59
  for root, dirs, files in os.walk(BUILD_DIR):
60
  if "package.json" in files:
61
  root_path = root
62
  break
63
 
64
+ yield "πŸ”¨ Running 'npm install'..."
 
65
  subprocess.run(["npm", "install"], cwd=root_path, check=True)
66
 
67
+ yield "πŸ—οΈ Running 'npm run build'..."
 
68
  subprocess.run(["npm", "run", "build"], cwd=root_path, check=True)
69
 
70
  dist_path = os.path.join(root_path, "dist")
71
  if os.path.exists(dist_path):
72
+ yield f"βœ… Build Successful! Your React app is ready in: {dist_path}"
73
  else:
74
+ yield "⚠️ Build finished but 'dist' folder not found."
75
 
76
  except Exception as e:
77
  yield f"❌ Error: {str(e)}"
78
 
79
+ # --- UI Setup ---
80
+ with gr.Blocks() as demo:
81
+ gr.HTML("<h1 style='text-align:center;'>πŸš€ AI Chat + React Preview</h1>")
82
 
83
  with gr.Tabs():
84
+ with gr.TabItem("πŸ’¬ Chat"):
85
+ # Fixed ChatInterface syntax for Gradio 5/6
86
+ gr.ChatInterface(fn=chat_fn)
87
 
88
+ with gr.TabItem("βš›οΈ React Zip Build"):
89
+ gr.Markdown("### Upload React/Vite Project (ZIP)")
90
+ zip_input = gr.File(label="Upload ZIP", file_types=[".zip"])
91
+ status_output = gr.Markdown("Status: Idle")
92
+ build_btn = gr.Button("Install & Build", variant="primary")
 
93
 
 
94
  build_btn.click(handle_zip_upload, inputs=zip_input, outputs=status_output)
 
 
95
 
96
+ # Theme ko launch mein daala hai kyunki naye Gradio mein Blocks mein allow nahi hai
97
+ demo.launch(theme=gr.themes.Soft())