simonschoe commited on
Commit
d055610
β€’
1 Parent(s): e45808b

update interface

Browse files
Files changed (1) hide show
  1. app.py +53 -51
app.py CHANGED
@@ -1,41 +1,38 @@
1
- import gradio as gr
2
- import numpy as np
3
- import pandas as pd
4
- from datetime import datetime
5
  import os
6
  import re
 
7
 
8
- from huggingface_hub import hf_hub_url, cached_download
 
 
9
  from gensim.models.fasttext import load_facebook_model
10
-
11
- ACCESS_KEY = os.environ.get('ACCESS_KEY')
12
 
13
 
14
- # Setup model
15
- url = hf_hub_url(repo_id="simonschoe/call2vec", filename="model.bin")
16
- cached_download(url)
17
- model = load_facebook_model(cached_download(url))
18
 
19
- def semantic_search(_input, n):
20
  """ Perform semantic search """
21
 
22
  _input = re.split('[,;\n]', _input)
23
  _input = [s.strip().lower().replace(' ', '_') for s in _input if s]
24
 
25
  if _input[0] != ACCESS_KEY:
26
- with open('log.txt', 'a') as f:
27
  f.write(str(datetime.now()) + '+++' + '___'.join(_input) + '\n')
28
 
29
  if len(_input) > 1:
30
  avg_input = np.stack([model.wv[w] for w in _input], axis=0).mean(axis=0)
31
- nearest_neighbours = model.wv.most_similar(positive=avg_input, topn=n)
32
  frequencies = [model.wv.get_vecattr(nn[0], 'count') for nn in nearest_neighbours]
33
  else:
34
- nearest_neighbours = model.wv.most_similar(positive=_input[0], topn=n)
35
  frequencies = [model.wv.get_vecattr(nn[0], 'count') for nn in nearest_neighbours]
36
-
37
  if _input[0] == ACCESS_KEY:
38
- with open('log.txt', 'r') as f:
39
  prompts = f.readlines()
40
  prompts = [p.strip().split('+++') for p in prompts]
