File size: 1,922 Bytes
5ec8c71
 
 
 
 
 
ee65db2
5ec8c71
ee65db2
5ec8c71
ee65db2
 
5ec8c71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee65db2
5ec8c71
 
 
 
 
 
 
 
 
 
 
 
f308447
5ec8c71
 
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
import os
import gradio as gr
import torch
from peft import PeftModel, PeftConfig
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer

def load_data(file_obj):
    """
    Load data from the file object of the gr.File() inputs
    """
    path = file_obj.name
    with open(path, "r") as f:
        data = f.read()

    return data

def preprocessing(data):      
    texts = list()

    i = 0
    if len(data) <= i+4000:
        texts = data
    else:
        while len(data[i:]) != 0:
            if len(data[i:]) > 4000:
                string = str(data[i:i+4000])
                texts.append(string)
                i = i + 3800
            else:
                string = str(data[i:])
                texts.append(string)
                break    
    return texts

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

peft_model_id = "sooolee/flan-t5-base-cnn-samsum-lora"
config = PeftConfig.from_pretrained(peft_model_id)
tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path)
model = AutoModelForSeq2SeqLM.from_pretrained(config.base_model_name_or_path, device_map='auto') # load_in_8bit=True,
model = PeftModel.from_pretrained(model, peft_model_id, device_map='auto')

def summarize(path):
    transcript = load_data(file_obj)
    texts = preprocessing(transcript)
    inputs = tokenizer(texts, return_tensors="pt", padding=True, )

    with torch.no_grad():
        output_tokens = model.generate(input_ids=inputs["input_ids"].to("cuda"), max_new_tokens=60, do_sample=True, top_p=0.9)
        outputs = tokenizer.batch_decode(output_tokens.detach().cpu().numpy(), skip_special_tokens=True)
    
    return outputs

gr.Interface(
    fn=summarize,
    title = 'Summarize Transcripts',
    inputs = gr.File(file_types=["text"], label="Upload a text file.", interactive=True),
    outputs = gr.Textbox(label="Summary", max_lines=120, interactive=False),
).launch()