awinml commited on
Commit
c5e4524
1 Parent(s): ff5dcc7

Upload 8 files

Browse files
app.py CHANGED
@@ -6,18 +6,27 @@ import streamlit as st
6
 
7
  st.set_page_config(layout="wide") # isort: split
8
 
9
- from utils import (
10
  clean_entities,
11
- create_dense_embeddings,
12
- create_sparse_embeddings,
13
  extract_quarter_year,
14
  extract_ticker_spacy,
15
- format_query,
16
- get_flan_alpaca_xl_model,
17
  generate_alpaca_ner_prompt,
 
 
18
  generate_entities_flan_alpaca_checkpoint,
19
  generate_entities_flan_alpaca_inference_api,
20
- format_entities_flan_alpaca,
 
 
 
 
 
 
 
 
 
 
21
  generate_flant5_prompt_instruct_chunk_context,
22
  generate_flant5_prompt_instruct_chunk_context_single,
23
  generate_flant5_prompt_instruct_complete_context,
@@ -26,24 +35,23 @@ from utils import (
26
  generate_gpt_j_two_shot_prompt_1,
27
  generate_gpt_j_two_shot_prompt_2,
28
  generate_gpt_prompt,
 
29
  generate_text_flan_t5,
30
  get_context_list_prompt,
31
- get_data,
32
- get_flan_t5_model,
33
- get_mpnet_embedding_model,
34
- get_sgpt_embedding_model,
35
- get_spacy_model,
36
- get_splade_sparse_embedding_model,
37
- get_t5_model,
38
- gpt_model,
39
- hybrid_score_norm,
40
  query_pinecone,
41
  query_pinecone_sparse,
42
- retrieve_transcript,
43
- save_key,
44
  sentence_id_combine,
45
  text_lookup,
46
  )
 
 
 
 
 
 
47
 
48
  st.title("Question Answering on Earnings Call Transcripts")
49
 
 
6
 
7
  st.set_page_config(layout="wide") # isort: split
8
 
9
+ from utils.entity_extraction import (
10
  clean_entities,
 
 
11
  extract_quarter_year,
12
  extract_ticker_spacy,
13
+ format_entities_flan_alpaca,
 
14
  generate_alpaca_ner_prompt,
15
+ )
16
+ from utils.models import (
17
  generate_entities_flan_alpaca_checkpoint,
18
  generate_entities_flan_alpaca_inference_api,
19
+ generate_text_flan_t5,
20
+ get_data,
21
+ get_flan_alpaca_xl_model,
22
+ get_flan_t5_model,
23
+ get_mpnet_embedding_model,
24
+ get_sgpt_embedding_model,
25
+ get_spacy_model,
26
+ get_splade_sparse_embedding_model,
27
+ get_t5_model,
28
+ )
29
+ from utils.prompts import (
30
  generate_flant5_prompt_instruct_chunk_context,
31
  generate_flant5_prompt_instruct_chunk_context_single,
32
  generate_flant5_prompt_instruct_complete_context,
 
35
  generate_gpt_j_two_shot_prompt_1,
36
  generate_gpt_j_two_shot_prompt_2,
37
  generate_gpt_prompt,
38
+ generate_gpt_prompt_2,
39
  generate_text_flan_t5,
40
  get_context_list_prompt,
41
+ )
42
+ from utils.retriever import (
43
+ format_query,
 
 
 
 
 
 
44
  query_pinecone,
45
  query_pinecone_sparse,
 
 
46
  sentence_id_combine,
47
  text_lookup,
48
  )
49
+ from utils.transcript_retrieval import retrieve_transcript
50
+ from utils.vector_index import (
51
+ create_dense_embeddings,
52
+ create_sparse_embeddings,
53
+ hybrid_score_norm,
54
+ )
55
 
56
  st.title("Question Answering on Earnings Call Transcripts")
57
 
utils/__init__.py ADDED
File without changes
utils/entity_extraction.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ # Entity Extraction
4
+
5
+
6
+ def generate_alpaca_ner_prompt(query):
7
+ prompt = f"""Below is an instruction that describes a task, paired with an input that provides further context. Use the following guidelines to extract the entities representing the Company, Quarter, and Year in the sentence.
8
+
9
+ ### Instruction:
10
+ - The output should be in the form "Company - Value, Quarter - Value, Year - Value".
11
+ - The output should be in the form "Company - None, Quarter - None, Year - None", if no entities are found.
12
+ - Only use entities that exist in the final sentence.
13
+ - If Company cannot be found in the sentence, return "none" for that entity.
14
+ - If Quarter cannot be found in the sentence, return "none" for that entity.
15
+ - If Year cannot be found in the sentence, return "none" for that entity.
16
+ - If there is ambiguity finding the entity, return "none" for that entity.
17
+
18
+ ### Input:
19
+
20
+ What was discussed regarding Services revenue performance in Apple's Q3 2020 earnings call?
21
+ Company - Apple, Quarter - Q3, Year - 2020
22
+
23
+ How has the growth in Q1 been for the consumer market as seen by AMD?
24
+ Company - AMD, Quarter - Q1, Year - none
25
+
26
+ What was the long term view on GOOGL's cloud business growth as discussed in their earnings call?
27
+ Company - Google, Quarter - none, Year - none
28
+
29
+ What is Nvidia's outlook in the data center business in Q3 2020?
30
+ Company - Nvidia, Quarter - Q3, Year - 2020
31
+
32
+ What are the expansion plans of Amazon in the Asia Pacific region as discussed in their earnings call?
33
+ Company - Amazon, Quarter - none, Year - none
34
+
35
+ What did the Analysts ask about CSCO's cybersecurity business in the earnings call in 2016?
36
+ Company - Cisco, Quarter - none, Year - 2016
37
+
38
+
39
+ {query}
40
+ ### Response:"""
41
+ return prompt
42
+
43
+
44
+ def format_entities_flan_alpaca(values):
45
+ """
46
+ Extracts the text for each entity from the output generated by the
47
+ Flan-Alpaca model.
48
+ """
49
+ try:
50
+ company_string, quarter_string, year_string = values.split(", ")
51
+ except:
52
+ company = None
53
+ quarter = None
54
+ year = None
55
+ try:
56
+ company = company_string.split(" - ")[1].lower()
57
+ company = None if company.lower() == "none" else company
58
+ except:
59
+ company = None
60
+ try:
61
+ quarter = quarter_string.split(" - ")[1]
62
+ quarter = None if quarter.lower() == "none" else quarter
63
+
64
+ except:
65
+ quarter = None
66
+ try:
67
+ year = year_string.split(" - ")[1]
68
+ year = None if year.lower() == "none" else year
69
+
70
+ except:
71
+ year = None
72
+
73
+ print((company, quarter, year))
74
+ return company, quarter, year
75
+
76
+
77
+ def extract_quarter_year(string):
78
+ # Extract year from string
79
+ year_match = re.search(r"\d{4}", string)
80
+ if year_match:
81
+ year = year_match.group()
82
+ else:
83
+ year = None
84
+
85
+ # Extract quarter from string
86
+ quarter_match = re.search(r"Q\d", string)
87
+ if quarter_match:
88
+ quarter = "Q" + quarter_match.group()[1]
89
+ else:
90
+ quarter = None
91
+
92
+ return quarter, year
93
+
94
+
95
+ def extract_ticker_spacy(query, model):
96
+ doc = model(query)
97
+ entities = {ent.label_: ent.text for ent in doc.ents}
98
+ print(entities.keys())
99
+ if "ORG" in entities.keys():
100
+ company = entities["ORG"].lower()
101
+ else:
102
+ company = None
103
+ return company
104
+
105
+
106
+ def clean_entities(company, quarter, year):
107
+ company_ticker_map = {
108
+ "apple": "AAPL",
109
+ "amd": "AMD",
110
+ "amazon": "AMZN",
111
+ "cisco": "CSCO",
112
+ "google": "GOOGL",
113
+ "microsoft": "MSFT",
114
+ "nvidia": "NVDA",
115
+ "asml": "ASML",
116
+ "intel": "INTC",
117
+ "micron": "MU",
118
+ }
119
+
120
+ ticker_choice = [
121
+ "AAPL",
122
+ "CSCO",
123
+ "MSFT",
124
+ "ASML",
125
+ "NVDA",
126
+ "GOOGL",
127
+ "MU",
128
+ "INTC",
129
+ "AMZN",
130
+ "AMD",
131
+ ]
132
+ year_choice = ["2020", "2019", "2018", "2017", "2016", "All"]
133
+ quarter_choice = ["Q1", "Q2", "Q3", "Q4", "All"]
134
+ if company is not None:
135
+ if company in company_ticker_map.keys():
136
+ ticker = company_ticker_map[company]
137
+ ticker_index = ticker_choice.index(ticker)
138
+ else:
139
+ ticker_index = 0
140
+ else:
141
+ ticker_index = 0
142
+ if quarter is not None:
143
+ if quarter in quarter_choice:
144
+ quarter_index = quarter_choice.index(quarter)
145
+ else:
146
+ quarter_index = len(quarter_choice) - 1
147
+ else:
148
+ quarter_index = len(quarter_choice) - 1
149
+ if year is not None:
150
+ if year in year_choice:
151
+ year_index = year_choice.index(year)
152
+ else:
153
+ year_index = len(year_choice) - 1
154
+ else:
155
+ year_index = len(year_choice) - 1
156
+ return ticker_index, quarter_index, year_index
utils/models.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import re
3
+
4
+ import openai
5
+ import pandas as pd
6
+ import requests
7
+ import spacy
8
+ import spacy_transformers
9
+ import streamlit_scrollable_textbox as stx
10
+ import torch
11
+ from sentence_transformers import SentenceTransformer
12
+ from tqdm import tqdm
13
+ from transformers import (
14
+ AutoModelForMaskedLM,
15
+ AutoModelForSeq2SeqLM,
16
+ AutoTokenizer,
17
+ T5ForConditionalGeneration,
18
+ T5Tokenizer,
19
+ pipeline,
20
+ )
21
+
22
+ import pinecone
23
+ import streamlit as st
24
+
25
+
26
+ @st.experimental_singleton
27
+ def get_data():
28
+ data = pd.read_csv("earnings_calls_cleaned_metadata.csv")
29
+ return data
30
+
31
+
32
+ # Initialize Spacy Model
33
+
34
+
35
+ @st.experimental_singleton
36
+ def get_spacy_model():
37
+ return spacy.load("en_core_web_trf")
38
+
39
+
40
+ @st.experimental_singleton
41
+ def get_flan_alpaca_xl_model():
42
+ model = AutoModelForSeq2SeqLM.from_pretrained(
43
+ "/home/user/app/models/flan-alpaca-xl/"
44
+ )
45
+ tokenizer = AutoTokenizer.from_pretrained(
46
+ "/home/user/app/models/flan-alpaca-xl/"
47
+ )
48
+ return model, tokenizer
49
+
50
+
51
+ # Initialize models from HuggingFace
52
+
53
+
54
+ @st.experimental_singleton
55
+ def get_t5_model():
56
+ return pipeline("summarization", model="t5-small", tokenizer="t5-small")
57
+
58
+
59
+ @st.experimental_singleton
60
+ def get_flan_t5_model():
61
+ tokenizer = T5Tokenizer.from_pretrained("google/flan-t5-large")
62
+ model = T5ForConditionalGeneration.from_pretrained("google/flan-t5-large")
63
+ return model, tokenizer
64
+
65
+
66
+ @st.experimental_singleton
67
+ def get_mpnet_embedding_model():
68
+ device = "cuda" if torch.cuda.is_available() else "cpu"
69
+ model = SentenceTransformer(
70
+ "sentence-transformers/all-mpnet-base-v2", device=device
71
+ )
72
+ model.max_seq_length = 512
73
+ return model
74
+
75
+
76
+ @st.experimental_singleton
77
+ def get_splade_sparse_embedding_model():
78
+ model_sparse = "naver/splade-cocondenser-ensembledistil"
79
+ # check device
80
+ device = "cuda" if torch.cuda.is_available() else "cpu"
81
+ tokenizer = AutoTokenizer.from_pretrained(model_sparse)
82
+ model_sparse = AutoModelForMaskedLM.from_pretrained(model_sparse)
83
+ # move to gpu if available
84
+ model_sparse.to(device)
85
+ return model_sparse, tokenizer
86
+
87
+
88
+ @st.experimental_singleton
89
+ def get_sgpt_embedding_model():
90
+ device = "cuda" if torch.cuda.is_available() else "cpu"
91
+ model = SentenceTransformer(
92
+ "Muennighoff/SGPT-125M-weightedmean-nli-bitfit", device=device
93
+ )
94
+ model.max_seq_length = 512
95
+ return model
96
+
97
+
98
+ @st.experimental_memo
99
+ def save_key(api_key):
100
+ return api_key
101
+
102
+
103
+ # Text Generation
104
+
105
+
106
+ def gpt_model(prompt):
107
+ response = openai.Completion.create(
108
+ model="text-davinci-003",
109
+ prompt=prompt,
110
+ temperature=0,
111
+ max_tokens=1024,
112
+ )
113
+ return response.choices[0].text
114
+
115
+
116
+ def generate_text_flan_t5(model, tokenizer, input_text):
117
+ input_ids = tokenizer(input_text, return_tensors="pt").input_ids
118
+ outputs = model.generate(input_ids, temperature=0.5, max_length=512)
119
+ return tokenizer.decode(outputs[0], skip_special_tokens=True)
120
+
121
+
122
+ # Entity Extraction
123
+
124
+
125
+ def generate_entities_flan_alpaca_inference_api(prompt):
126
+ API_URL = "https://api-inference.huggingface.co/models/declare-lab/flan-alpaca-xl"
127
+ API_TOKEN = st.secrets["hg_key"]
128
+ headers = {"Authorization": f"Bearer {API_TOKEN}"}
129
+ payload = {
130
+ "inputs": prompt,
131
+ "parameters": {
132
+ "do_sample": True,
133
+ "temperature": 0.1,
134
+ "max_length": 80,
135
+ },
136
+ "options": {"use_cache": False, "wait_for_model": True},
137
+ }
138
+ try:
139
+ data = json.dumps(payload)
140
+ # Key not used as headers=headers not passed
141
+ response = requests.request("POST", API_URL, data=data)
142
+ output = json.loads(response.content.decode("utf-8"))[0][
143
+ "generated_text"
144
+ ]
145
+ except:
146
+ output = ""
147
+ print(output)
148
+ return output
149
+
150
+
151
+ def generate_entities_flan_alpaca_checkpoint(model, tokenizer, prompt):
152
+ model_inputs = tokenizer(prompt, return_tensors="pt")
153
+ input_ids = model_inputs["input_ids"]
154
+ generation_output = model.generate(
155
+ input_ids=input_ids,
156
+ temperature=0.1,
157
+ top_p=0.5,
158
+ max_new_tokens=1024,
159
+ )
160
+ output = tokenizer.decode(generation_output[0], skip_special_tokens=True)
161
+ return output
utils/prompts.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def generate_gpt_prompt(query_text, context_list):
2
+ context = " ".join(context_list)
3
+ prompt = f"""Answer the question in 6 long detailed points as accurately as possible using the provided context. Include as many key details as possible.
4
+ Context: {context}
5
+ Question: {query_text}
6
+ Answer:"""
7
+ return prompt
8
+
9
+
10
+ def generate_gpt_prompt_2(query_text, context_list):
11
+ context = " ".join(context_list)
12
+ prompt = f"""
13
+ Context information is below:
14
+ ---------------------
15
+ {context}
16
+ ---------------------
17
+ Given the context information and prior knowledge, answer this question:
18
+ {query_text}
19
+ Try to include as many key details as possible and format the answer in points."""
20
+ return prompt
21
+
22
+
23
+ def generate_flant5_prompt_instruct_complete_context(query_text, context_list):
24
+ context = " ".join(context_list)
25
+ prompt = f"""Answer the question in long detailed sentences using the context.
26
+ Question: {query_text}
27
+ Context: {context}
28
+ Answer: """
29
+ return prompt
30
+
31
+
32
+ def generate_flant5_prompt_instruct_chunk_context(query_text, context_list):
33
+ prompt = """"""
34
+ for chunk in context_list:
35
+ prompt_chunk = f"""Answer the question in long detailed sentences using the context.
36
+ Question: {query_text}
37
+ Context: {chunk}
38
+ Answer: """
39
+ prompt = (
40
+ prompt
41
+ + "\n"
42
+ + "---------"
43
+ + "Separate Model API Calls"
44
+ + "---------"
45
+ + "\n"
46
+ + prompt_chunk
47
+ )
48
+ return prompt
49
+
50
+
51
+ def generate_flant5_prompt_summ_chunk_context(query_text, context_list):
52
+ prompt = """"""
53
+ for chunk in context_list:
54
+ prompt_chunk = f"""Summarize: {chunk}"""
55
+ prompt = (
56
+ prompt
57
+ + "\n"
58
+ + "---------"
59
+ + "Separate Model API Calls"
60
+ + "---------"
61
+ + "\n"
62
+ + prompt_chunk
63
+ )
64
+ return prompt
65
+
66
+
67
+ def generate_flant5_prompt_instruct_chunk_context_single(query_text, chunk):
68
+ prompt = f"""Answer the question in long detailed sentences using the context.
69
+ Question: {query_text}
70
+ Context: {chunk}
71
+ Answer: """
72
+ return prompt
73
+
74
+
75
+ def generate_flant5_prompt_summ_chunk_context_single(query_text, chunk):
76
+ prompt = f"""summarize: {chunk}"""
77
+ return prompt
78
+
79
+
80
+ def get_context_list_prompt(prompt):
81
+ prompt_list = prompt.split("---------------------")
82
+ context = prompt_list[-2].strip()
83
+ context_list = context.split(" \n")
84
+ return context_list
85
+
86
+
87
+ def generate_gpt_j_two_shot_prompt_1(query_text, context_list):
88
+ context = " \n".join(context_list)
89
+ prompt = f"""Answer the Question in detail based on the Context in 7-9 descriptive and summarized sentences.
90
+
91
+ Question: What is Nvidia's visibility in the data center business?
92
+ Context: People still saw it as something esoteric. But today, data centers all over the world expect a very significant part of their data center being accelerated with GPUs. The number of workloads that we've accelerated since in the last 5 years have expanded tremendously, whether it's imaging or video or conversational AI or deep recommender systems that probably unquestionably, at this point, the most important machine learning model in the world. When we came -- when we started to introduce Ampere to the data center, it was very commonsensical to them that they would adopt it. They have a large amount of workload that's already accelerated by NVIDIA GPUs. And as you know, our GPUs are architecturally compatible from generation to generation. And I think every nation and government and scientific lab is now gearing up to think about what does it take to create a national defense system for each country that is based on computational methods? And NVIDIA is an accelerated computing company. We take something that otherwise would take a year in the case of Oak Ridge, and they filter 1 billion compounds in a day. And so notice, I've said 3 different architecture in a data center today. Most data centers today has a storage server, has CPU servers, and it has scale-up acceleration service with Voltas has scaled out servers with GeForce and then it has scale cloud computing, flexible servers based on V100. And so the ability to predict workload is so hard, and therefore, the utilization of these systems will be spiky. And then the second thing is we'd like to be able to innovate across the entire stack. You know that NVIDIA is just supremely obsessed about software stacks. And the reason for that is because software creates markets.
93
+ Answer: Nvidia has become a very significant part of the data center business in the last 5 years, with its GPUs being used to accelerate a wide range of workloads, from imaging and video to conversational AI and deep recommender systems. Data centers have been quick to adopt Nvidia's Ampere architecture, as it is architecturally compatible with previous generations of GPUs. Nvidia is also being used to create national defense systems for countries, with Oak Ridge National Laboratory using it to filter 1 billion compounds in a day. Data centers today typically have a combination of storage servers, CPU servers, and scale-up acceleration servers with Volta and GeForce, as well as scale cloud computing servers based on V100. Nvidia is focused on software stacks, as they believe software creates markets. Overall, Nvidia has become a major player in the data center business, with its GPUs being used to accelerate a wide range of workloads and its software stacks creating markets.
94
+ ###
95
+ Question: What is the update on the server chip roadmap and strategy?
96
+ Context: Navin, any... Maybe the only thing I'd add, John, is that from a product point of view, the dynamic to think about in 2019 is that, as Bob mentioned, we began shipping for production Cascade Lake, our next-generation Xeon. And really, that product is going to ramp -- start to ramp in the middle part of the year and into the second half of the year. The product features look very compelling. The AI capability we have with DL Boost, the support for Optane persistent memory, the security, hardware mitigation fixes, so that the customer momentum around that product line looks very strong. But it really doesn't ramp until the middle to the second half of the year. During the course of '19, our expectations are, of that mix, that we'll be more logic-oriented. And that's really driven by a couple of things: one, ensuring we have the capacity to meet the 14-nanometer demand for our customers; secondly, as we ramp 10-nanometer in 2019 and position for 10- in 2020, we'll invest additional capital there; and then third, obviously, our expectations are to continue to invest in next-node technology, in particular, 7-nanometer. So logic capital is going to be going up year-on-year. Again, 10-nanometer ramp, not really any different. I highlighted in the prepared remarks, we feel very good about kind of where we are in ramping 10-nanometer during the course of the year to get systems on the shelf for the holiday season, so no real change there. And modem and memory growth will be a little bit slower today versus where we were 90 days ago. I think, as Bob said, and I think we talked about a little bit, we had 3 quarters of really, really strong growth in 2018 in the cloud. And that was driven by a product cycle as well as a typical multiyear build-out pattern with Xeon Scalable. And if you look back at all the historical trends we've had in the cloud business, we've always said there's some lumpiness to the business.
97
+ Answer: Intel began shipping for production Cascade Lake, their next-generation Xeon, in 2019 and the product features look very compelling with AI capability, support for Optane persistent memory, and security hardware mitigation fixes. The product is expected to ramp up in the middle part of the year and into the second half of the year. Intel is investing in 14-nanometer capacity to meet customer demand, 10-nanometer technology for 2019 and 2020, and 7-nanometer technology. Logic capital is expected to increase year-on-year. Intel is investing in 10-nanometer technology to get systems on the shelf for the holiday season. Modem and memory growth is expected to be slower than it was 90 days ago due to the 3 quarters of strong growth in 2018 in the cloud.
98
+ ###
99
+ Question: {query_text}
100
+ Context: {context}
101
+ Answer:?"""
102
+ return prompt
103
+
104
+
105
+ def generate_gpt_j_two_shot_prompt_2(query_text, context_list):
106
+ context = " \n".join(context_list)
107
+ prompt = f"""Answer the Question in detail based on the Context in 7-9 descriptive and summarized sentences.
108
+
109
+ Question: What was discussed regarding Wearables revenue performance?
110
+ Context: Products revenue $79.1b. Up 8%, as iPhone returned to growth. Had incredibly strong results in Wearables, where Co. set all-time records for Apple Watch and AirPods. Services revenue grew 17% to new all-time record $12.7b with double-digit growth in every geographic segment, a new all-time records across portfolio. Among consumers and businesses, planning to purchase tablets in March qtr., 78% plan to purchase iPads. Wearables, Home & Accessories: Established new all-time record with revenue of $10b, up 37% YoverY with strong double-digit performance across all five geographic segments and growth across Wearables, Accessories and Home. Set all-time records for Wearables in virtually every market Co. tracks, even as it experienced some product shortages due to strong customer demand for Apple Watch and AirPods during the qtr. Continued to see strong demand for products in enterprise market, as technology solutions enabled businesses to do their best work. 100% of Fortune 500 companies in healthcare sector use AAPL technology in areas like patient experience, clinical communications and nursing workflows. Seeing smaller companies in this sector drive innovation with technology and apps. One example is Gauss Surgical, which uses Core ML in iOS to more accurately estimate blood loss during childbirth and surgery. This helps clinicians have more complete and timely information on whether a patient needs an intervention, which can impact both clinical outcomes and costs. Amit, it's Tim. If you look at the Apple -- or the Wearables as a category within the Wearables, Home and Accessories revenue, Wearables grew 44%, so it was very strong, as you say. The -- both Apple Watch and AirPods did very well in terms of collecting new customers. Apple Watch, in particular, 75% of the customers are new to the Apple Watch, and so it's still very much selling to new customers at this point. For the results from last quarter, we had double-digit growth for iPhone in Mainland China, so that was an important change from where we had been running. We also had double-digit growth in Services in Mainland China, and we had extremely strong double-digit on Wearables. And so really, there were a number of different factors.
111
+ Answer: Wearables revenue was part of the overall Products revenue of $79.1b, which was up 8%. Wearables, Home & Accessories revenue established a new all-time record with revenue of $10b, up 37% year-over-year. Wearables experienced strong double-digit performance across all five geographic segments and growth across Wearables, Accessories and Home. Apple Watch and AirPods set all-time records for Wearables in virtually every market the company tracks, despite some product shortages due to strong customer demand. Apple Watch had 75% of customers being new to the product. Wearables had double-digit growth in Mainland China.
112
+ ###
113
+ Question: How has the growth been for the PC market?
114
+ Context: Yes. So when we look at the PC market, we finished 2019 very strong in the overall PC market, both mobile and desktop. I think that's primarily on the strength of the product portfolio and the expanding customer platforms that we have. So let me talk first about the market, and then talk a little bit about how we're seeing the full year. So if you look at the PC market, I think, the discussion so far has been, let's call it, 2020, flat to maybe down slightly. There has been some concern raised about the second half of '20 perhaps be weakened -- weaker than normal seasonality just due to some of the enterprise refresh cycles that are strong in the first half. So we feel good about that. In the data center market, again, I would say that the growth of computing continues. From our standpoint, we see it as a good market environment for data center in both cloud as well as enterprise. I think the CPU opportunity is very immediate and in front of us as we look at the opportunities with Rome and the expanding opportunities. I think the data center GPU market continues to be an important growth vector for us, and now I call that over the several-year horizon. So when you look at the opportunities that we have, when we combine our CPU and GPU IP together, they're very, very strong. So I'm not sure I'm going to forecast a share target for 2020. I will say though, if you take a look back at the last 8 quarters, we've been on a fairly steady share gain in PCs, somewhere between -- depending on the quarter, let's call it, 50 to 100 basis points per quarter, and that changes between desktop and notebook. I think we grew somewhere on the order of 4 points a share.
115
+ Answer: AMD finished 2019 very strong in the overall PC market, both mobile and desktop, primarily due to the strength of their product portfolio and expanding customer platforms. The discussion for 2020 is that the PC market will be flat to slightly down, due to some concern about weaker than normal seasonality in the second half of the year. The data center market is a good environment for AMD, with CPU opportunities being very immediate and GPU opportunities being a growth vector over the next several years. Over the last 8 quarters, AMD has seen a steady share gain in PCs, ranging from 50 to 100 basis points per quarter, and growing 4 points of share overall. This share gain has been seen in both desktop and notebook PCs. AMD has seen strong growth in the PC market due to their product portfolio and expanding customer platforms, as well as their CPU and GPU IP.
116
+ ###
117
+ Question: {query_text}
118
+ Context: {context}
119
+ Answer:?"""
120
+ return prompt
utils/retriever.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def query_pinecone_sparse(
2
+ dense_vec,
3
+ sparse_vec,
4
+ top_k,
5
+ index,
6
+ year,
7
+ quarter,
8
+ ticker,
9
+ participant_type,
10
+ threshold=0.25,
11
+ ):
12
+ if participant_type == "Company Speaker":
13
+ participant = "Answer"
14
+ else:
15
+ participant = "Question"
16
+
17
+ if year == "All":
18
+ if quarter == "All":
19
+ xc = index.query(
20
+ vector=dense_vec,
21
+ sparse_vector=sparse_vec,
22
+ top_k=top_k,
23
+ filter={
24
+ "Year": {
25
+ "$in": [
26
+ int("2020"),
27
+ int("2019"),
28
+ int("2018"),
29
+ int("2017"),
30
+ int("2016"),
31
+ ]
32
+ },
33
+ "Quarter": {"$in": ["Q1", "Q2", "Q3", "Q4"]},
34
+ "Ticker": {"$eq": ticker},
35
+ "QA_Flag": {"$eq": participant},
36
+ },
37
+ include_metadata=True,
38
+ )
39
+ else:
40
+ xc = index.query(
41
+ vector=dense_vec,
42
+ sparse_vector=sparse_vec,
43
+ top_k=top_k,
44
+ filter={
45
+ "Year": {
46
+ "$in": [
47
+ int("2020"),
48
+ int("2019"),
49
+ int("2018"),
50
+ int("2017"),
51
+ int("2016"),
52
+ ]
53
+ },
54
+ "Quarter": {"$eq": quarter},
55
+ "Ticker": {"$eq": ticker},
56
+ "QA_Flag": {"$eq": participant},
57
+ },
58
+ include_metadata=True,
59
+ )
60
+ else:
61
+ # search pinecone index for context passage with the answer
62
+ xc = index.query(
63
+ vector=dense_vec,
64
+ sparse_vector=sparse_vec,
65
+ top_k=top_k,
66
+ filter={
67
+ "Year": int(year),
68
+ "Quarter": {"$eq": quarter},
69
+ "Ticker": {"$eq": ticker},
70
+ "QA_Flag": {"$eq": participant},
71
+ },
72
+ include_metadata=True,
73
+ )
74
+ # filter the context passages based on the score threshold
75
+ filtered_matches = []
76
+ for match in xc["matches"]:
77
+ if match["score"] >= threshold:
78
+ filtered_matches.append(match)
79
+ xc["matches"] = filtered_matches
80
+ return xc
81
+
82
+
83
+ def query_pinecone(
84
+ dense_vec,
85
+ top_k,
86
+ index,
87
+ year,
88
+ quarter,
89
+ ticker,
90
+ participant_type,
91
+ threshold=0.25,
92
+ ):
93
+ if participant_type == "Company Speaker":
94
+ participant = "Answer"
95
+ else:
96
+ participant = "Question"
97
+
98
+ if year == "All":
99
+ if quarter == "All":
100
+ xc = index.query(
101
+ vector=dense_vec,
102
+ top_k=top_k,
103
+ filter={
104
+ "Year": {
105
+ "$in": [
106
+ int("2020"),
107
+ int("2019"),
108
+ int("2018"),
109
+ int("2017"),
110
+ int("2016"),
111
+ ]
112
+ },
113
+ "Quarter": {"$in": ["Q1", "Q2", "Q3", "Q4"]},
114
+ "Ticker": {"$eq": ticker},
115
+ "QA_Flag": {"$eq": participant},
116
+ },
117
+ include_metadata=True,
118
+ )
119
+ else:
120
+ xc = index.query(
121
+ vector=dense_vec,
122
+ top_k=top_k,
123
+ filter={
124
+ "Year": {
125
+ "$in": [
126
+ int("2020"),
127
+ int("2019"),
128
+ int("2018"),
129
+ int("2017"),
130
+ int("2016"),
131
+ ]
132
+ },
133
+ "Quarter": {"$eq": quarter},
134
+ "Ticker": {"$eq": ticker},
135
+ "QA_Flag": {"$eq": participant},
136
+ },
137
+ include_metadata=True,
138
+ )
139
+ else:
140
+ # search pinecone index for context passage with the answer
141
+ xc = index.query(
142
+ vector=dense_vec,
143
+ top_k=top_k,
144
+ filter={
145
+ "Year": int(year),
146
+ "Quarter": {"$eq": quarter},
147
+ "Ticker": {"$eq": ticker},
148
+ "QA_Flag": {"$eq": participant},
149
+ },
150
+ include_metadata=True,
151
+ )
152
+ # filter the context passages based on the score threshold
153
+ filtered_matches = []
154
+ for match in xc["matches"]:
155
+ if match["score"] >= threshold:
156
+ filtered_matches.append(match)
157
+ xc["matches"] = filtered_matches
158
+ return xc
159
+
160
+
161
+ def format_query(query_results):
162
+ # extract passage_text from Pinecone search result
163
+ context = [
164
+ result["metadata"]["Text"] for result in query_results["matches"]
165
+ ]
166
+ return context
167
+
168
+
169
+ def sentence_id_combine(data, query_results, lag=1):
170
+ # Extract sentence IDs from query results
171
+ ids = [
172
+ result["metadata"]["Sentence_id"]
173
+ for result in query_results["matches"]
174
+ ]
175
+ # Generate new IDs by adding a lag value to the original IDs
176
+ new_ids = [id + i for id in ids for i in range(-lag, lag + 1)]
177
+ # Remove duplicates and sort the new IDs
178
+ new_ids = sorted(set(new_ids))
179
+ # Create a list of lookup IDs by grouping the new IDs in groups of lag*2+1
180
+ lookup_ids = [
181
+ new_ids[i : i + (lag * 2 + 1)]
182
+ for i in range(0, len(new_ids), lag * 2 + 1)
183
+ ]
184
+ # Create a list of context sentences by joining the sentences
185
+ # corresponding to the lookup IDs
186
+ context_list = [
187
+ " ".join(
188
+ data.loc[data["Sentence_id"].isin(lookup_id), "Text"].to_list()
189
+ )
190
+ for lookup_id in lookup_ids
191
+ ]
192
+ return context_list
193
+
194
+
195
+ def text_lookup(data, sentence_ids):
196
+ context = ". ".join(data.iloc[sentence_ids].to_list())
197
+ return context
utils/transcript_retrieval.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Transcript Retrieval
2
+
3
+
4
+ def retrieve_transcript(data, year, quarter, ticker):
5
+ if year == "All" or quarter == "All":
6
+ row = (
7
+ data.loc[
8
+ (data.Ticker == ticker),
9
+ ["File_Name"],
10
+ ]
11
+ .drop_duplicates()
12
+ .iloc[0, 0]
13
+ )
14
+ else:
15
+ row = (
16
+ data.loc[
17
+ (data.Year == int(year))
18
+ & (data.Quarter == quarter)
19
+ & (data.Ticker == ticker),
20
+ ["File_Name"],
21
+ ]
22
+ .drop_duplicates()
23
+ .iloc[0, 0]
24
+ )
25
+ # convert row to a string and join values with "-"
26
+ # row_str = "-".join(row.astype(str)) + ".txt"
27
+ open_file = open(
28
+ f"Transcripts/{ticker}/{row}",
29
+ "r",
30
+ )
31
+ file_text = open_file.read()
32
+ return f"""{file_text}"""
utils/vector_index.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ def create_dense_embeddings(query, model):
5
+ dense_emb = model.encode([query]).tolist()
6
+ return dense_emb
7
+
8
+
9
+ def create_sparse_embeddings(query, model, tokenizer):
10
+ device = "cuda" if torch.cuda.is_available() else "cpu"
11
+ inputs = tokenizer(query, return_tensors="pt").to(device)
12
+
13
+ with torch.no_grad():
14
+ logits = model(**inputs).logits
15
+
16
+ inter = torch.log1p(torch.relu(logits[0]))
17
+ token_max = torch.max(inter, dim=0) # sum over input tokens
18
+ nz_tokens = torch.where(token_max.values > 0)[0]
19
+ nz_weights = token_max.values[nz_tokens]
20
+
21
+ order = torch.sort(nz_weights, descending=True)
22
+ nz_weights = nz_weights[order[1]]
23
+ nz_tokens = nz_tokens[order[1]]
24
+ return {
25
+ "indices": nz_tokens.cpu().numpy().tolist(),
26
+ "values": nz_weights.cpu().numpy().tolist(),
27
+ }
28
+
29
+
30
+ def hybrid_score_norm(dense, sparse, alpha: float):
31
+ """Hybrid score using a convex combination
32
+
33
+ alpha * dense + (1 - alpha) * sparse
34
+
35
+ Args:
36
+ dense: Array of floats representing
37
+ sparse: a dict of `indices` and `values`
38
+ alpha: scale between 0 and 1
39
+ """
40
+ if alpha < 0 or alpha > 1:
41
+ raise ValueError("Alpha must be between 0 and 1")
42
+ hs = {
43
+ "indices": sparse["indices"],
44
+ "values": [v * (1 - alpha) for v in sparse["values"]],
45
+ }
46
+ return [v * alpha for v in dense], hs