Skip to content

Instantly share code, notes, and snippets.

View admond1994's full-sized avatar

Admond Lee admond1994

View GitHub Profile
if __name__ == "__main__":
recognizer = sr.Recognizer()
mic = sr.Microphone(device_index=1)
response = recognize_speech_from_mic(recognizer, mic)
print('\nSuccess : {}\nError : {}\n\nText from Speech\n{}\n\n{}' \
.format(response['success'],
response['error'],
'-'*17,
response['transcription']))
def recognize_speech_from_mic(recognizer, microphone):
"""Transcribe speech from recorded from `microphone`.
Returns a dictionary with three keys:
"success": a boolean indicating whether or not the API request was
successful
"error": `None` if no error occured, otherwise a string containing
an error message if the API could not be reached or
speech was unrecognizable
"transcription": `None` if speech could not be transcribed,
otherwise a string containing the transcribed text
def get_discrete_intervals_from_values(df):
'''
AIM -> get discrete intervals by binning values to a range
INPUT -> df
OUTPUT -> updated df with discrete intervals based on numerical values
------
'''
df['rating'] = pd.cut(df['rating'],
def get_unique_last_str(df):
'''
AIM -> get unique last str for a column
INPUT -> df
OUTPUT -> updated df based on the unique last strings in a column
------
'''
df = df[df.index.isin(df['col_1'].drop_duplicates(keep='last').index)].reset_index(drop=True)
def remove_nan_values(df):
'''
AIM -> remove NaN values of a particular column and output the whole dataframe
INPUT -> df
OUTPUT -> updated df without NaN values for a particular column
------
'''
df = df[df['col_1'].notnull()]
def list_comprehension(df):
'''
AIM -> IF ELSE for the list comprehension
INPUT -> df
OUTPUT -> List
------
'''
compute_list = [df['col_1'][i] if df['col_1'][i] > 0 else -1 for i in range(len(df))]
def rename_col(df):
'''
AIM -> rename column names
INPUT -> df
OUTPUT -> updated df with new column names
------
'''
df.rename(index=str, columns={'col_1': 'new_col_1',
def get_probability(start_value, end_value, eval_points, kd):
# Number of evaluation points
N = eval_points
step = (end_value - start_value) / (N - 1) # Step size
x = np.linspace(start_value, end_value, N)[:, np.newaxis] # Generate values in the range
kd_vals = np.exp(kd.score_samples(x)) # Get PDF values for each x
probability = np.sum(kd_vals * step) # Approximate the integral of the PDF
return probability.round(4)
def plot_prob_density(df_lunch, df_dinner, field, x_start, x_end):
plt.figure(figsize = (10, 7))
unit = 1.5
x = np.linspace(df_lunch.min() - unit, df_lunch.max() + unit, 1000)[:, np.newaxis]
# Plot the data using a normalized histogram
plt.hist(df_lunch, bins=10, density=True, label='Lunch Time', color='orange', alpha=0.2)
plt.hist(df_dinner, bins=10, density=True, label='Dinner Time', color='navy', alpha=0.2)
fig = plt.figure(figsize=(15, 7))
ax1 = fig.add_subplot(111)
ax1.set_xlabel('Month',fontsize=15)
ax1.set_ylabel('Total Amount Spent ($)',fontsize=15)
ax1.set_title('Total Amount Spent for different Months',fontsize=15)
ax1.bar(df.groupby(by=['year_month'])['amount_spent'].sum().index.tolist()[1:],
df.groupby(by=['year_month'])['amount_spent'].sum()[1:],
alpha=0.85,
label='Amount Spent by Month')