-
Notifications
You must be signed in to change notification settings - Fork 4
/
bkp
378 lines (322 loc) · 13.1 KB
/
bkp
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import streamlit as st
import re
import sys
us_pw = sys.argv[1] # user input: "my_user:password"
db_ip = sys.argv[2] # user input: 192.168.1.11
port = sys.argv[3] # user input: 5432
hide_streamlit_style = """
<style>
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
</style>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/darkmode-js.min.js"></script>
<script>
function addDarkmodeWidget() {
new Darkmode().showWidget();
}
window.addEventListener('load', addDarkmodeWidget);
</script>
"""
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
def start(button=None):
'''
Main app. Creates the GUI and gathers basic info.
'''
if type(button) == str:
pass
st.title('Venmo Requests Calculator')
st.write('Your one stop shop for personalized and accurate venmo requests.')
select_input = st.radio("Select input type", options=['Auto','Manual'])
if select_input == 'Manual':
receipt_input ,fees_input, tax_input, tip_input = manual_input()
else:
import image_rec as ir
receipt_input ,fees_input, tax_input, tip_input = ir.auto_input()
rf = receiptFormat()
# a dictionary of name(s) and sum of amount
raw_pairs = [(
rf.parse_alpha(alpha),
sum([float(i) for i in rf.parse_numbers(numbers)])
) for (alpha, numbers) in re.findall(rf.pattern, receipt_input)]
# combine all split costs with the people involved
data = {}
for (people, amount) in raw_pairs:
for person in [person.capitalize() for person in people]:
if not person in data:
data[person] = round(amount/len(people),2)
else:
data[person] += round(amount/len(people),2)
precheck_sum = sum(data.values())
total_value = round(precheck_sum+tax_input+tip_input+fees_input,2) # prefill the total
total_input = st.number_input("Calculated Total*",step=10.0,value=total_value)
try:
# gets a dictionary of total spent, dictionary of spent on food, percent tip, percent tax, and misc fees per person
my_total, my_food, tip_perc, tax_perc, fee_part = venmo_calc(my_dic = data, total=total_input, tax=tax_input, tip=tip_input, misc_fees=fees_input)
##### LIVE TESTING AREA #####
except:
st.warning("Something happened, please tell Pete!")
#############################
# Database section
st.write("Not required, but very fun")
col_save,col_show = st.columns([0.33,1])
with col_show:
button_show = st.button(label='Preview the Database')
with col_save:
button_save = st.button(label='Submit to Database')
if button_save == True:
saveus = saveInfo(my_total, my_food, tip_perc, tax_perc, fee_part,showme='no')
saveus.save_table()
st.balloons()
if button_show == True:
showus = saveInfo()
dataframe = showus.read_table()
dataframe = dataframe.iloc[:,1:]
show_me = dataframe.tail()
st.table(show_me)
def manual_input():
'''
Cut from app() function to make way for screenshot.
Manual input of costs, fees, tax, tips.
'''
with st.expander(label='How To'):
st.write(f"""
1. Input the name and itemized money spent in a format of:
```
Peter: 20.21,5.23, 3.21
Russell: 101.01, 15.89, 1.99
```
Or on a single line:
```
Peter 20.21 5.23 3.21 Russell 101.01 15.89 1.99
```
Or with a split cost (Peter and Russell pay 8 each)
```
Peter and Russell 16
Peter: 20.21, 5.23
Russell 101.01 15.89 1.99
```
2. Input the rest of the fees or tips as needed""")
receipt_input = st.text_area(label="Add name and food prices*")
col1, col2, col3 = st.columns(3)
with col1:
fees_input = st.number_input("Fees in dollars",step=1.0)
with col2:
tax_input = st.number_input("Tax in dollars",step=1.0)
with col3:
tip_input = st.number_input("Tip in dollars",step=5.0)
return receipt_input ,fees_input, tax_input, tip_input
class receiptFormat():
# Receipt formatting
def __init__(self):
'''
Formats string input of name/money using the following regix pattern.
( name group with optional space, colon, and comma
(?:
[A-Za-z ,:] capture all alpha which includes "and"
)+ one or more times
)
( number group matching numbers separated by comma or space
(?:
[\\d.]+[, ]* (sorry eruopeans)
)+
)
'''
self.pattern = '((?:[A-Za-z ,:])+)((?:[\\d.]+[, ]*)+)'
def parse_alpha(self,alpha):
'Splits string on delimiter including "and" "<space>" ":" ","'
return list(filter(None, re.split('(?:and| |:|,)+', alpha)))
def parse_numbers(self,numbers):
'Splits "12.2 12.3 56 53.2" -> "[12.2,12.3,56,53.2]"'
return list(filter(None, re.split('(?:[^\\d\\.])', numbers)))
def venmo_calc(my_dic, total, tax=0, tip=0, misc_fees=0):
"""
Returns lump sums to request using venmo
input
-----
my_dic: dict
Dictionary of name:[list of prices]
total: float
Total shown on receipt, charged to your card
tax: float
Tax applied in dollars, not percent
tip: float
Amount tipped in dollars, not percent
misc_fees: float
Sum of all other fees not accounted for, like delivery fee, etc
output
-----
request: dict
Dictionary of name:amount, indicating how much to charge each person
"""
import pandas as pd
precheck_sum = round(sum(my_dic.values())+tax+tip+misc_fees,2)
total = round(total,2) # otherwise get weird 23.00000005 raw totals
if total != precheck_sum:
return st.write(f"You provided {total} as the total, but I calculated {precheck_sum}")
else:
num_ppl = len(my_dic.keys())
tax_perc = tax/(total-tip-misc_fees-tax)
tip_perc = tip/(total-tip-misc_fees-tax)
fee_part = round(misc_fees/num_ppl,2)
request = {}
rounded_sum = 0
for key in my_dic.keys():
my_total = my_dic[key]
tax_part = tax_perc * my_total
tip_part = tip_perc * my_total
person_total = my_total + tax_part + fee_part + tip_part
rounded_sum += person_total
request[key] = person_total
### Explain the calculation for transparency ###
with st.expander(label='What just happened?'):
st.write(f"""
1. Tax% ($p_x$) was calculated using tax/(food_total): __{round(tax_perc*100,2)}%__
2. Tip% ($p_p$) was calculated using tip/(food_total): __{round(tip_perc*100,2)}%__
3. Fees were distributed equally: __${fee_part}__ per person
4. Each person's sum was calculated using: $m_t=d_s + (d_s * p_x) + (d_s*p_p) + d_f$
* $m_t$ = total money to request
* $d_s$ = dollars spent on food
* $p_x$ = percent tax
* $p_p$ = percent tip
* $d_f$ = dollars spent on fee
""")
rounded_sum = round(rounded_sum,2)
### Error catcher ###
if (rounded_sum > total+0.1):
return st.write(f"Uh oh! My calculated venmo charge sum is ${rounded_sum} but the receipt total was ${round(total,2)}")
### Format the output ###
output_money = {}
for key in request.keys():
output_money[key] = [round(request[key],2)]
df_out = pd.DataFrame.from_dict(output_money)
df_out = df_out.reset_index(drop=True)
df_out = df_out.T
df_out.columns = ['Amount']
venmo_request(request,my_dic,tip_perc,tax_perc,fee_part,tip,tax,misc_fees,df_out)
return output_money, my_dic, tip_perc, tax_perc, fee_part
def venmo_request(request,my_dic,tip_perc,tax_perc,fee_part,tip,tax,misc_fees,df_out):
'''
Generates a link that directs user to venmo app with prefilled options
ASCII table source: http://www.asciitable.com/
Use Hx column, add a % before it
'''
# used in venmo_request
html_table_header = '''
<table class="tg">
'''
# used in venmo_request
html_table_end = '''</tr>
</tbody>
</table>'''
link_output = {}
for key in request.keys():
txn = 'charge' # charge or pay
audience = 'private' # private, friends, or public
amount = round(request[key],2) # total requested dollars
# statement construction
statement = f'Hi {key}! Food was ${round(my_dic[key],2)}'
if tip > 0.0:
statement += f', tip was {round(tip_perc*100,2)}%25'
if tax > 0.0:
statement += f', tax was {round(tax_perc*100,2)}%25'
if misc_fees > 0.0:
statement += f', fees were ${round(fee_part,2)}'
statement += '.%0AMade with %3C3 at payme.peti.work' # %0A creates a new line
statement = statement.replace(' ','%20') # replace spaces for url parameter
link = f"https://venmo.com/?txn={txn}&audience={audience}&recipients={key}&amount={amount}¬e={statement}"
#link_html = f"<a href='{link}' target='_blank'>Click me for {key}'s sake!</a>"
#link_md = f"[Click me for {key}'s sake!](link)"
link_output[key] = link
html_table_data = f'''
<tbody>'''
venmo_logo = 'https://cdn1.venmo.com/marketing/images/branding/downloads/venmo_logo_blue.svg'
for key in request.keys():
# append each person's rows to html table
html_row = f'''
<tr>
<td class="tg-0pky">{key}<br></td>
<td class="tg-0pky">${round(request[key],2)}</td>
<td class="tg-0pky"><a href="{link_output[key]}" target="_blank" rel="noopener noreferrer"><img src="{venmo_logo}" width="60"></a><br></td>
</tr>'''
html_table_data += html_row
html_table = html_table_header + html_table_data + html_table_end
st.write(html_table, unsafe_allow_html=True)
st.write('')
def send_to_tg(link_output):
tg_link = 'tg://msg_url?url=https://holesome.netlify.app&text=hurry'
df_tg = pd.read_json('tg_info.json')
st.table(df_tg)
print("hi")
class saveInfo():
def __init__(self, my_total=0, my_food=0, tip_perc=0, tax_perc=0, fee_part=0,showme='yes'):
'''
Initialize the sqlite database
input
-----
my_total: dict
Dictionary of name:float, representing the total requested from each individual
my_food: dict
Dictionary of name:float, representing the total spent on food by each individual
tip_perc: float
Percent (in decimal form) the whole group tipped
tax_perc: float
Percent (in decimal form) the whole group spent on tax
fee_part: float
Misc fees evenly divided amongst all individuals
'''
import sqlalchemy as sq
import os
import datetime as dt
from pytz import timezone
# initialize engine
engine = sq.create_engine(f'postgres://{us_pw}@{db_ip}:{port}')
meta = sq.MetaData()
if showme=='no':
# table format in db
self.payme_now = sq.Table(
'payme_now', meta,
sq.Column('id', sq.Integer, primary_key = True),
sq.Column('date',sq.DateTime),
sq.Column('name', sq.String),
sq.Column('food', sq.Float),
sq.Column('tip',sq.Float),
sq.Column('tax',sq.Float),
sq.Column('fees',sq.Float),
sq.Column('total',sq.Float)
)
# format data into proper list of dictionaries
tz = timezone('US/Eastern')
result = []
for key in my_total.keys():
person = {
'date':dt.datetime.now(tz),
'name':key,
'food':my_food[key],
'tip':round(my_food[key] * tip_perc,2),
'tax':round(my_food[key] * tax_perc,2),
'fees':fee_part,
'total':my_total[key][0] # its a dictionary of lists, with each list having only the total
}
result.append(person)
self.result = result
meta.create_all(engine) # not sure why its needed, but its in the tutorial so ... :shrug:
self.engine = engine
def save_table(self):
'''
Saves information to database
'''
import datetime as dt
conn = self.engine.connect()
result = conn.execute(self.payme_now.insert(), self.result)
def read_table(self):
'''
Returns the entire database
'''
import pandas as pd
return pd.read_sql_table('payme_now',self.engine,parse_dates='date')
def app():
'''
Only purpose is to start the app. Own function so the rest of the functions can be organized in a logical way.
'''
start(button='start')
app()