gloignon commited on
Commit
f4d46f6
·
verified ·
1 Parent(s): 681310c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -0
app.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import pandas as pd
4
+ import plotly.express as px
5
+ from sklearn.decomposition import PCA
6
+ from sentence_transformers import SentenceTransformer
7
+
8
+ # Load pre-trained sentence transformer model
9
+ model = SentenceTransformer('all-MiniLM-L6-v2')
10
+
11
+ # Function to calculate embeddings and PCA
12
+ def compute_pca(texts):
13
+ # Generate embeddings
14
+ embeddings = model.encode(texts)
15
+
16
+ # Compute PCA
17
+ pca = PCA(n_components=2)
18
+ pca_result = pca.fit_transform(embeddings)
19
+
20
+ # Create DataFrame for visualization
21
+ df = pd.DataFrame({
22
+ 'Text': texts,
23
+ 'PC1': pca_result[:, 0],
24
+ 'PC2': pca_result[:, 1]
25
+ })
26
+
27
+ # Plot the PCA result
28
+ fig = px.scatter(df, x='PC1', y='PC2', text='Text', title='PCA of Text Embeddings')
29
+ return fig
30
+
31
+ # Define Gradio app layout and interactions
32
+ def text_editor_app():
33
+ with gr.Blocks() as demo:
34
+ # Text box to input texts
35
+ text_input = gr.Textbox(lines=10, placeholder="Enter or paste your texts here, one per line...", label="Text Inputs")
36
+
37
+ # Display the list of texts
38
+ texts = gr.Dataframe(headers=["Texts"], label="Text List", interactive=True)
39
+
40
+ # Button to process texts
41
+ submit_button = gr.Button("Compute Embeddings and PCA")
42
+
43
+ # Output plot
44
+ output_plot = gr.Plot(label="PCA Visualization")
45
+
46
+ # Define button click interaction
47
+ def process_texts(text_input):
48
+ # Split input texts by newline
49
+ text_list = text_input.strip().split('\n')
50
+ return gr.DataFrame.update(value=[[t] for t in text_list], row_count=len(text_list))
51
+
52
+ submit_button.click(fn=lambda x: compute_pca([t[0] for t in x]), inputs=texts, outputs=output_plot)
53
+ text_input.change(fn=process_texts, inputs=text_input, outputs=texts)
54
+
55
+ return demo
56
+
57
+ # Launch the app
58
+ text_editor_app().launch()