shrestha-prabin commited on
Commit
4e977d5
·
verified ·
1 Parent(s): 06ca9ef

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +55 -37
src/streamlit_app.py CHANGED
@@ -1,40 +1,58 @@
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 matplotlib.pyplot as plt
2
+ import nltk
3
  import numpy as np
4
  import pandas as pd
5
+ import seaborn as sns
6
  import streamlit as st
7
+ from nltk.tokenize import word_tokenize
8
+
9
+ nltk.download("punkt")
10
+ nltk.download("punkt_tab")
11
+
12
+ st.title("📊 Bayesian Token Co-occurrence Simulator")
13
+
14
+ # User input
15
+ user_input = st.text_area(
16
+ "✍️ Enter your training sentences (one per line):",
17
+ """
18
+ fido loves the red ball
19
+ timmy and fido go to the park
20
+ fido and timmy love to play
21
+ the red ball is timmy's favorite toy
22
+ """,
23
+ )
24
+
25
+ sentences = user_input.strip().split("\n")
26
+ tokenized = [word_tokenize(s.lower()) for s in sentences if s.strip()]
27
+ vocab = sorted(set(word for sentence in tokenized for word in sentence))
28
+ token2idx = {word: i for i, word in enumerate(vocab)}
29
+ idx2token = {i: word for word, i in token2idx.items()}
30
+
31
+ # Co-occurrence matrix
32
+ window_size = 2
33
+ matrix = np.zeros((len(vocab), len(vocab)))
34
+
35
+ for sentence in tokenized:
36
+ for i, word in enumerate(sentence):
37
+ for j in range(
38
+ max(0, i - window_size), min(len(sentence), i + window_size + 1)
39
+ ):
40
+ if i != j:
41
+ matrix[token2idx[word]][token2idx[sentence[j]]] += 1
42
+
43
+ alpha = st.slider("🔧 Set Bayesian Prior (α smoothing)", 0.0, 2.0, 0.1)
44
+ posterior = matrix + alpha
45
+
46
+ df = pd.DataFrame(posterior, index=vocab, columns=vocab)
47
+ st.subheader("📈 Co-occurrence Heatmap")
48
+ fig, ax = plt.subplots(figsize=(10, 8))
49
+ sns.heatmap(df, annot=True, cmap="Blues", fmt=".1f", ax=ax)
50
+ st.pyplot(fig)
51
+
52
+ # Next-token prediction
53
+ selected_word = st.selectbox("🔮 Predict next token after:", vocab)
54
+ row = posterior[token2idx[selected_word]]
55
+ probs = row / row.sum()
56
+ prediction = np.random.choice(vocab, p=probs)
57
+
58
+ st.markdown(f"**Predicted next token:** `{prediction}`")