File size: 13,620 Bytes
7658165
 
 
 
 
 
 
 
 
 
 
 
 
039bde1
7658165
039bde1
7658165
039bde1
 
 
d7cf785
039bde1
 
 
d7cf785
039bde1
 
 
 
 
 
 
 
 
 
 
 
 
7658165
039bde1
7658165
 
 
 
 
 
039bde1
7658165
039bde1
7658165
039bde1
 
 
 
 
 
 
 
 
7658165
 
039bde1
7658165
039bde1
7658165
039bde1
 
 
7658165
039bde1
 
 
7658165
 
039bde1
 
7658165
039bde1
 
d7cf785
039bde1
d7cf785
039bde1
 
 
d7cf785
039bde1
 
 
 
 
 
 
 
 
 
 
 
 
7658165
039bde1
7658165
 
039bde1
7658165
039bde1
7658165
039bde1
 
 
7658165
039bde1
 
 
7658165
 
 
039bde1
 
7658165
039bde1
 
 
d7cf785
039bde1
 
 
d7cf785
039bde1
 
 
 
 
 
 
 
 
 
 
 
 
7658165
039bde1
7658165
039bde1
 
 
 
 
7658165
039bde1
7658165
039bde1
 
 
7658165
039bde1
7658165
 
 
 
039bde1
7658165
039bde1
 
 
7658165
039bde1
 
7658165
 
039bde1
 
 
 
 
 
 
7658165
039bde1
 
 
 
7658165
039bde1
 
 
7658165
 
 
 
6ec5b94
 
 
 
7658165
 
 
adb850a
 
 
 
7658165
 
 
 
039bde1
7658165
 
 
 
 
 
 
bed3338
7658165
 
 
 
 
 
 
bed3338
7658165
bed3338
7658165
 
 
 
 
 
039bde1
 
7658165
42cd37c
 
 
 
7658165
039bde1
 
42cd37c
039bde1
7658165
42cd37c
7658165
 
 
039bde1
 
 
 
7658165
 
 
 
 
 
 
 
 
f566b01
7658165
 
 
 
 
f566b01
7658165
 
 
 
 
 
 
 
039bde1
f566b01
 
bacd5a5
7658165
 
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import gradio as gr
import pandas as pd
import re
import csv
import pandas as pd


def update_scores(winner, loser, k_factor=100):
  score_difference = int(k_factor/(winner/loser))
  winner += score_difference
  loser -= score_difference
  return winner, loser

def vote_startup(opponents_df):
  try:
    opponents_df = opponents_df[["elo_score",	"descriptor",	"opponent"]]
  except:
    opponents_df = pd.DataFrame(columns=['elo_score', 'descriptor', 'opponent'])
  if len(opponents_df)>0:
      if len(opponents_df)>10:
          slice_size = 4
          slice = int(len(opponents_df)/slice_size)
          sample = opponents_df[slice:(slice_size-1)*slice].sample(frac=1).iloc[0]
          opponent, descriptor = sample["opponent"], sample["descriptor"]
      else:
          sample = opponents_df.sample(frac=1).iloc[0]
          opponent, descriptor = sample["opponent"], sample["descriptor"]
  if len(opponents_df) > 1:
      # Randomly select a opponent to compare with
      sample = opponents_df.sample(frac=1)
      comparison_opponent = sample.iloc[0]
      if comparison_opponent['opponent'] == opponent and comparison_opponent['descriptor'] == descriptor:
        comparison_opponent = sample.iloc[1]
      first_df = opponents_df[opponents_df["opponent"]==opponent][opponents_df["descriptor"]==descriptor]
      first_string = first_df["opponent"].tolist()[0]+" - "+first_df["descriptor"].tolist()[0]
      second_df = comparison_opponent
      second_string = second_df["opponent"]+" - "+second_df["descriptor"]
      return f"Do you like '{descriptor} - {opponent}' better than '{comparison_opponent['descriptor']} - {comparison_opponent['opponent']}'?", first_string, second_string, display_rankings(opponents_df)
  else:
      return "Add some opponents to start voting!", "", "", display_rankings(opponents_df)

