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
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
import streamlit as st
from datetime import time, datetime
import time as t
from time import time as now
import pandas as pd
import pandas_profiling
import numpy as np
from streamlit_pandas_profiling import st_profile_report
from io import StringIO
import requests
from pathlib import Path
from streamlit_elements import elements, dashboard, mui, media

st.set_page_config(page_title="Francesco Daimon Fernicola", page_icon=":milky_way:", layout="wide")

with st.container():
    st.subheader("Hello, and welcome to my official webpage! I am Daimon :wink:")
    st.title("PhD Candidate in Machine Translation / Translator / Mountain enthusiast")
    st.write("I am passionate about finding new ways to effectively use and understand Machine Translation and effectively evaluating its quality.")
    st.write("""
    [Github](https://github.com/FrancescoFernicola)
    [Unibo](https://www.unibo.it/sitoweb/francesco.fernicola2)
    [LinkedIn](https://www.linkedin.com/in/francesco-fernicola-69a0771b7/?locale=en_US)
    [Twitter](https://twitter.com/FrancescoDaimon)
    """)

st.header('st.button')

if st.button('Say hello'):
    st.write('Why hello there')
else:
    st.write('Goodbye')

st.header('st.slider')
st.subheader('Slider')
age = st.slider('How old are you?', 0, 120, 25)
st.write(f"I'm {age} years old")


st.subheader('Range Slider')

values = st.slider(
    'Select a range of values',
    0.0, 100.0, (25.0, 75.0)
)
st.write(f"Values: {values}")


st.subheader('Range time slider')

appointment = st.slider(
    "Schedule your appointment:",
    value=(time(11,30), time(12,45)),
    format="hh:mm"
)
st.write(f"You're scheduled for: {appointment}")


st.subheader('Datetime slider')

start_time = st.slider(
    "When do you start?",
    value=datetime(2023, 1, 1, 9, 30),
    format="DD/MM/YY - hh:mm"
)

st.write(f"Start time: {start_time}")




st.header('Line Chart')



chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=['a', 'b', 'c']
)

st.line_chart(chart_data)



with st.container():
    option = st.selectbox(
        'What is your favorite color?',
        ('Blue', 'Red', 'Green', 'More')
        )

    if not option == 'More':
        st.write(f'Your favorite color is {option}')
    else:
        new_option = st.multiselect(
            'What are your favorite colors',
            ['Green', 'Yellow', 'Red', 'Blue'],
            ['Yellow', 'Red']
        )
        st.write(f'Your favorite colors are {", ".join(new_option)}')

st.header('st.checkbox')

st.write('What would you like to order?')

icecream = st.checkbox('Ice cream')
coffee = st.checkbox('Coffee')
cola = st.checkbox('Cola')

if icecream:
    st.write("Great! Heres some more :icecream:")

if coffee:
    st.write("Okay, here's some coffee :coffee:")

if cola:
    st.write("Here you go πŸ₯€")


#st.header('streamlig_pandas_profiling')

#df = pd.read_csv('https://raw.githubusercontent.com/dataprofessor/data/master/penguins_cleaned.csv')

#pr = df.profile_report()
#st_profile_report(pr)


st.write("Contents of the '.streamlit/config.toml' file of this app")

st.code("""
[theme]
primaryColor="#F39C12"
backgroundColor="#2E86C1"
secondaryBackgroundColor="#AED6F1"
textColor="#FFFFFF"
font="monospace"
""")

number = st.sidebar.slider('Select a number:', 0, 10, 5)
st.write(f'Selected number from slider widget is: {number}')

st.header("This is taken from the .streamlit/secrets.toml")

st.write(f"Secret message: {st.secrets['message']}")
st.header("Remember to add the file to the .gitignore!")



st.title('st.file_uploader')

st.subheader('Input TSV/CSV')
uploaded_file = st.file_uploader("Choose a file")

if uploaded_file is not None:
    if uploaded_file.name.endswith('.tsv'):
        data = pd.read_csv(uploaded_file, sep="\t")
    else:
        data = pd.read_csv(uploaded_file)

    st.subheader("DataFrame")
    st.write(data)
    st.write(data.describe())
    
