code: def generate_text_semantic(
      text,
      model,
      history_prompt=None,
      temp=0.7,
      top_k=None,
      top_p=None,
      silent=False,
      min_eos_p=0.2,
      max_gen_duration_s=None,
      allow_early_stop=True,
      base=None,
      use_kv_caching=True,
      **kwargs,  # pylint: disable=unused-argument
  ):
      """Generate semantic tokens from text.
  
      Args:
          text (str): The text to generate semantic tokens from.
          model (BarkModel): The BarkModel to use for generating the semantic tokens.
          history_prompt (tuple): A tuple of (semantic_history, coarse_history, fine_history) to use as a prompt for the generation.
          temp (float): The temperature to use for the generation.
          top_k (int): The number of top tokens to consider for the generation.
          top_p (float): The cumulative probability to consider for the generation.
          silent (bool): Whether to silence the tqdm progress bar.
          min_eos_p (float): The minimum probability to consider for the end of sentence token.
          max_gen_duration_s (float): The maximum duration in seconds to generate for.
          allow_early_stop (bool): Whether to allow the generation to stop early.
          base (tuple): A tuple of (semantic_history, coarse_history, fine_history) to use as a base for the generation.
          use_kv_caching (bool): Whether to use key-value caching for the generation.
          **kwargs: Additional keyword arguments. They are ignored.
  
      Returns:
          np.ndarray: The generated semantic tokens.
      """
      assert isinstance(text, str)
      text = _normalize_whitespace(text)
      assert len(text.strip()) > 0
      if all(v is not None for v in history_prompt) or base is not None:
          if history_prompt is not None:
              semantic_history = history_prompt[0]
          if base is not None:
              semantic_history = base[0]
          assert (
              isinstance(semantic_history, np.ndarray)
              and len(semantic_history.shape) == 1
              and len(semantic_history) > 0
              and semantic_history.min() >= 0
              and semantic_history.max()
              <= model.config.SEMANTIC_VOCAB_SIZE - 1
          )
      else:
          semantic_history = None
      encoded_text = (
          np.array(_tokenize(model.tokenizer, text))
          + model.config.TEXT_ENCODING_OFFSET
      )
      if len(encoded_text) > 256:
          p = round(
              (len(encoded_text) - 256) / len(encoded_text) * 100, 1
          )
          logger.warning(
              f"warning, text too long, lopping of last {p}%"
          )
          encoded_text = encoded_text[:256]
      encoded_text = np.pad(
          encoded_text,
          (0, 256 - len(encoded_text)),
          constant_values=model.config.TEXT_PAD_TOKEN,
          mode="constant",
      )
      if semantic_history is not None:
          semantic_history = semantic_history.astype(np.int64)
          # lop off if history is too long, pad if needed
          semantic_history = semantic_history[-256:]
          semantic_history = np.pad(
              semantic_history,
              (0, 256 - len(semantic_history)),
              constant_values=model.config.SEMANTIC_PAD_TOKEN,
              mode="constant",
          )
      else:
          semantic_history = np.array(
              [model.config.SEMANTIC_PAD_TOKEN] * 256
          )
      x = torch.from_numpy(
          np.hstack(
              [
                  encoded_text,
                  semantic_history,
                  np.array([model.config.SEMANTIC_INFER_TOKEN]),
              ]
          ).astype(np.int64)
      )[None]
      assert x.shape[1] == 256 + 256 + 1
      with inference_mode():
          x = x.to(model.device)
          n_tot_steps = 768
          # custom tqdm updates since we don't know when eos will occur
          pbar = tqdm.tqdm(disable=silent, total=100)
          pbar_state = 0
          tot_generated_duration_s = 0
          kv_cache = None
          for n in range(n_tot_steps):
              if use_kv_caching and kv_cache is not None:
                  x_input = x[:, [-1]]
              else:
                  x_input = x
              logits, kv_cache = model.semantic_model(
                  x_input,
                  merge_context=True,
                  use_cache=use_kv_caching,
                  past_kv=kv_cache,
              )
              relevant_logits = logits[
                  0, 0, : model.config.SEMANTIC_VOCAB_SIZE
              ]
              if allow_early_stop:
                  relevant_logits = torch.hstack(
                      (
                          relevant_logits,
                          logits[
                              0, 0, [model.config.SEMANTIC_PAD_TOKEN]
                          ],
                      )
                  )  # eos
              if top_p is not None:
                  # faster to convert to numpy
                  logits_device = relevant_logits.device
                  logits_dtype = relevant_logits.type()
                  relevant_logits = (
                      relevant_logits.detach()
                      .cpu()
                      .type(torch.float32)
                      .numpy()
                  )
                  sorted_indices = np.argsort(relevant_logits)[::-1]
                  sorted_logits = relevant_logits[sorted_indices]
                  cumulative_probs = np.cumsum(softmax(sorted_logits))
                  sorted_indices_to_remove = cumulative_probs > top_p
                  sorted_indices_to_remove[
                      1:
                  ] = sorted_indices_to_remove[:-1].copy()
                  sorted_indices_to_remove[0] = False
                  relevant_logits[
                      sorted_indices[sorted_indices_to_remove]
                  ] = -np.inf
                  relevant_logits = torch.from_numpy(relevant_logits)
                  relevant_logits = relevant_logits.to(
                      logits_device
                  ).type(logits_dtype)
              if top_k is not None:
                  v, _ = torch.topk(
                      relevant_logits,
                      min(top_k, relevant_logits.size(-1)),
                  )
                  relevant_logits[relevant_logits < v[-1]] = -float(
                      "Inf"
                  )
              probs = torch.softmax(relevant_logits / temp, dim=-1)
              item_next = torch.multinomial(probs, num_samples=1)
              if allow_early_stop and (
                  item_next == model.config.SEMANTIC_VOCAB_SIZE
                  or (min_eos_p is not None and probs[-1] >= min_eos_p)
              ):
                  # eos found, so break
                  pbar.update(100 - pbar_state)
                  break
              x = torch.cat((x, item_next[None]), dim=1)
              tot_generated_duration_s += (
                  1 / model.config.SEMANTIC_RATE_HZ
              )
              if (
                  max_gen_duration_s is not None
                  and tot_generated_duration_s > max_gen_duration_s
              ):
                  pbar.update(100 - pbar_state)
                  break
              if n == n_tot_steps - 1:
                  pbar.update(100 - pbar_state)
                  break
              del logits, relevant_logits, probs, item_next
              req_pbar_state = np.min(
                  [100, int(round(100 * n / n_tot_steps))]
              )
              if req_pbar_state > pbar_state:
                  pbar.update(req_pbar_state - pbar_state)
              pbar_state = req_pbar_state
          pbar.close()
          out = x.detach().cpu().numpy().squeeze()[256 + 256 + 1 :]
      assert all(out >= 0) and all(
          out < model.config.SEMANTIC_VOCAB_SIZE
      )
      clear_cuda_cache()
      return out
  
imports: import logging
  import os
  import re
  from glob import glob
  from typing import Dict, List
  import librosa
  import numpy
  import torch
  import torchaudio
  import tqdm
  from encodec.utils import convert_audio
  from scipy.special import softmax
  from torch.nn import functional
  from TTS.tts.layers.bark.hubert.hubert_manager import HubertManager
  from TTS.tts.layers.bark.hubert.kmeans_hubert import CustomHubert
  from TTS.tts.layers.bark.hubert.tokenizer import HubertTokenizer
  from TTS.tts.layers.bark.load_model import clear_cuda_cache, inference_mode
label_desc: Use image node_id 11 for calling a global function with example usage: generate_text_semantic(text, model, history_prompt, temp, top_k, top_p, silent, min_eos_p, max_gen_duration_s, allow_early_stop, base, use_kv_caching) and returns: out