def clean_string(string):
  string = string.strip().replace("  "," ").lower()
  string = " ".join([x[0].upper()+x[1:] for x in string.split()])
  return string

def add_and_compare(descriptor, opponent, opponents_df):
    try:
      opponents_df = opponents_df[["elo_score",	"descriptor",	"opponent"]]
    except:
      opponents_df = pd.DataFrame(columns=['elo_score', 'descriptor', 'opponent'])
    if descriptor != "" and opponent != "":
        descriptor = clean_string(descriptor)
        opponent = clean_string(opponent)
        new_opponent = pd.DataFrame({'descriptor': [descriptor], 'opponent': [opponent], 'elo_score': [1000]})
        opponents_df = pd.concat([opponents_df, new_opponent], ignore_index=True)
        opponents_df.to_csv("opponents_df.csv")
    opponents_df = opponents_df[["elo_score", "descriptor", "opponent"]]
    return "", "", display_rankings(opponents_df)

# Function to update Elo ratings based on user's choice
def update_ratings_pos(first_string, second_string, opponents_df):
    try:
      opponents_df = opponents_df[["elo_score",	"descriptor",	"opponent"]]
    except:
      opponents_df = pd.DataFrame(columns=['elo_score', 'descriptor', 'opponent'])
    if len(opponents_df)==0:
      return "Add some opponents to start voting!", "", "", display_rankings(opponents_df)
    if first_string != "":
      opponents_df["combined"] = opponents_df["opponent"] + " - " + opponents_df["descriptor"]
      loser = opponents_df[opponents_df["combined"] == second_string]
      winner = opponents_df[opponents_df["combined"] == first_string]
      # Update Elo scores
      winner_score, loser_score = update_scores(winner['elo_score'].values[0], loser['elo_score'].values[0])
      opponents_df.at[winner.index[0], 'elo_score'] = winner_score
      opponents_df.at[loser.index[0], 'elo_score'] = loser_score

    opponents_df = opponents_df.sort_values(by='elo_score', ascending=False)
    opponents_df.to_csv("opponents_df.csv")

    if len(opponents_df)>10:
          slice_size = 4
          slice = int(len(opponents_df)/slice_size)
          sample = opponents_df[slice:(slice_size-1)*slice].sample(frac=1).iloc[0]
          opponent, descriptor = sample["opponent"], sample["descriptor"]
    else:
          sample = opponents_df.sample(frac=1).iloc[0]
          opponent, descriptor = sample["opponent"], sample["descriptor"]
    if len(opponents_df) > 1:
        # Randomly select a opponent to compare with
        sample = opponents_df.sample(frac=1)
        comparison_opponent = sample.iloc[0]
        if comparison_opponent['opponent'] == opponent and comparison_opponent['descriptor'] == descriptor:
          comparison_opponent = sample.iloc[1]
        first_df = opponents_df[opponents_df["opponent"]==opponent][opponents_df["descriptor"]==descriptor]
        first_string = first_df["opponent"].tolist()[0]+" - "+first_df["descriptor"].tolist()[0]
        second_df = comparison_opponent
        second_string = second_df["opponent"]+" - "+second_df["descriptor"]
        return f"Do you like '{descriptor} - {opponent}' better than '{comparison_opponent['descriptor']} - {comparison_opponent['opponent']}'?", first_string, second_string, display_rankings(opponents_df)
    else:
        return "Add some opponents to start voting!", "", "", display_rankings(opponents_df)

