import re import openai import pandas as pd import pinecone import spacy import streamlit_scrollable_textbox as stx import torch from sentence_transformers import SentenceTransformer from tqdm import tqdm from transformers import ( AutoModelForMaskedLM, AutoModelForSeq2SeqLM, AutoTokenizer, pipeline, ) from transformers import T5Tokenizer, T5ForConditionalGeneration import streamlit as st @st.experimental_singleton def get_data(): data = pd.read_csv("earnings_calls_cleaned_metadata.csv") return data # Initialize Spacy Model @st.experimental_singleton def get_spacy_model(): return spacy.load("en_core_web_sm") # Initialize models from HuggingFace @st.experimental_singleton def get_t5_model(): return pipeline("summarization", model="t5-small", tokenizer="t5-small") @st.experimental_singleton def get_flan_t5_model(): tokenizer = T5Tokenizer.from_pretrained("google/flan-t5-large") model = T5ForConditionalGeneration.from_pretrained("google/flan-t5-large") return model, tokenizer @st.experimental_singleton def get_mpnet_embedding_model(): device = "cuda" if torch.cuda.is_available() else "cpu" model = SentenceTransformer( "sentence-transformers/all-mpnet-base-v2", device=device ) model.max_seq_length = 512 return model @st.experimental_singleton def get_splade_sparse_embedding_model(): model_sparse = "naver/splade-cocondenser-ensembledistil" # check device device = "cuda" if torch.cuda.is_available() else "cpu" tokenizer = AutoTokenizer.from_pretrained(model_sparse) model_sparse = AutoModelForMaskedLM.from_pretrained(model_sparse) # move to gpu if available model_sparse.to(device) return model_sparse, tokenizer @st.experimental_singleton def get_sgpt_embedding_model(): device = "cuda" if torch.cuda.is_available() else "cpu" model = SentenceTransformer( "Muennighoff/SGPT-125M-weightedmean-nli-bitfit", device=device ) model.max_seq_length = 512 return model @st.experimental_memo def save_key(api_key): return api_key def create_dense_embeddings(query, model): dense_emb = model.encode([query]).tolist() return dense_emb def create_sparse_embeddings(query, model, tokenizer): device = "cuda" if torch.cuda.is_available() else "cpu" inputs = tokenizer(query, return_tensors="pt").to(device) with torch.no_grad(): logits = model(**inputs).logits inter = torch.log1p(torch.relu(logits[0])) token_max = torch.max(inter, dim=0) # sum over input tokens nz_tokens = torch.where(token_max.values > 0)[0] nz_weights = token_max.values[nz_tokens] order = torch.sort(nz_weights, descending=True) nz_weights = nz_weights[order[1]] nz_tokens = nz_tokens[order[1]] return { "indices": nz_tokens.cpu().numpy().tolist(), "values": nz_weights.cpu().numpy().tolist(), } def hybrid_score_norm(dense, sparse, alpha: float): """Hybrid score using a convex combination alpha * dense + (1 - alpha) * sparse Args: dense: Array of floats representing sparse: a dict of `indices` and `values` alpha: scale between 0 and 1 """ if alpha < 0 or alpha > 1: raise ValueError("Alpha must be between 0 and 1") hs = { "indices": sparse["indices"], "values": [v * (1 - alpha) for v in sparse["values"]], } return [v * alpha for v in dense], hs def query_pinecone_sparse( dense_vec, sparse_vec, top_k, index, year, quarter, ticker, participant_type, threshold=0.25, ): if participant_type == "Company Speaker": participant = "Answer" else: participant = "Question" if year == "All": if quarter == "All": xc = index.query( vector=dense_vec, sparse_vector=sparse_vec, top_k=top_k, filter={ "Year": { "$in": [ int("2020"), int("2019"), int("2018"), int("2017"), int("2016"), ] }, "Quarter": {"$in": ["Q1", "Q2", "Q3", "Q4"]}, "Ticker": {"$eq": ticker}, "QA_Flag": {"$eq": participant}, }, include_metadata=True, ) else: xc = index.query( vector=dense_vec, sparse_vector=sparse_vec, top_k=top_k, filter={ "Year": { "$in": [ int("2020"), int("2019"), int("2018"), int("2017"), int("2016"), ] }, "Quarter": {"$eq": quarter}, "Ticker": {"$eq": ticker}, "QA_Flag": {"$eq": participant}, }, include_metadata=True, ) else: # search pinecone index for context passage with the answer xc = index.query( vector=dense_vec, sparse_vector=sparse_vec, top_k=top_k, filter={ "Year": int(year), "Quarter": {"$eq": quarter}, "Ticker": {"$eq": ticker}, "QA_Flag": {"$eq": participant}, }, include_metadata=True, ) # filter the context passages based on the score threshold filtered_matches = [] for match in xc["matches"]: if match["score"] >= threshold: filtered_matches.append(match) xc["matches"] = filtered_matches return xc def query_pinecone( dense_vec, top_k, index, year, quarter, ticker, participant_type, threshold=0.25, ): if participant_type == "Company Speaker": participant = "Answer" else: participant = "Question" if year == "All": if quarter == "All": xc = index.query( vector=dense_vec, top_k=top_k, filter={ "Year": { "$in": [ int("2020"), int("2019"), int("2018"), int("2017"), int("2016"), ] }, "Quarter": {"$in": ["Q1", "Q2", "Q3", "Q4"]}, "Ticker": {"$eq": ticker}, "QA_Flag": {"$eq": participant}, }, include_metadata=True, ) else: xc = index.query( vector=dense_vec, top_k=top_k, filter={ "Year": { "$in": [ int("2020"), int("2019"), int("2018"), int("2017"), int("2016"), ] }, "Quarter": {"$eq": quarter}, "Ticker": {"$eq": ticker}, "QA_Flag": {"$eq": participant}, }, include_metadata=True, ) else: # search pinecone index for context passage with the answer xc = index.query( vector=dense_vec, top_k=top_k, filter={ "Year": int(year), "Quarter": {"$eq": quarter}, "Ticker": {"$eq": ticker}, "QA_Flag": {"$eq": participant}, }, include_metadata=True, ) # filter the context passages based on the score threshold filtered_matches = [] for match in xc["matches"]: if match["score"] >= threshold: filtered_matches.append(match) xc["matches"] = filtered_matches return xc def format_query(query_results): # extract passage_text from Pinecone search result context = [ result["metadata"]["Text"] for result in query_results["matches"] ] return context def sentence_id_combine(data, query_results, lag=1): # Extract sentence IDs from query results ids = [ result["metadata"]["Sentence_id"] for result in query_results["matches"] ] # Generate new IDs by adding a lag value to the original IDs new_ids = [id + i for id in ids for i in range(-lag, lag + 1)] # Remove duplicates and sort the new IDs new_ids = sorted(set(new_ids)) # Create a list of lookup IDs by grouping the new IDs in groups of lag*2+1 lookup_ids = [ new_ids[i : i + (lag * 2 + 1)] for i in range(0, len(new_ids), lag * 2 + 1) ] # Create a list of context sentences by joining the sentences corresponding to the lookup IDs context_list = [ " ".join( data.loc[data["Sentence_id"].isin(lookup_id), "Text"].to_list() ) for lookup_id in lookup_ids ] return context_list def text_lookup(data, sentence_ids): context = ". ".join(data.iloc[sentence_ids].to_list()) return context def generate_gpt_prompt(query_text, context_list): context = " ".join(context_list) 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. Context: {context} Question: {query_text} Answer:""" return prompt def generate_gpt_prompt_2(query_text, context_list): context = " ".join(context_list) prompt = f""" Context information is below: --------------------- {context} --------------------- Given the context information and prior knowledge, answer this question: {query_text} Try to include as many key details as possible and format the answer in points.""" return prompt def generate_flant5_prompt_instruct_complete_context(query_text, context_list): context = " ".join(context_list) prompt = f"""Answer the question in long detailed sentences using the context. Question: {query_text} Context: {context} Answer: """ return prompt def generate_flant5_prompt_instruct_chunk_context(query_text, context_list): prompt = """""" for chunk in context_list: prompt_chunk = f"""Answer the question in long detailed sentences using the context. Question: {query_text} Context: {chunk} Answer: """ prompt = ( prompt + "\n" + "---------" + "Separate Model API Calls" + "---------" + "\n" + prompt_chunk ) return prompt def generate_flant5_prompt_summ_chunk_context(query_text, context_list): prompt = """""" for chunk in context_list: prompt_chunk = f"""Summarize: {chunk}""" prompt = ( prompt + "\n" + "---------" + "Separate Model API Calls" + "---------" + "\n" + prompt_chunk ) return prompt def generate_flant5_prompt_instruct_chunk_context_single(query_text, chunk): prompt = f"""Answer the question in long detailed sentences using the context. Question: {query_text} Context: {chunk} Answer: """ return prompt def generate_flant5_prompt_summ_chunk_context_single(query_text, chunk): prompt = f"""summarize: {chunk}""" return prompt def generate_text_flan_t5(model, tokenizer, input_text): input_ids = tokenizer(input_text, return_tensors="pt").input_ids outputs = model.generate(input_ids, temperature=0.5, max_length=512) return tokenizer.decode(outputs[0], skip_special_tokens=True) def get_context_list_prompt(prompt): prompt_list = prompt.split("---------------------") context = prompt_list[-2].strip() context_list = context.split(" \n") return context_list def gpt_model(prompt): response = openai.Completion.create( model="text-davinci-003", prompt=prompt, temperature=0, max_tokens=1024, ) return response.choices[0].text def generate_gpt_j_two_shot_prompt_1(query_text, context_list): context = " \n".join(context_list) prompt = f"""Answer the Question in detail based on the Context in 7-9 descriptive and summarized sentences. Question: What is Nvidia's visibility in the data center business? 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. 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. ### Question: What is the update on the server chip roadmap and strategy? 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. 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. ### Question: {query_text} Context: {context} Answer:?""" return prompt def generate_gpt_j_two_shot_prompt_2(query_text, context_list): context = " \n".join(context_list) prompt = f"""Answer the Question in detail based on the Context in 7-9 descriptive and summarized sentences. Question: What was discussed regarding Wearables revenue performance? 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. 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. ### Question: How has the growth been for the PC market? 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. 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. ### Question: {query_text} Context: {context} Answer:?""" return prompt # Entity Extraction def extract_quarter_year(string): # Extract year from string year_match = re.search(r"\d{4}", string) if year_match: year = year_match.group() else: return None, None # Extract quarter from string quarter_match = re.search(r"Q\d", string) if quarter_match: quarter = "Q" + quarter_match.group()[1] else: return None, None return quarter, year def extract_entities(query, model): doc = model(query) entities = {ent.label_: ent.text for ent in doc.ents} if "ORG" in entities.keys(): company = entities["ORG"].lower() if "DATE" in entities.keys(): quarter, year = extract_quarter_year(entities["DATE"]) return company, quarter, year else: return company, None, None else: if "DATE" in entities.keys(): quarter, year = extract_quarter_year(entities["DATE"]) return None, quarter, year else: return None, None, None def clean_entities(company, quarter, year): company_ticker_map = { "apple": "AAPL", "amd": "AMD", "amazon": "AMZN", "cisco": "CSCO", "google": "GOOGL", "microsoft": "MSFT", "nvidia": "NVDA", "asml": "ASML", "intel": "INTC", "micron": "MU", } ticker_choice = [ "AAPL", "CSCO", "MSFT", "ASML", "NVDA", "GOOGL", "MU", "INTC", "AMZN", "AMD", ] year_choice = ["2020", "2019", "2018", "2017", "2016", "All"] quarter_choice = ["Q1", "Q2", "Q3", "Q4", "All"] if company is not None: if company in company_ticker_map.keys(): ticker = company_ticker_map[company] ticker_index = ticker_choice.index(ticker) else: ticker_index = 0 else: ticker_index = 0 if quarter is not None: if quarter in quarter_choice: quarter_index = quarter_choice.index(quarter) else: quarter_index = len(quarter_choice) - 1 else: quarter_index = len(quarter_choice) - 1 if year is not None: if year in year_choice: year_index = year_choice.index(year) else: year_index = len(year_choice) - 1 else: year_index = len(year_choice) - 1 return ticker_index, quarter_index, year_index # Transcript Retrieval def retrieve_transcript(data, year, quarter, ticker): if year == "All" or quarter == "All": row = ( data.loc[ (data.Ticker == ticker), ["File_Name"], ] .drop_duplicates() .iloc[0, 0] ) else: row = ( data.loc[ (data.Year == int(year)) & (data.Quarter == quarter) & (data.Ticker == ticker), ["File_Name"], ] .drop_duplicates() .iloc[0, 0] ) # convert row to a string and join values with "-" # row_str = "-".join(row.astype(str)) + ".txt" open_file = open( f"Transcripts/{ticker}/{row}", "r", ) file_text = open_file.read() return file_text