Update app.py
Browse files
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
|
| 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=
|
| 17 |
-
device_map=
|
| 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
|
| 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
|
| 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 |
-
#
|
| 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 |
-
|
| 64 |
-
yield "π¨ Installing dependencies (npm install)... This may take a minute."
|
| 65 |
subprocess.run(["npm", "install"], cwd=root_path, check=True)
|
| 66 |
|
| 67 |
-
|
| 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
|
| 74 |
else:
|
| 75 |
-
yield "β οΈ Build finished but 'dist' folder
|
| 76 |
|
| 77 |
except Exception as e:
|
| 78 |
yield f"β Error: {str(e)}"
|
| 79 |
|
| 80 |
-
# ---
|
| 81 |
-
with gr.Blocks(
|
| 82 |
-
gr.HTML("<h1 style='text-align:center;'>π AI Chat + React
|
| 83 |
|
| 84 |
with gr.Tabs():
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
gr.ChatInterface(fn=chat_fn
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
gr.
|
| 92 |
-
|
| 93 |
-
|
| 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 |
-
|
| 102 |
-
|
|
|
|
| 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())
|