else:
    st.info("☝️ Upload a TSV/CSV file")


with st.expander('About this app'):
    st.write('This app shows the various options you can use (and should use) to customize your page')
    st.image('https://imgs.xkcd.com/comics/app.png', width=250)
    st.write('Below you will also display the progress of the calculation via "st.progress()"')



st.sidebar.header('Input')
user_name = st.sidebar.text_input('What is your name?')
user_emoji = st.sidebar.selectbox('Choose an emoji', ['', 'πŸ˜„', 'πŸ˜†', '😊', '😍', '😴', 'πŸ˜•', '😱'])
user_food = st.sidebar.selectbox('What is your favorite food?', ['', 'Tom Yum Kung', 'Burrito', 'Lasagna', 'Hamburger', 'Pizza'])

st.header('Output')

col1, col2, col3 = st.columns(3)

with col1:
  if user_name != '':
    st.write(f'πŸ‘‹ Hello {user_name}!')
  else:
    st.write('πŸ‘ˆ  Please enter your **name**!')

with col2:
  if user_emoji != '':
    st.write(f'{user_emoji} is your favorite **emoji**!')
  else:
    st.write('πŸ‘ˆ Please choose an **emoji**!')

with col3:
  if user_food != '':
    st.write(f'🍴 **{user_food}** is your favorite **food**!')
  else:
    st.write('πŸ‘ˆ Please choose your favorite **food**!')


#my_bar = st.progress(0)

#for percent_complete in range(100):
#    t.sleep(0.05)
#    my_bar.progress(percent_complete + 1)

st.metric(label="F1", 
    value="81.1",
    delta="-0.1")


st.title('st.cache')

a0 = now()
st.subheader('Using st.cache')

@st.cache(suppress_st_warning=True)
def load_data_a():
    dataframe = pd.DataFrame(
        np.random.rand(2000000, 5),
        columns=['a', 'b', 'c', 'd', 'e']
    )
    return dataframe

st.write(load_data_a())
a1 = now()
st.info(a1-a0)

b0 = now()


st.subheader('Not using st.cache')

def load_data_b():
  dataframe = pd.DataFrame(
    np.random.rand(2000000, 5),
    columns=['a', 'b', 'c', 'd', 'e']
  )
  return dataframe

st.write(load_data_b())
b1 = now()
st.info(b1-b0)

st.title('st.session_state')

def lbs_to_kg():
    st.session_state.kg = st.session_state.lbs/2.2046

def kg_to_lbs():
    st.session_state.lbs = st.session_state.kg*2.2046

st.header('Input kg/lbs')
col1, spacer, col2 = st.columns([2, 1, 2])

with col1:
    punds = st.number_input("Pounds:", key = "lbs", on_change = lbs_to_kg)

with col2:
    kilogram = st.number_input("Kilograms:", key = "kg", on_change= kg_to_lbs)

st.header('Output')
st.write("st.session_state object: ", st.session_state)



st.title('πŸ€ Bored API app')

st.sidebar.header("Input Boredom")
selected_type = st.sidebar.selectbox('Select an activity type', ["education", "recreational", "social", "diy", "charity", "cooking", "relaxation", "music", "busywork"])

suggested_activity_url = f'http://www.boredapi.com/api/activity?type={selected_type}'
json_response = requests.get(suggested_activity_url)
suggested_activity = json_response.json()


c1, c2 = st.columns(2)

with c1:
    with st.expander('About this app'):
        st.write('Bored stiff? The **BORED API APP** gives suggestions on activities that you can do when bored. This is powered by Bored API.')
with c2:
    with st.expander('JSON data'):
        st.write(suggested_activity)

st.header('Suggested activity')
st.info(suggested_activity['activity'])

col1, col2, col3 = st.columns(3)

with col1:
    st.metric(label="Number of Participants", value=suggested_activity['participants'], delta='')