# Function to update Elo ratings based on user's choice
def update_ratings_neg(first_string, second_string, opponents_df):
    try:
      opponents_df = opponents_df[["elo_score",	"descriptor",	"opponent"]]
    except:
      opponents_df = pd.DataFrame(columns=['elo_score', 'descriptor', 'opponent'])
    if len(opponents_df)==0:
      return "Add some opponents to start voting!", "", "", display_rankings(opponents_df)
    if first_string != "":
      opponents_df["combined"] = opponents_df["opponent"] + " - " + opponents_df["descriptor"]
      loser = opponents_df[opponents_df["combined"] == first_string]
      winner = opponents_df[opponents_df["combined"] == second_string]

      # Update Elo scores
      winner_score, loser_score = update_scores(winner['elo_score'].values[0], loser['elo_score'].values[0])
      opponents_df.at[winner.index[0], 'elo_score'] = winner_score
      opponents_df.at[loser.index[0], 'elo_score'] = loser_score

    opponents_df = opponents_df.sort_values(by='elo_score', ascending=False)
    opponents_df.to_csv("opponents_df.csv")
    if len(opponents_df)>10:
          slice_size = 4
          slice = int(len(opponents_df)/slice_size)
          sample = opponents_df[slice:(slice_size-1)*slice].sample(frac=1).iloc[0]
          opponent, descriptor = sample["opponent"], sample["descriptor"]
    else:
          sample = opponents_df.sample(frac=1).iloc[0]
          opponent, descriptor = sample["opponent"], sample["descriptor"]
    if len(opponents_df) > 1:
        # Randomly select a opponent to compare with
        sample = opponents_df.sample(frac=1)
        comparison_opponent = sample.iloc[0]
        if comparison_opponent['opponent'] == opponent and comparison_opponent['descriptor'] == descriptor:
          comparison_opponent = sample.iloc[1]
        first_df = opponents_df[opponents_df["opponent"]==opponent][opponents_df["descriptor"]==descriptor]
        first_string = first_df["opponent"].tolist()[0]+" - "+first_df["descriptor"].tolist()[0]
        second_df = comparison_opponent
        second_string = second_df["opponent"]+" - "+second_df["descriptor"]
        return f"Do you like '{descriptor} - {opponent}' better than '{comparison_opponent['descriptor']} - {comparison_opponent['opponent']}'?", first_string, second_string, display_rankings(opponents_df)
    else:
        return "Add some opponents to start voting!", "", "", display_rankings(opponents_df)
        
def display_rankings(opponents_df=pd.DataFrame(columns=['elo_score', 'descriptor', 'opponent'])):
  opponents_df = opponents_df.sort_values(by='elo_score', ascending=False)
  opponents_df = opponents_df[["elo_score",	"descriptor",	"opponent"]]
  opponents_df.to_csv("opponents_df.csv")
  return opponents_df

def export_csv(opponents_df):
    # Function to export DataFrame to CSV
    save_df = opponents_df
    save_df.to_csv("opponents_df.csv")
    return "opponents_df.csv"

def import_csv(file, opponents_df):
    if file is not None:
        #file_content = file.decode('utf-8')
        new_df = pd.read_csv(file)
        try:
            opponents_df = opponents_df[["elo_score",	"descriptor",	"opponent"]]
        except:
            opponents_df = pd.DataFrame(columns=['elo_score', 'descriptor', 'opponent'])
        new_df = new_df[["elo_score",	"descriptor",	"opponent"]]
        opponents_df = pd.concat([opponents_df,new_df])

    opponents_df = opponents_df.drop_duplicates(subset=['descriptor', 'opponent'])
    return opponents_df

    
# Function to remove a opponent
def remove_opponent(descriptor, opponent, opponents_df):
    # Find and remove the opponent from the DataFrame
    descriptor = clean_string(descriptor)
    opponent = clean_string(opponent)
    opponents_df = opponents_df[~((opponents_df["descriptor"] == descriptor) & (opponents_df["opponent"] == opponent))]
    return opponents_df[["elo_score", "descriptor", "opponent"]]

def reset_rankings(opponents_df):
    opponents_df["elo_score"] = [1000]*len(opponents_df)
    opponents_df = opponents_df[["elo_score",	"descriptor",	"opponent"]]
    return display_rankings(opponents_df)

def clear_rankings(opponents_df):
    opponents_df = pd.DataFrame(columns=['elo_score', 'descriptor', 'opponent'])
    return display_rankings(opponents_df)
    