41
  result = pd.DataFrame(prompts,
@@ -43,40 +40,28 @@ def semantic_search(_input, n):
43
  else:
44
  result = pd.DataFrame([(a[0],a[1],b) for a,b in zip(nearest_neighbours, frequencies)],
45
  columns=['Token', 'Cosine Similarity', 'Corpus Frequency'])
46
-
47
  result.to_csv('result.csv')
48
  return result, 'result.csv', '\n'.join(_input)
49
 
50
- app = gr.Blocks()
51
 
52
  with app:
53
- gr.Markdown("# Call2Vec")
54
- gr.Markdown("## Semantic Search in Quarterly Earnings Conference Calls")
55
- with gr.Row():
56
- with gr.Column():
 
 
 
 
 
57
  text_in = gr.Textbox(lines=1, placeholder="Insert text", label="Search Query")
58
  with gr.Row():
59
  n = gr.Slider(value=50, minimum=5, maximum=250, step=5, label="Number of Neighbours")
60
- compute_bt = gr.Button("Search")
61
  df_out = gr.Dataframe(interactive=False)
62
  f_out = gr.File(interactive=False, label="Download")
63
- with gr.Column():
64
- gr.Markdown(
65
- """
66
- #### Project Description
67
- Call2Vec is a [fastText](https://fasttext.cc/) word embedding model trained via [Gensim](https://radimrehurek.com/gensim/). It maps each token in the vocabulary into a dense, 300-dimensional vector space, designed for performing semantic search.
68
- The model is trained on a large sample of quarterly earnings conference calls, held by U.S. firms during the 2006-2022 period. In particular, the training data is restriced to the (rather sponentous) executives' remarks of the Q&A section of the call. The data has been preprocessed prior to model training via stop word removal, lemmatization, named entity masking, and coocurrence modeling.
69
- """
70
- )
71
- gr.Markdown(
72
- """
73
- #### App usage
74
- The model is intented to be used for **semantic search**: It encodes the search query (entered in the textbox on the right) in a dense vector space and finds semantic neighbours, i.e., token which frequently occur within similar contexts in the underlying training data.
75
- The model allows for two use cases:
76
- 1. *Single Search:* The input query consists of a single word. When provided a bi-, tri-, or even fourgram, the quality of the model output depends on the presence of the query token in the model's vocabulary. N-grams should be concated by an underscore (e.g., "machine_learning" or "artifical_intelligence").
77
- 2. *Multi Search:* The input query may consist of several words or n-grams, seperated by comma, semi-colon or newline. It then computes the average vector over all inputs and performs semantic search based on the average input token.
78
- """
79
- )
80
  gr.Examples(
81
  examples = [
82
  ["transformation", 20],
@@ -88,15 +73,32 @@ with app:
88
  fn = semantic_search,
89
  cache_examples=True
90
  )
91
- gr.Markdown(
92
- """
93
- <p style="text-align: center;">
94
- Call2Vec by X and Y
95
- <br>
96
- <img 'id="visitor-badge" alt="visitor badge" src="https://visitor-badge.glitch.me/badge?page_id=simonschoe.call2vec&left_color=green&right_color=blue" />
97
- </p>
98
- """
99
- )
100
- compute_bt.click(semantic_search, inputs=[text_in, n], outputs=[df_out, f_out, text_in])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
  app.launch()
 
 
 
 
 
1
  import os
2
  import re
3
+ from datetime import datetime
4
 
5
+ import gradio as gr
6
+ import numpy as np
7
+ import pandas as pd
8
  from gensim.models.fasttext import load_facebook_model
9
+ from huggingface_hub import hf_hub_download
 
10
 
11
 
12
+ ACCESS_KEY = os.environ.get('ACCESS_KEY')
13
+ url = hf_hub_download(repo_id="simonschoe/call2vec", filename="model.bin") #hf_hub_url(repo_id="simonschoe/call2vec", filename="model.bin")
14
+ model = load_facebook_model(url)
 
15
 
16
+ def semantic_search(_input, neighbours):
17
  """ Perform semantic search """
18
 
19
  _input = re.split('[,;\n]', _input)
20
  _input = [s.strip().lower().replace(' ', '_') for s in _input if s]
21
 
22
  if _input[0] != ACCESS_KEY:
23
+ with open('log.txt', 'a', encoding='utf-8') as f:
24
  f.write(str(datetime.now()) + '+++' + '___'.join(_input) + '\n')
25
 
26
  if len(_input) > 1:
27
  avg_input = np.stack([model.wv[w] for w in _input], axis=0).mean(axis=0)
28
+ nearest_neighbours = model.wv.most_similar(positive=avg_input, topn=neighbours)
29
  frequencies = [model.wv.get_vecattr(nn[0], 'count') for nn in nearest_neighbours]
30
  else:
31
+ nearest_neighbours = model.wv.most_similar(positive=_input[0], topn=neighbours)
32
  frequencies = [model.wv.get_vecattr(nn[0], 'count') for nn in nearest_neighbours]
33
+
34
  if _input[0] == ACCESS_KEY:
35
+ with open('log.txt', 'r', encoding='utf-8') as f:
36
  prompts = f.readlines()
37
  prompts = [p.strip().split('+++') for p in prompts]
38
  result = pd.DataFrame(prompts,
 
40
  else:
41
  result = pd.DataFrame([(a[0],a[1],b) for a,b in zip(nearest_neighbours, frequencies)],
42
  columns=['Token', 'Cosine Similarity', 'Corpus Frequency'])
43
+
44
  result.to_csv('result.csv')
45
  return result, 'result.csv', '\n'.join(_input)
46
 
47
+ app = gr.Blocks(theme=gr.themes.Default(), css='#component-0 {max-width: 730px; margin: auto; padding-top: 1.5rem}')
48
 
49
  with app:
50
+ gr.Markdown(
51
+ """
52
+ # Call2Vec
53
+ ## Semantic Search in Quarterly Earnings Conference Calls
54
+ """
55
+ )
56
+
57
+ with gr.Tabs() as tabs:
58
+ with gr.TabItem("πŸ” Model", id=0):
59
  text_in = gr.Textbox(lines=1, placeholder="Insert text", label="Search Query")
60
  with gr.Row():
61
  n = gr.Slider(value=50, minimum=5, maximum=250, step=5, label="Number of Neighbours")
62
+ btn = gr.Button("Search")
63
  df_out = gr.Dataframe(interactive=False)
64
  f_out = gr.File(interactive=False, label="Download")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  gr.Examples(
66
  examples = [
67
  ["transformation", 20],
 
73
  fn = semantic_search,
74
  cache_examples=True
75
  )
76
+ with gr.TabItem("πŸ“ Usage", id=1):
77
+ gr.Markdown(
78
+ """
79
+ #### App usage
80
+ The model is intended to be used for **semantic search**: It encodes the search query (entered in the textbox on the right) in a dense vector space and finds semantic neighbours, i.e., token which frequently occur within similar contexts in the underlying training data.
81
+ The model allows for two use cases:
82
+ 1. *Single Search:* The input query consists of a single word. When provided a bi-, tri-, or even fourgram, the quality of the model output depends on the presence of the query token in the model's vocabulary. N-grams should be concated by an underscore (e.g., "machine_learning" or "artifical_intelligence").
83
+ 2. *Multi Search:* The input query may consist of several words or n-grams, seperated by comma, semi-colon or newline. It then computes the average vector over all inputs and performs semantic search based on the average input token.
84
+ """
85
+ )
86
+ with gr.TabItem("πŸ“– About", id=2):
87
+ gr.Markdown(
88
+ """
89
+ #### Project Description
90
+ Call2Vec is a [fastText](https://fasttext.cc/) word embedding model trained via [Gensim](https://radimrehurek.com/gensim/). It maps each token in the vocabulary into a dense, 300-dimensional vector space, designed for performing semantic search.
91
+ The model is trained on a large sample of quarterly earnings conference calls, held by U.S. firms during the 2006-2022 period. In particular, the training data is restriced to the (rather sponentous) executives' remarks of the Q&A section of the call. The data has been preprocessed prior to model training via stop word removal, lemmatization, named entity masking, and coocurrence modeling.
92
+ """
93
+ )
94
+
95
+ with gr.Accordion("πŸ“™ Citation", open=False):
96
+ citation_button = gr.Textbox(
97
+ value='Placeholder',
98
+ label='Copy to cite these results.',
99
+ show_copy_button=True
100
+ )
101
+
102
+ btn.click(semantic_search, inputs=[text_in, n], outputs=[df_out, f_out, text_in])
103
 
104
  app.launch()