kevinlu1248 commited on
Commit
8e147a8
·
verified ·
1 Parent(s): 7c8b294

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +62 -39
src/streamlit_app.py CHANGED
@@ -1,40 +1,63 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
5
-
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import html
 
 
2
  import streamlit as st
3
+ from transformers import AutoTokenizer
4
+ import colorsys
5
+
6
+ st.set_page_config(layout="wide", page_title="Text Tokenizer")
7
+
8
+ def get_random_color(token_id):
9
+ # Generate a color based on the token id to ensure consistency
10
+ hue = (hash(str(token_id)) % 1000) / 1000.0
11
+ return f"hsla({int(hue * 360)}, 70%, 30%, 70%)"
12
+
13
+ def load_tokenizer(model_name="Qwen/Qwen2.5-Coder-7B-Instruct"):
14
+ if 'tokenizer' not in st.session_state:
15
+ st.session_state.tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
16
+ return st.session_state.tokenizer
17
+
18
+ st.title("Text Tokenizer")
19
+ selected_model = "Qwen/Qwen2.5-Coder-7B-Instruct"
20
+
21
+ # Load tokenizer based on selection
22
+ try:
23
+ tokenizer = load_tokenizer(selected_model)
24
+ st.success(f"Loaded tokenizer: {selected_model}")
25
+ except Exception as e:
26
+ st.error(f"Failed to load tokenizer: {e}")
27
+ st.stop()
28
+
29
+ # Input text area
30
+ input_text = st.text_area("Enter text to tokenize", height=200)
31
+
32
+ # Tokenize button
33
+ if st.button("Tokenize") and input_text:
34
+ tokens = tokenizer.encode(input_text)
35
+ st.write(f"Total tokens: {len(tokens)}")
36
+
37
+ # Generate colored text visualization
38
+ result = ""
39
+ prev_tokens = []
40
+ prev_string = ""
41
+
42
+ for token in tokens:
43
+ color = get_random_color(token)
44
+ current_string = tokenizer.decode(prev_tokens + [token])
45
+ prev_tokens.append(token)
46
+ current_delta = current_string[len(prev_string):]
47
+ prev_string = current_string
48
+
49
+ current_delta = html.escape(current_delta)
50
+ current_delta = (current_delta
51
+ .replace("\n", "↵<br/>")
52
+ .replace(" ", "&nbsp;")
53
+ .replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;"))
54
+
55
+ result += f'<span style="background-color: {color};">{current_delta}</span>'
56
+
57
+ st.html(f'<pre style="background-color: #222; padding: 10px; font-family: Courier, monospace;">{result}</pre>')
58
+
59
+ # Show raw tokens (optional)
60
+ with st.expander("View raw tokens"):
61
+ token_strings = [tokenizer.decode([t]) for t in tokens]
62
+ for i, (token_id, token_str) in enumerate(zip(tokens, token_strings)):
63
+ st.write(f"{i}: Token ID {token_id} → '{token_str}'")