Spaces:
Sleeping
Sleeping
File size: 9,690 Bytes
5f77bb2 288997f 5f77bb2 288997f 5f77bb2 288997f 5f77bb2 288997f 5f77bb2 288997f 5f77bb2 288997f 5f77bb2 288997f 5f77bb2 288997f 5f77bb2 288997f 5f77bb2 288997f 5f77bb2 288997f 5f77bb2 288997f 5f77bb2 288997f 5f77bb2 288997f 5f77bb2 288997f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 |
import streamlit as st
import pandas as pd
import subprocess
import time
import random
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, models
from transformers import BertTokenizer, TFBertModel
import requests
import matplotlib.pyplot as plt
from io import BytesIO
import base64
# ---------------------------- Helper Function for NER Data ----------------------------
def generate_ner_data():
# Sample NER data for different entities
data_person = [{"text": f"Person example {i}", "entities": [{"entity": "Person", "value": f"Person {i}"}]} for i in range(1, 21)]
data_organization = [{"text": f"Organization example {i}", "entities": [{"entity": "Organization", "value": f"Organization {i}"}]} for i in range(1, 21)]
data_location = [{"text": f"Location example {i}", "entities": [{"entity": "Location", "value": f"Location {i}"}]} for i in range(1, 21)]
data_date = [{"text": f"Date example {i}", "entities": [{"entity": "Date", "value": f"Date {i}"}]} for i in range(1, 21)]
data_product = [{"text": f"Product example {i}", "entities": [{"entity": "Product", "value": f"Product {i}"}]} for i in range(1, 21)]
# Create a dictionary of all NER examples
ner_data = {
"Person": data_person,
"Organization": data_organization,
"Location": data_location,
"Date": data_date,
"Product": data_product
}
return ner_data
# ---------------------------- Fun NER Data Function ----------------------------
def ner_demo():
st.header("π€ LLM NER Model Demo π΅οΈββοΈ")
# Generate NER data
ner_data = generate_ner_data()
# Pick a random entity type to display
entity_type = random.choice(list(ner_data.keys()))
st.subheader(f"Here comes the {entity_type} entity recognition, ready to show its magic! π©β¨")
# Select a random record to display
example = random.choice(ner_data[entity_type])
st.write(f"Analyzing: *{example['text']}*")
# Display recognized entity
for entity in example["entities"]:
st.success(f"π Found a {entity['entity']}: **{entity['value']}**")
# A bit of rhyme to lighten up the task
st.write("There once was an AI so bright, π")
st.write("It could spot any name in sight, ποΈ")
st.write("With a click or a tap, it put on its cap, π©")
st.write("And found entities day or night! π")
# ---------------------------- Helper: Text Data Augmentation ----------------------------
def word_subtraction(text):
"""Subtract words at random positions."""
words = text.split()
if len(words) > 2:
index = random.randint(0, len(words) - 1)
words.pop(index)
return " ".join(words)
def word_recombination(text):
"""Recombine words with random shuffling."""
words = text.split()
random.shuffle(words)
return " ".join(words)
# ---------------------------- ML Model Building ----------------------------
def build_small_model(input_shape):
model = models.Sequential()
model.add(layers.Dense(64, activation='relu', input_shape=(input_shape,)))
model.add(layers.Dense(32, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
return model
# ---------------------------- TensorFlow and Keras Integration ----------------------------
def train_model_demo():
st.header("π§ͺ Let's Build a Mini TensorFlow Model π")
# Generate random synthetic data for simplicity
data_size = 100
X_train = np.random.rand(data_size, 10)
y_train = np.random.randint(0, 2, size=data_size)
st.write(f"π **Data Shape**: {X_train.shape}, with binary target labels.")
# Build the model
model = build_small_model(X_train.shape[1])
st.write("π§ **Model Summary**:")
st.text(model.summary())
# Train the model
st.write("π **Training the model...**")
history = model.fit(X_train, y_train, epochs=5, batch_size=16, verbose=0)
# Output training results humorously
st.success("π Training completed! The model now knows its ABCs... or 1s and 0s at least! π")
st.write(f"Final training loss: **{history.history['loss'][-1]:.4f}**, accuracy: **{history.history['accuracy'][-1]:.4f}**")
st.write("Fun fact: This model can make predictions on binary outcomes like whether a cat will sleep or not. π±π€")
# ---------------------------- Additional Useful Examples ----------------------------
def code_snippet_sharing():
st.header("π€ Code Snippet Sharing with Syntax Highlighting π₯οΈ")
code = '''def hello_world():
print("Hello, world!")'''
st.code(code, language='python')
st.write("Developers often need to share code snippets. Here's how you can display code with syntax highlighting in Streamlit! π")
def file_uploader_example():
st.header("π File Uploader Example π€")
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
if uploaded_file is not None:
data = pd.read_csv(uploaded_file)
st.write("π File uploaded successfully!")
st.dataframe(data.head())
st.write("Use file uploaders to allow users to bring their own data into your app! π")
def matplotlib_plot_example():
st.header("π Matplotlib Plot Example π")
# Generate data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create plot
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Sine Wave')
st.pyplot(fig)
st.write("You can integrate Matplotlib plots directly into your Streamlit app! π¨")
def cache_example():
st.header("β‘ Streamlit Cache Example π")
@st.cache
def expensive_computation(a, b):
time.sleep(2)
return a * b
st.write("Let's compute something that takes time...")
result = expensive_computation(2, 21)
st.write(f"The result is {result}. But thanks to caching, it's faster the next time! β‘")
# ---------------------------- Display Tweet ----------------------------
def display_tweet():
st.header("π¦ Tweet Spotlight: TensorFlow and Transformers π")
tweet_html = '''
<blockquote class="twitter-tweet">
<p lang="en" dir="ltr">
Just tried integrating TensorFlow with Transformers for my latest LLM project! π
The synergy between them is incredible. TensorFlow's flexibility combined with Transformers' power boosts Generative AI capabilities to new heights! π₯ #TensorFlow #Transformers #AI #MachineLearning
</p>— AI Enthusiast (@ai_enthusiast) <a href="https://twitter.com/ai_enthusiast/status/1234567890">September 30, 2024</a>
</blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
'''
st.components.v1.html(tweet_html, height=300)
st.write("Tweets can be embedded to showcase social proof or updates. Isn't that neat? π€")
# ---------------------------- Header and Introduction ----------------------------
st.set_page_config(page_title="LLMs and Tiny ML Models", page_icon="π€", layout="wide", initial_sidebar_state="expanded")
st.title("π€π LLMs and Tiny ML Models with TensorFlow ππ€")
st.markdown("This app demonstrates how to build small TensorFlow models, solve common developer problems, and augment text data using word subtraction and recombination strategies.")
st.markdown("---")
# ---------------------------- Main Navigation ----------------------------
st.sidebar.title("Navigation")
options = st.sidebar.radio("Go to", ['NER Demo', 'TensorFlow Model', 'Text Augmentation', 'Code Sharing', 'File Uploader', 'Matplotlib Plot', 'Streamlit Cache', 'Tweet Spotlight'])
if options == 'NER Demo':
if st.button('π§ͺ Run NER Model Demo'):
ner_demo()
else:
st.write("Click the button above to start the AI NER magic! π©β¨")
elif options == 'TensorFlow Model':
if st.button('π Build and Train a TensorFlow Model'):
train_model_demo()
elif options == 'Text Augmentation':
st.subheader("π² Fun Text Augmentation with Random Strategies π²")
input_text = st.text_input("Enter a sentence to see some augmentation magic! β¨", "TensorFlow is awesome!")
if st.button("Subtract Random Words"):
st.write(f"Original: **{input_text}**")
st.write(f"Augmented: **{word_subtraction(input_text)}**")
if st.button("Recombine Words"):
st.write(f"Original: **{input_text}**")
st.write(f"Augmented: **{word_recombination(input_text)}**")
st.write("Try both and see how the magic works! π©β¨")
elif options == 'Code Sharing':
code_snippet_sharing()
elif options == 'File Uploader':
file_uploader_example()
elif options == 'Matplotlib Plot':
matplotlib_plot_example()
elif options == 'Streamlit Cache':
cache_example()
elif options == 'Tweet Spotlight':
display_tweet()
st.markdown("---")
# ---------------------------- Footer and Additional Resources ----------------------------
st.subheader("π Additional Resources")
st.markdown("""
- [Official Streamlit Documentation](https://docs.streamlit.io/)
- [TensorFlow Documentation](https://www.tensorflow.org/api_docs)
- [Transformers Documentation](https://huggingface.co/docs/transformers/index)
- [Streamlit Cheat Sheet](https://docs.streamlit.io/library/cheatsheet)
- [Matplotlib Documentation](https://matplotlib.org/stable/contents.html)
""")
# ---------------------------- requirements.txt ----------------------------
st.markdown('''
Reference Libraries:
plaintext
streamlit
pandas
numpy
tensorflow
transformers
matplotlib
''') |