# theme='Taithrah/Minimal'
# Gradio interface
theme = gr.themes.Soft(primary_hue="red", secondary_hue="blue")


    
with gr.Blocks(theme=theme) as app:
    
    gr.Markdown(
        """## Preference-based Elo Ranker
        This tool helps you create **accurate rankings** of things based on your personal preferences.
        It does this by asking you questions comparing a random pair of your inpys, and then using your
        answers to calculate Elo scores for ranking.
        """
    )

    with gr.Row():
        previews_df = pd.DataFrame(columns=['elo_score', 'descriptor', 'opponent'])
        previews = gr.DataFrame(value=previews_df, interactive=False, visible=False)
        with gr.Column():
            gr.Markdown(
                """### Vote to Rank
                """
            )
            with gr.Row():
                compare_output = gr.Textbox("Add some options to start voting!", label="Comparison", interactive=False, scale=3)
                with gr.Row():
                    yes_button = gr.Button("Yes", variant="secondary")
                    no_button = gr.Button("No", variant="primary")
                
            new_vote = gr.Button("New Vote")
            with gr.Row():
                with gr.Column():
                    compare_index_1 = gr.Textbox(label="",interactive=False, visible=False)
                with gr.Column():
                    compare_index_2 = gr.Textbox(label="",interactive=False, visible=False)
        with gr.Column():
            gr.Markdown(
                """### Rankings
                """
            )
    
            opponents_df = pd.DataFrame(columns=['elo_score', 'descriptor', 'opponent'])
            rankings = gr.DataFrame(value=opponents_df, interactive=False, headers=["Score","descriptor", "opponent"])
            
    gr.Markdown(
        """### Add Opponents
        """
    )
    with gr.Row():
        descriptor_input = gr.Textbox(label="Type")
        opponent_input = gr.Textbox(label="Opponent")
        add_button = gr.Button("Add Opponent")
    add_button.click(add_and_compare, inputs=[descriptor_input, opponent_input, rankings], outputs=[descriptor_input, opponent_input, rankings])
    gr.Markdown(
        """### Remove Opponents
        """
    )
    with gr.Row():
        remove_descriptor_input = gr.Textbox(label="Type")
        remove_opponent_input = gr.Textbox(label="Opponent")
        remove_button = gr.Button("Remove opponent")
    remove_button.click(remove_opponent, inputs=[remove_descriptor_input, remove_opponent_input, rankings], outputs=rankings)
    
    gr.Markdown(
        """### Import and Export Rankings
        """
    )
    with gr.Row():
        
        # Import CSV file to replace the existing DataFrame
        import_button = gr.File(label="Import CSV", file_count="single")
        import_button.change(fn=import_csv, inputs=[import_button, rankings], outputs=[rankings])

        with gr.Column():
            # Export button to download the DataFrame as CSV
            export_link = gr.File(label="Download CSV", file_count="single")
            export_button = gr.Button("Export as CSV")
            export_button.click(fn=export_csv, inputs=[rankings], outputs=export_link)
        
    gr.Markdown("### Reset Data")
    with gr.Row():
      reset_button = gr.Button("Reset Scores")
      reset_button.click(reset_rankings, inputs=[rankings], outputs=rankings)
      clear_button = gr.Button("Clear Table", variant="primary")
      clear_button.click(clear_rankings, inputs=[rankings], outputs=rankings)
        
    # add_button.click(add_and_compare, inputs=[descriptor_input, opponent_input, rankings], outputs=[descriptor_input, opponent_input, rankings])
    yes_button.click(update_ratings_pos, inputs=[compare_index_1, compare_index_2, rankings], outputs=[compare_output, compare_index_1, compare_index_2, rankings])
    no_button.click(update_ratings_neg, inputs=[compare_index_1, compare_index_2, rankings], outputs=[compare_output, compare_index_1, compare_index_2, rankings])
    new_vote.click(vote_startup, inputs=[rankings],outputs=[compare_output, compare_index_1, compare_index_2, rankings])

app.launch(share=False)