Spaces:
Runtime error
Runtime error
Update app.py
Browse files234 unmodified lines235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264234 unmodified linesdef 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 directlyoutputs = model(**inputs)embedding = outputs[0][:, 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_embeddingreturn np.zeros(model.config.hidden_size)def format_topics(topic_model, topic_counts):234 unmodified lines235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272234 unmodified linesdef get_embedding_for_text(text, tokenizer, model):"""Get embedding for complete text."""# First tokenize to get exact counttokens = tokenizer.tokenize(text)# Process in chunks of exactly 510 tokens (512 - 2 for CLS and SEP)chunk_size = 510chunk_embeddings = []for i in range(0, len(tokens), chunk_size):chunk = tokens[i:i + chunk_size]# Convert tokens back to textchunk_text = tokenizer.convert_tokens_to_string(chunk)# Now encode with special tokensencoded = tokenizer(chunk_text,return_tensors='pt',max_length=512,truncation=True,padding='max_length')# Move to deviceencoded = {k: v.to(model.device) for k, v in encoded.items()}# Get embeddingwith torch.no_grad():output = model(**encoded)embedding = output[0][:, 0, :].cpu().numpy()chunk_embeddings.append(embedding[0])# Combine all chunk embeddingsif chunk_embeddings:return np.mean(chunk_embeddings, axis=0)return np.zeros(model.config.hidden_size)def format_topics(topic_model, topic_counts):
app.py+23-15