File size: 31,483 Bytes
9c49e99
244a3e0
 
9c49e99
e375940
f9da573
9c49e99
e375940
f9da573
 
e375940
f9da573
e375940
f9da573
e375940
0175cb6
 
e375940
f9da573
e375940
0175cb6
e375940
f9da573
 
 
 
8d46199
f9da573
 
 
9c49e99
 
 
 
 
 
 
 
0175cb6
 
c658480
 
5482130
26de0f1
0175cb6
f9da573
 
 
 
 
 
 
 
 
 
6627aee
 
 
f9da573
 
 
 
 
 
 
 
 
 
 
 
e375940
 
 
 
 
 
 
 
 
 
 
 
f9da573
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e375940
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac5b87a
e375940
 
 
 
 
 
 
 
ac5b87a
 
6966109
ac5b87a
6966109
ac5b87a
 
 
 
e375940
ac5b87a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e375940
ac5b87a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e375940
ac5b87a
 
 
 
 
 
 
 
 
f9da573
 
 
 
 
 
 
 
 
 
 
e375940
 
 
f9da573
 
 
ac5b87a
f9da573
e375940
 
 
 
f9da573
 
 
 
 
 
e375940
 
f9da573
 
 
e375940
 
 
 
f9da573
 
 
 
 
 
 
 
 
9c49e99
bf8b612
9b8f482
bf8b612
 
 
2b221a0
 
 
9c49e99
bf8b612
9975133
 
 
8d46199
9975133
 
 
 
 
 
 
6627aee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c49e99
 
 
6627aee
 
 
 
 
 
 
 
 
 
 
9c49e99
 
 
 
 
 
 
9975133
f9da573
 
9975133
fe54061
bf8b612
f9da573
 
 
 
6627aee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c49e99
 
5482130
 
 
 
 
 
 
 
 
 
 
 
 
 
ab04112
 
5482130
ab04112
5482130
 
 
 
 
ab04112
 
5482130
ab04112
5482130
 
ab04112
 
5482130
 
 
 
 
 
244a3e0
 
ab04112
 
244a3e0
 
 
ab04112
244a3e0
ab04112
 
 
 
 
 
 
244a3e0
 
5482130
244a3e0
5482130
 
 
 
 
 
 
 
 
 
0175cb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab04112
 
0175cb6
 
9c49e99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9da573
 
 
 
6966109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9da573
2b221a0
f9da573
8d46199
f9da573
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
import re
import json
import requests

import openai
import pandas as pd
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,
    T5ForConditionalGeneration,
    T5Tokenizer,
    pipeline,
)

import pinecone
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")


@st.experimental_singleton
def get_flan_alpaca_xl_model():
    model = AutoModelForSeq2SeqLM.from_pretrained("/home/user/app/models/flan-alpaca-xl/")
    tokenizer = AutoTokenizer.from_pretrained("/home/user/app/models/flan-alpaca-xl/")
    return model, tokenizer


# 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 generate_alpaca_ner_prompt(query):
    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.

### Instruction:
- The output should be in the form "Company - Value, Quarter - Value, Year - Value".
- The output should be in the form "Company - None, Quarter - None, Year - None", if no entities are found.
- Only use entities that exist in the final sentence.
- If Company cannot be found in the sentence, return "none" for that entity.
- If Quarter cannot be found in the sentence, return "none" for that entity.
- If Year cannot be found in the sentence, return "none" for that entity.
- If there is ambiguity finding the entity, return "none" for that entity.

### Input:

What was discussed regarding Services revenue performance in Apple's Q3 2020 earnings call?
Company - Apple, Quarter - Q3, Year - 2020

How has the growth in Q1 been for the consumer market as seen by AMD?
Company - AMD, Quarter - Q1, Year - none

What was the long term view on GOOGL's cloud business growth as discussed in their earnings call?
Company - Google, Quarter - none, Year - none

What is Nvidia's outlook in the data center business in Q3 2020?
Company - Nvidia, Quarter - Q3, Year - 2020

What are the expansion plans of Amazon in the Asia Pacific region as discussed in their earnings call?
Company - Amazon, Quarter - none, Year - none

What did the Analysts ask about CSCO's cybersecurity business in the earnings call in 2016?
Company - Cisco, Quarter - none, Year - 2016


{query}
### Response:"""
    return prompt

def generate_entities_flan_alpaca_inference_api(prompt):
    API_URL = "https://api-inference.huggingface.co/models/declare-lab/flan-alpaca-xl"
    API_TOKEN = st.secrets["hg_key"]
    headers = {"Authorization": f"Bearer {API_TOKEN}"}
    payload = {
        "inputs": prompt,
        "parameters": {"do_sample": True, "temperature":0.1, "max_length":80},
        "options": {"use_cache": False, "wait_for_model": True}
    }
    try:
        data = json.dumps(payload)
        response = requests.request("POST", API_URL, data=data)
        output = json.loads(response.content.decode("utf-8"))[0]["generated_text"]
    except:
        output = ""
    print(output)
    return output


def generate_entities_flan_alpaca_checkpoint(model, tokenizer, prompt):
    model_inputs = tokenizer(prompt, return_tensors="pt")
    input_ids = inputs["input_ids"]
    generation_output = model.generate(
        input_ids=input_ids,
        temperature=0.1,
        top_p=0.5,
        max_new_tokens=1024,
    )
    output = tokenizer.decode(generation_output[0], skip_special_tokens=True)
    return output


def format_entities_flan_alpaca(model_output):
    """
    Extracts the text for each entity from the output generated by the 
    Flan-Alpaca model.
    """
    try:
        company_string, quarter_string, year_string = values.split(", ")
    except:
        company = None
        quarter = None
        year = None
    try:
        company = company_string.split(" - ")[1].lower()
        company = None if company.lower() == 'none' else company
    except:
        company = None
    try:
        quarter = quarter_string.split(" - ")[1]
        quarter = None if quarter.lower() == 'none' else quarter

    except:
        quarter = None
    try:
        year = year_string.split(" - ")[1]
        year = None if year.lower() == 'none' else year

    except:
        year = None
    
    print((company, quarter, year))
    return company, quarter, year


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