berndf commited on
Commit
08f0b45
·
verified ·
1 Parent(s): 38656f5
Files changed (1) hide show
  1. app.py +112 -51
app.py CHANGED
@@ -1,64 +1,125 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
 
8
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- messages.append({"role": "user", "content": message})
 
27
 
28
- response = ""
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
41
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
 
 
 
 
59
  ],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  )
61
 
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
+ import streamlit as st
2
+ from transformers import AutoTokenizer, AutoModel
3
+ from sklearn.decomposition import PCA
4
+ import torch
5
+ import numpy as np
6
+ import plotly.graph_objects as go
7
+ import math
8
 
9
+ # Load transformer model + tokenizer..
10
+ @st.cache_resource
11
+ def load_model():
12
+ tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
13
+ model = AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
14
+ return tokenizer, model
15
 
16
+ tokenizer, model = load_model()
17
 
18
+ # Encode using mean pooling
19
+ def encode_texts(texts):
20
+ with torch.no_grad():
21
+ inputs = tokenizer(texts, padding=True, truncation=True, return_tensors="pt")
22
+ output = model(**inputs)
23
+ mask = inputs["attention_mask"].unsqueeze(-1).expand(output.last_hidden_state.shape).float()
24
+ pooled = torch.sum(output.last_hidden_state * mask, dim=1) / mask.sum(dim=1)
25
+ return pooled.cpu().numpy()
 
26
 
27
+ # Session state init
28
+ if "submitted_text" not in st.session_state:
29
+ st.session_state.submitted_text = """BMW
30
+ Porsche
31
+ Mercedes
32
+ Coffee
33
+ Tea
34
+ Water
35
+ Germany
36
+ Italy
37
+ Brazil
38
+ Violin
39
+ Drums
40
+ Trumpet
41
+ Man
42
+ Women
43
+ Child"""
44
 
45
+ # UI layout
46
+ col1, col2 = st.columns([1, 3])
47
 
48
+ with col1:
49
+ st.title("🧠 Embedding Input")
50
 
51
+ with st.form(key="embedding_input_form"):
52
+ st.form_submit_button("✅ Submit Text")
53
+ st.text_area(
54
+ label="Enter words (one per line)",
55
+ key="submitted_text",
56
+ height=400,
57
+ )
 
58
 
59
+ texts = [t.strip() for t in st.session_state.submitted_text.split("\n") if t.strip()]
60
+ if len(texts) < 3:
61
+ st.warning("Please enter at least three words.")
62
+ st.stop()
63
 
64
+ embeddings = encode_texts(texts)
65
+ coords = PCA(n_components=3).fit_transform(embeddings)
66
 
67
+ # Rotation frames
68
+ frames = []
69
+ for angle in range(0, 360, 2):
70
+ rad = math.radians(angle)
71
+ camera = dict(eye=dict(x=2 * math.cos(rad), y=2 * math.sin(rad), z=0.7))
72
+ frames.append(go.Frame(layout=dict(scene_camera=camera)))
73
+
74
+ # Plotly figure with animation controls
75
+ fig = go.Figure(
76
+ data=[
77
+ go.Scatter3d(
78
+ x=coords[:, 0],
79
+ y=coords[:, 1],
80
+ z=coords[:, 2],
81
+ mode="markers+text",
82
+ text=texts,
83
+ textposition="top center",
84
+ textfont=dict(color="black"),
85
+ marker=dict(size=6),
86
+ )
87
  ],
88
+ layout=go.Layout(
89
+ title="3D Embedding Projection",
90
+ scene=dict(
91
+ xaxis=dict(title="X", showbackground=True, backgroundcolor="rgba(255,0,0,0.4)"),
92
+ yaxis=dict(title="Y", showbackground=True, backgroundcolor="rgba(0,255,0,0.4)"),
93
+ zaxis=dict(title="Z", showbackground=True, backgroundcolor="rgba(0,0,255,0.4)"),
94
+ ),
95
+ updatemenus=[
96
+ dict(
97
+ type="buttons",
98
+ showactive=False,
99
+ buttons=[
100
+ dict(
101
+ label="🔄 Rotate",
102
+ method="animate",
103
+ args=[
104
+ None,
105
+ dict(
106
+ frame=dict(duration=50, redraw=True),
107
+ transition=dict(duration=0),
108
+ fromcurrent=True,
109
+ mode="immediate"
110
+ )
111
+ ],
112
+ )
113
+ ],
114
+ x=0.05,
115
+ y=0.9
116
+ )
117
+ ],
118
+ margin=dict(l=0, r=0, b=0, t=30),
119
+ ),
120
+ frames=frames
121
  )
122
 
123
+ with col2:
124
+ st.title("📊 3D Plot")
125
+ st.plotly_chart(fig, use_container_width=True)