File size: 2,589 Bytes
0ab9053 0f71c84 d65bc64 0f71c84 ac2910f 0f71c84 3213643 0f71c84 d65bc64 0f71c84 d65bc64 0f71c84 d65bc64 0f71c84 3213643 0f71c84 d65bc64 0f71c84 d65bc64 0f71c84 d65bc64 0f71c84 d65bc64 0f71c84 d65bc64 0f71c84 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
import asyncio
import random
import gradio as gr
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
print("===== Application Startup =====")
# -----------------------
# Load model
# -----------------------
print("Loading model...")
model_name = "gpt2" # you can swap this for a larger model if you have GPU
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
print("Model loaded successfully.")
# -----------------------
# Load dataset
# -----------------------
print("Fetching dataset...")
dataset = load_dataset("lvwerra/stack-exchange-paired", split="train[:200]")
# limit to 200 for speed β you can increase if you want
print(f"Total prompts available: {len(dataset)}")
# Split dataset
initial_prompts = dataset[:20] # first 20 for fast startup
remaining_prompts = dataset[20:] # remaining ~180
# Storage for loaded prompts
prompts = []
for item in initial_prompts:
prompts.append(item["question"])
print(f"Loaded {len(prompts)} initial prompts for fast startup.")
# -----------------------
# Async loading of remaining prompts
# -----------------------
async def load_remaining_prompts():
print("Background: Loading remaining prompts...")
await asyncio.sleep(2) # simulate delay
for item in remaining_prompts:
prompts.append(item["question"])
print(f"Background: Finished loading. Total prompts now = {len(prompts)}")
# -----------------------
# Gradio interface
# -----------------------
def chat_with_model(user_input):
"""Respond to user with a random dataset prompt + model output."""
if not prompts:
return "Prompts not ready yet. Please wait..."
prompt = random.choice(prompts)
response = generator(f"{prompt}\n\nUser: {user_input}\nAI:",
max_length=100,
num_return_sequences=1,
do_sample=True)[0]["generated_text"]
return response
demo = gr.Interface(
fn=chat_with_model,
inputs=gr.Textbox(lines=2, placeholder="Ask me something..."),
outputs="text",
title="Fast Prompt Loader Chatbot",
description="Loads 20 prompts fast, then background loads 200+ prompts"
)
# -----------------------
# App runner
# -----------------------
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.create_task(load_remaining_prompts()) # schedule async loading
demo.launch(server_name="0.0.0.0", server_port=7860)
|