skanderovitch commited on
Commit
b0037ca
·
verified ·
1 Parent(s): e90d339

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +181 -0
app.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import itertools
3
+ from sentence_transformers import SentenceTransformer
4
+ from sklearn.metrics.pairwise import cosine_similarity
5
+ import pandas as pd
6
+ import numpy as np
7
+ from collections import defaultdict
8
+
9
+ # text = """Economy
10
+ # Labour Party: Aim to deliver economic stability through growth and tough spending rules? (The Speaker)?.
11
+ # Conservative Party: Focus on economic growth by reducing debt and creating jobs? (theweek)?? (The Speaker)?.
12
+ # Liberal Democrats: Promote a fair and innovative economy with opportunities for all? (The Speaker)?.
13
+ # Scottish National Party (SNP): Advocate for full tax devolution to boost the Scottish economy? (theweek)?.
14
+ # Green Party: Invest in a green economic transformation to create sustainable jobs? (The Speaker)?.
15
+ # Reform UK: Aim to stimulate growth by reducing taxes and government spending? (theweek)?? (The Speaker)?.
16
+ # Taxation
17
+ # Labour Party: Propose to raise funds by taxing private schools, clamping down on tax underpayment, and a windfall tax on oil and gas companies? (theweek)?.
18
+ # Conservative Party: Plan to cut National Insurance and maintain lower personal taxes? (theweek)?.
19
+ # Liberal Democrats: Advocate for fair taxation and investments in public services? (The Speaker)?.
20
+ # Scottish National Party (SNP): Support windfall taxes on businesses and full tax power devolution? (theweek)?.
21
+ # Green Party: Propose new taxes on assets worth over £10 million and carbon tax? (The Speaker)?.
22
+ # Reform UK: Plan to raise the income tax threshold, scrap inheritance tax on smaller estates, and cut VAT on energy bills? (theweek)?? (The Speaker)?.
23
+ # Debt
24
+ # Labour Party: Aim to keep national debt under control through economic growth? (The Speaker)?.
25
+ # Conservative Party: Focus on reducing national debt as a key priority? (The Speaker)?.
26
+ # Liberal Democrats: Promote a sustainable approach to managing national debt? (The Speaker)?.
27
+ # Scottish National Party (SNP): Push for additional funding and economic autonomy to manage debt better? (theweek)?.
28
+ # Green Party: Invest heavily in green initiatives while aiming to manage debt sustainably? (The Speaker)?.
29
+ # Reform UK: Plan to reduce government spending to manage and reduce debt? (theweek)?.
30
+ # Inflation
31
+ # Labour Party: Aim to keep inflation low through economic stability measures? (The Speaker)?.
32
+ # Conservative Party: Prioritize halving inflation as a main economic goal? (The Speaker)?.
33
+ # Liberal Democrats: Focus on maintaining low inflation through fair economic policies? (The Speaker)?.
34
+ # Scottish National Party (SNP): Call for more funding to address inflationary pressures? (theweek)?.
35
+ # Green Party: Promote economic policies that balance environmental investment with controlling inflation? (The Speaker)?.
36
+ # Reform UK: Aim to lower inflation by cutting taxes and reducing energy costs? (theweek)?.
37
+ # Healthcare
38
+ # Labour Party: Plan to reduce NHS waiting times and invest in health infrastructure? (The Speaker)?.
39
+ # Conservative Party: Focus on cutting NHS waiting lists and improving healthcare services? (The Speaker)?.
40
+ # Liberal Democrats: Promise to improve access to GPs and emergency dental care? (theweek)?? (The Speaker)?.
41
+ # Scottish National Party (SNP): Demand increased NHS funding and better healthcare services? (theweek)?.
42
+ # Green Party: Propose major NHS investment and immediate pay rises for NHS staff? (The Speaker)?.
43
+ # Reform UK: Aim to achieve zero waiting lists and exempt healthcare workers from basic income tax? (theweek)?.
44
+ # Energy
45
+ # Labour Party: Establish Great British Energy, a new publicly-owned clean power company? (The Speaker)?.
46
+ # Conservative Party: Continue investing in energy security and diversification? (theweek)?.
47
+ # Liberal Democrats: Invest in renewable energy to generate 80% of electricity from renewables by the next decade? (The Speaker)?.
48
+ # Scottish National Party (SNP): Support re-entry into the EU single market to boost energy trade? (theweek)?.
49
+ # Green Party: Push for a green energy transformation, nationalizing major energy companies? (The Speaker)?.
50
+ # Reform UK: Increase drilling for gas and oil, scrapping net-zero plans to lower energy bills? (theweek)?.
51
+ # Environment
52
+ # Labour Party: Aim to make Britain a clean energy superpower? (The Speaker)?.
53
+ # Conservative Party: Continue current environmental policies with a focus on balanced growth? (theweek)?.
54
+ # Liberal Democrats: Promote a flourishing environment with fair access to nature? (The Speaker)?.
55
+ # Scottish National Party (SNP): Advocate for stronger environmental protections and policies? (theweek)?.
56
+ # Green Party: Focus on extensive environmental legislation and investment in green infrastructure? (The Speaker)?.
57
+ # Reform UK: Oppose current green policies and focus on traditional energy sources? (theweek)?.
58
+ # Security
59
+ # Labour Party: Strengthen border security and crack down on antisocial behavior? (The Speaker)?.
60
+ # Conservative Party: Implement mandatory national service and continue the Rwanda immigration scheme? (The Speaker)?.
61
+ # Liberal Democrats: Ensure fair access to security and justice for all? (The Speaker)?.
62
+ # Scottish National Party (SNP): Focus on unifying Scotland's security policies and practices? (The Speaker)?.
63
+ # Green Party: Promote community-based security measures and social justice? (The Speaker)?.
64
+ # Reform UK: Establish a new department for immigration and enhance border security? (theweek)?.
65
+ # Education
66
+ # Labour Party: Recruit 6,500 new teachers and improve educational infrastructure? (The Speaker)?.
67
+ # Conservative Party: Replace A-Levels with a new ‘Advanced British Standard’ and ensure continuous math education until age 18? (theweek)?? (The Speaker)?.
68
+ # Liberal Democrats: Increase school and college funding per pupil above the rate of inflation and lower the voting age to 16? (theweek)?? (The Speaker)?.
69
+ # Scottish National Party (SNP): Focus on improving access to quality education and advocating for full devolution of educational powers? (theweek)?.
70
+ # Green Party: Support comprehensive educational reforms including increased funding and nationalizing education services? (The Speaker)?.
71
+ # Reform UK: Reform educational standards, introduce patriotic curriculum, and eliminate "woke" ideologies from schools? (theweek)?? (The Speaker)?.
72
+ # Pensions
73
+ # Labour Party: No specific changes to pensions mentioned in the available manifestos? (The Speaker)?.
74
+ # Conservative Party: Maintain the triple lock system for pensions, ensuring they rise with inflation, wage growth, or 2.5%, whichever is highest? (theweek)?? (The Speaker)?.
75
+ # Liberal Democrats: No specific changes to pensions mentioned in the available manifestos? (The Speaker)?.
76
+ # Scottish National Party (SNP): Demand full devolution of pension powers to Scotland? (theweek)?.
77
+ # Green Party: No specific changes to pensions mentioned in the available manifestos? (The Speaker)?.
78
+ # Reform UK: No specific changes to pensions mentioned in the available manifestos? (theweek)?.
79
+ # Housing
80
+ # Labour Party: Commit to building more affordable housing and upgrading existing homes? (The Speaker)?.
81
+ # Conservative Party: Build 1.6 million new homes and support first-time buyers with government-backed mortgages? (theweek)?? (The Speaker)?.
82
+ # Liberal Democrats: Build 380,000 new homes annually, including 150,000 social housing units? (theweek)?? (The Speaker)?.
83
+ # Scottish National Party (SNP): Focus on increasing spending to provide more social housing in Scotland? (theweek)?.
84
+ # Green Party: Provide 150,000 new social homes every year and improve home insulation? (The Speaker)?.
85
+ # Reform UK: No specific housing policies mentioned in the available manifestos? (theweek)?? (The Speaker)?.
86
+ # Immigration
87
+ # Labour Party: Strengthen border security and crack down on illegal immigration? (The Speaker)?.
88
+ # Conservative Party: Continue with the Rwanda immigration scheme and introduce mandatory national service? (theweek)?? (The Speaker)?.
89
+ # Liberal Democrats: Provide safe and legal routes for asylum seekers and reform the immigration system to be merit-based? (theweek)?? (The Speaker)?.
90
+ # Scottish National Party (SNP): Advocate for humane immigration policies and support rejoining the EU single market? (theweek)?.
91
+ # Green Party: Support fair immigration policies and provide better support for asylum seekers? (The Speaker)?.
92
+ # Reform UK: Implement a four-point plan to curb illegal immigration and leave the European Convention on Human Rights? (theweek)?? (The Speaker)?."""
93
+
94
+
95
+
96
+ # data = []
97
+
98
+ # for line in text.split('\n'):
99
+ # new_theme = line.strip().split()
100
+ # if len(new_theme) == 1:
101
+ # theme = new_theme[0]
102
+ # continue
103
+ # party, position = line.strip().split(': ')
104
+ # position = position.split('?')[0]
105
+ # data.append([theme,party,position])
106
+ # data = pd.DataFrame(data,columns='theme party position'.split()).set_index(['theme','party'])['position'].unstack()
107
+ # data.to_parquet('./data.parquet')
108
+ data = pd.read_parquet('./data.parquet')
109
+
110
+ # # Load a pre-trained model
111
+ # model = SentenceTransformer('all-MiniLM-L6-v2')
112
+
113
+ # # Define your sentences
114
+ # sentences = data.stack().to_list()
115
+
116
+ # # Generate embeddings
117
+ # embeddings = model.encode(sentences)
118
+
119
+ # embeddings = pd.DataFrame([[embedding] for embedding in embeddings],index=data.stack().index,columns=['embedding'])['embedding'].unstack()
120
+ # embeddings.to_parquet('./embeddings.parquet')
121
+ embeddings = pd.read_parquet('./embeddings.parquet')
122
+
123
+ # similarities = []
124
+ # for theme in embeddings.index:
125
+ # print(theme)
126
+ # for p1,p2 in itertools.combinations(embeddings.columns,2):
127
+ # similarity = cosine_similarity([embeddings.loc[theme,p1]], [embeddings.loc[theme,p2]])[0][0]
128
+ # similarities.append([theme,p1,p2,similarity])
129
+ # similarities.append([theme,p2,p1,similarity])
130
+
131
+
132
+ # similarities = pd.DataFrame(similarities,columns = 'theme party1 party2 similarity'.split()).set_index('theme party1 party2'.split())['similarity'].reset_index()
133
+ # similarities.to_parquet('./similarities.parquet')
134
+ similarities = pd.read_parquet('./similarities.parquet')
135
+
136
+ # similarities.loc[('Debt',slice(None),slice(None))].reset_index()
137
+
138
+
139
+
140
+
141
+
142
+ st.title("Do you know your political parties?")
143
+
144
+
145
+ parties = st.multiselect(
146
+ "Which parties do you choose?",
147
+ list(data.columns),
148
+ list(data.columns))
149
+
150
+ themes = st.multiselect(
151
+ "Which themes matter to you?",
152
+ list(data.index),
153
+ list(data.index))
154
+
155
+ st.write("You selected:", themes)
156
+
157
+
158
+ subset = embeddings.loc[themes,parties]
159
+ X = np.array([array for array in subset.T.apply(lambda l: np.concatenate(l).ravel(), axis=1)])
160
+
161
+ from sklearn.manifold import Isomap
162
+ from sklearn.decomposition import PCA
163
+
164
+ model = PCA(n_components=2)
165
+ projection = model.fit_transform(X)
166
+
167
+
168
+ import plotly.express as px
169
+
170
+
171
+ projection = pd.DataFrame(projection,columns=['x','y'])
172
+ projection['text'] = parties
173
+ projection['color'] = parties
174
+ projection['hover'] = data.loc[themes,parties].T.apply(lambda l: '<br>'.join(l.tolist()),axis=1).values
175
+ projection
176
+ fig = px.scatter(projection,x='x', y='y', text='text', color='text', hover_data=["hover"])
177
+ fig.update_traces(marker=dict(size=12,
178
+ line=dict(width=2,
179
+ color='DarkSlateGrey')),
180
+ selector=dict(mode='markers'),)
181
+ st.plotly_chart(fig)