Update app.py
Browse files8 unmodified lines9101112131415161718192021222324252627282930313233342 unmodified lines3738394041421 unmodified line4445464748495051525354555657585960616263646566676869707172737475767778798081821 unmodified line848586878889909192939495969798991001011021037 unmodified lines11111211311411511611711811912012112212312412512612712812913013124 unmodified lines1561571581591601611621631641651661671681691701711721731748 unmodified linesimport torchimport timeimport randomapp = FastAPI()MODEL_NAME = "Qwen/Qwen2.5-0.5B-Instruct"tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME,trust_remote_code=True)model = AutoModelForCausalLM.from_pretrained(MODEL_NAME,device_map="auto",torch_dtype="auto",trust_remote_code=True,low_cpu_mem_usage=True)model.eval()TEMPLATES = ["templates/landing1.html","templates/landing2.html",2 unmodified linesULTIMA_REQUEST = {}@app.post("/chat")async def chat(request: Request):1 unmodified lineahora = time.time()if ip in ULTIMA_REQUEST:if ahora - ULTIMA_REQUEST[ip] < 5:return {"response": "Rate limit"}ULTIMA_REQUEST[ip] = ahoratry:data = await request.json()historial = data.get("historial", [])[-6:]except:return {"response": "Invalid JSON"}if not historial:return {"response": "Empty history"}user_prompt = str(historial[-1]["content"])[:2000]template_path = random.choice(TEMPLATES)with open(template_path, "r", encoding="utf-8") as f:BASE_TEMPLATE = f.read()messages = [{"role": "system","content": ("Generate website content. ""Return ONLY these fields:\n""TITLE:\n""DESCRIPTION:\n""BUTTON:\n""PRIMARY_COLOR:\n""BACKGROUND:\n")},{"role": "user",1 unmodified line}]text = tokenizer.apply_chat_template(messages,tokenize=False,add_generation_prompt=True)if len(text) > 6000:return {"response": "Prompt too long"}model_inputs = tokenizer(text,return_tensors="pt",truncation=True,max_length=4096)model_inputs = {7 unmodified linesskip_special_tokens=True)def generate():with torch.no_grad():model.generate(**model_inputs,streamer=streamer,max_new_tokens=180,do_sample=True,temperature=0.7,top_p=0.9,repetition_penalty=1.1,pad_token_id=tokenizer.eos_token_id,eos_token_id=tokenizer.eos_token_id)thread = Thread(target=generate)thread.start()24 unmodified linesline = line.strip()if line.startswith("TITLE:"):title = line.replace("TITLE:", "").strip()elif line.startswith("DESCRIPTION:"):description = line.replace("DESCRIPTION:", "").strip()elif line.startswith("BUTTON:"):button = line.replace("BUTTON:", "").strip()elif line.startswith("PRIMARY_COLOR:"):primary_color = line.replace("PRIMARY_COLOR:", "").strip()elif line.startswith("BACKGROUND:"):background = line.replace("BACKGROUND:", "").strip()final_html = BASE_TEMPLATE8 unmodified lines9101112131415161718192021222324252627282930313233343536373839402 unmodified lines434445464748495051525354555657585960616263646566671 unmodified line697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091 unmodified line1111121131141151161171181191201211221231241251261277 unmodified lines13513613713813914014114214314414514614714814915015115215315415515624 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102118 unmodified linesimport torchimport timeimport randomimport ostorch.set_grad_enabled(False)torch.backends.cuda.matmul.allow_tf32 = Truetorch.backends.cudnn.allow_tf32 = Trueapp = FastAPI()MODEL_NAME = "meta-llama/Llama-3.2-1B-Instruct"tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)model = AutoModelForCausalLM.from_pretrained(MODEL_NAME,torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,low_cpu_mem_usage=True,device_map="auto")model.eval()if tokenizer.pad_token is None:tokenizer.pad_token = tokenizer.eos_tokenTEMPLATES = ["templates/landing1.html","templates/landing2.html",2 unmodified linesULTIMA_REQUEST = {}MAX_HISTORY = 4MAX_INPUT_CHARS = 1200MAX_INPUT_TOKENS = 1024MAX_NEW_TOKENS = 120SYSTEM_PROMPT = ("Generate website content. ""Return ONLY these fields:\n""TITLE:\n""DESCRIPTION:\n""BUTTON:\n""PRIMARY_COLOR:\n""BACKGROUND:\n")@app.get("/")async def root():return {"status": "ok"}@app.post("/chat")async def chat(request: Request):1 unmodified lineahora = time.time()if ip in ULTIMA_REQUEST:if ahora - ULTIMA_REQUEST[ip] < 3:return {"response": "Rate limit"}ULTIMA_REQUEST[ip] = ahoratry:data = await request.json()historial = data.get("historial", [])[-MAX_HISTORY:]except:return {"response": "Invalid JSON"}if not historial:return {"response": "Empty history"}ultimo = historial[-1]if ultimo.get("role") != "user":return {"response": "Invalid role"}user_prompt = str(ultimo.get("content", ""))[:MAX_INPUT_CHARS]template_path = random.choice(TEMPLATES)if not os.path.exists(template_path):return {"response": "Template not found"}with open(template_path, "r", encoding="utf-8") as f:BASE_TEMPLATE = f.read()messages = [{"role": "system","content": SYSTEM_PROMPT},{"role": "user",1 unmodified line}]prompt = tokenizer.apply_chat_template(messages,tokenize=False,add_generation_prompt=True)model_inputs = tokenizer(prompt,return_tensors="pt",truncation=True,max_length=MAX_INPUT_TOKENS)model_inputs = {7 unmodified linesskip_special_tokens=True)generation_kwargs = dict(**model_inputs,streamer=streamer,max_new_tokens=MAX_NEW_TOKENS,do_sample=True,temperature=0.65,top_p=0.9,repetition_penalty=1.05,use_cache=True,pad_token_id=tokenizer.eos_token_id,eos_token_id=tokenizer.eos_token_id)def generate():with torch.inference_mode():model.generate(**generation_kwargs)thread = Thread(target=generate)thread.start()24 unmodified linesline = line.strip()if line.startswith("TITLE:"):title = line.replace("TITLE:", "").strip()[:80]elif line.startswith("DESCRIPTION:"):description = line.replace("DESCRIPTION:","").strip()[:220]elif line.startswith("BUTTON:"):button = line.replace("BUTTON:","").strip()[:40]elif line.startswith("PRIMARY_COLOR:"):primary_color = line.replace("PRIMARY_COLOR:","").strip()[:30]elif line.startswith("BACKGROUND:"):background = line.replace("BACKGROUND:","").strip()[:120]final_html = BASE_TEMPLATE
app.py+81-44