with col2:
    st.metric(label="Type of Activity", value=suggested_activity['type'].capitalize(), delta='')
with col3:
    st.metric(label='Price', value=suggested_activity['price'], delta='')



media_url = st.text_input("Media URL", value="https://www.youtube.com/watch?v=9EcjWd-O4jI&ab_channel=TechnotronicVEVO")

layout = [
    # Media item is positioned in coordinates x=0 and y=3, and takes 6/12 columns and has a height of 4.
    dashboard.Item("media", 0, 2, 12, 4),
]

with elements("demo"):

    # Create a new dashboard with the layout specified above.
    #
    # draggableHandle is a CSS query selector to define the draggable part of each dashboard item.
    # Here, elements with a 'draggable' class name will be draggable.
    #
    # For more information on available parameters for dashboard grid:
    # https://github.com/react-grid-layout/react-grid-layout#grid-layout-props
    # https://github.com/react-grid-layout/react-grid-layout#responsive-grid-layout-props

    with dashboard.Grid(layout, draggableHandle=".draggable"):
        with mui.Card(key="media", sx={"display": "flex", "flexDirection": "column"}):
            mui.CardHeader(title="Media Player", className="draggable")
            with mui.CardContent(sx={"flex": 1, "minHeight": 0}):

                # This element is powered by ReactPlayer, it supports many more players other
                # than YouTube. You can check it out there: https://github.com/cookpete/react-player#props

                media.Player(url=media_url, width="100%", height="100%", controls=True)


def local_css(file_name):
    with open(file_name) as f:
        st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)

local_css("style/style.css")


from transformers import MBartForConditionalGeneration, MBart50TokenizerFast


st.subheader("MBART-50 Translator")

source = "In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move."
target = ""
model = MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-50-many-to-many-mmt")
tokenizer = MBart50TokenizerFast.from_pretrained("facebook/mbart-large-50-many-to-many-mmt")


def get_translation(src_code, trg_code, src):

    # translate Hindi to French
    tokenizer.src_lang = src_code
    encoded = tokenizer(src, return_tensors="pt")
    generated_tokens = model.generate(
        **encoded,
        forced_bos_token_id=tokenizer.lang_code_to_id[trg_code]
    )
    trg = tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
    
    return trg

valid_languages = ['en_XX', 'fr_XX', 'de_DE', 'it_IT', 'es_XX']

with st.form("my_form"):
    left_c, right_c = st.columns(2)
    with left_c:
        src_lang = st.selectbox(
        'Source language',
        ('en_XX', 'fr_XX', 'de_DE', 'it_IT', 'es_XX'),

        )
    with right_c:
        trg_lang = st.selectbox(
        'Target language',
        ('fr_XX', 'en_XX', 'de_DE', 'it_IT', 'es_XX')
        )
    source = st.text_area("Source", value=source, height=130, placeholder="Enter the source text...")


    submitted = st.form_submit_button("Translate")
    if submitted:
        if len(source) > 0 and src_lang in valid_languages and trg_lang in valid_languages:
            with st.spinner("Translating..."):
                try:
                    target = get_translation(src_lang, trg_lang, source)[0]
                    st.subheader("Translation done!")
                    target = st.text_area("Target", value=target, height=130)
                except:
                    st.subheader("Translation failed :sad:")
                    
        else:
            st.write("Please enter the source text, source language and target language.")



# ---- CONTACT ----
with st.container():
    st.write("---")
    st.header("Get in Touch With Me!")
    st.write("##")

    contact_form = """
    <form action="https://formsubmit.co/daimon.f@outlook.com" method="POST">
        <input type="hidden" name="_captcha" value="false">
        <input type="text" name="name" placeholder="Your name" required>
        <input type="email" name="email" placeholder="Your email" required>
        <textarea name="message" placeholder="Your message here" required></textarea>
        <button type="submit">Send</button>
    </form>
    """
    left_column, right_column = st.columns(2)
    with left_column:
        st.markdown(contact_form, unsafe_allow_html=True)
    with right_column:
        st.empty()