Spaces:
Runtime error
Runtime error
Update app.py
Browse files233 unmodified lines234235236237238239240241242243244245246247248249250251252253254255256257258259260261233 unmodified linesreturn final_emotiondef get_embedding_for_text(text, tokenizer, model):"""Get embedding for complete text."""chunks = split_text(text)chunk_embeddings = []for chunk in chunks:inputs = tokenizer(chunk,return_tensors="pt",padding=True,truncation=True,max_length=512)inputs = {k: v.to(model.device) for k, v in inputs.items()}with torch.no_grad():# Access the first element of the tuple which contains the hidden statesoutputs = model(**inputs)[0]embedding = outputs[:, 0, :].cpu().numpy()chunk_embeddings.append(embedding[0])if chunk_embeddings:weights = np.array([len(chunk.split()) for chunk in chunks])weights = weights / weights.sum()weighted_embedding = np.average(chunk_embeddings, axis=0, weights=weights)return weighted_embedding233 unmodified lines234235236237238239240241242243244245246247248249250251252253254255256257258259260261262233 unmodified linesreturn final_emotiondef get_embedding_for_text(text, tokenizer, model):"""Get embedding for complete text while preserving all content."""# Split into optimal chunks of exactly 512 tokenstokenized_text = tokenizer.encode(text)chunks = [tokenized_text[i:i + 512] for i in range(0, len(tokenized_text), 512)]chunk_embeddings = []for chunk in chunks:inputs = tokenizer.encode(tokenizer.decode(chunk),return_tensors="pt",padding='max_length',max_length=512)inputs = inputs.to(model.device)with torch.no_grad():outputs = model(inputs)[0]embedding = outputs[:, 0, :].cpu().numpy()chunk_embeddings.append(embedding[0])if chunk_embeddings:# Weight each chunk based on its content lengthweights = np.array([len(chunk) for chunk in chunks])weights = weights / weights.sum()weighted_embedding = np.average(chunk_embeddings, axis=0, weights=weights)return weighted_embedding
app.py+11-10