Spaces:
Sleeping
Sleeping
Angelawork
commited on
Commit
·
4563ea0
1
Parent(s):
7222a6a
single output gradio app
Browse files
app.py
ADDED
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import urllib.request
|
3 |
+
import gradio as gr
|
4 |
+
from transformers import T5Tokenizer, T5ForConditionalGeneration
|
5 |
+
import huggingface_hub
|
6 |
+
import re
|
7 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
8 |
+
import torch
|
9 |
+
import time
|
10 |
+
import transformers
|
11 |
+
import requests
|
12 |
+
import globals
|
13 |
+
from utility import *
|
14 |
+
|
15 |
+
"""set up"""
|
16 |
+
huggingface_hub.login(token=globals.HF_TOKEN)
|
17 |
+
gemma_tokenizer = AutoTokenizer.from_pretrained(globals.gemma_2b_URL)
|
18 |
+
gemma_model = AutoModelForCausalLM.from_pretrained(globals.gemma_2b_URL)
|
19 |
+
|
20 |
+
falcon_tokenizer = AutoTokenizer.from_pretrained(globals.falcon_7b_URL, trust_remote_code=True, device_map=globals.device_map, offload_folder="offload")
|
21 |
+
falcon_model = AutoModelForCausalLM.from_pretrained(globals.falcon_7b_URL, trust_remote_code=True,
|
22 |
+
torch_dtype=torch.bfloat16, device_map=globals.device_map, offload_folder="offload")
|
23 |
+
|
24 |
+
def get_model(model_typ):
|
25 |
+
if model_typ not in ["gemma", "falcon", "falcon_api", "simplet5_base", "simplet5_large"]:
|
26 |
+
raise ValueError('Invalid model type. Choose "gemma", "falcon", "falcon_api","simplet5_base", "simplet5_large".')
|
27 |
+
if model_typ=="gemma":
|
28 |
+
tokenizer = gemma_tokenizer
|
29 |
+
model = gemma_model
|
30 |
+
prefix = globals.gemma_PREFIX
|
31 |
+
elif model_typ=="falcon_api":
|
32 |
+
prefix = globals.falcon_PREFIX
|
33 |
+
model=None
|
34 |
+
tokenizer = None
|
35 |
+
elif model_typ=="falcon":
|
36 |
+
tokenizer = falcon_tokenizer
|
37 |
+
model = falcon_model
|
38 |
+
prefix = globals.falcon_PREFIX
|
39 |
+
elif model_typ in ["simplet5_base","simplet5_large"]:
|
40 |
+
prefix = globals.simplet5_PREFIX
|
41 |
+
URL = globals.simplet5_base_URL if model_typ=="simplet5_base" else globals.simplet5_large_URL
|
42 |
+
T5_MODEL_PATH = f"https://huggingface.co/{URL}/resolve/main/{globals.T5_FILE_NAME}"
|
43 |
+
fetch_model(T5_MODEL_PATH, globals.T5_FILE_NAME)
|
44 |
+
tokenizer = T5Tokenizer.from_pretrained(URL)
|
45 |
+
model = T5ForConditionalGeneration.from_pretrained(URL)
|
46 |
+
return model, tokenizer, prefix
|
47 |
+
|
48 |
+
def single_query(model_typ="gemma",prompt="She has a heart of gold",
|
49 |
+
max_length=256,
|
50 |
+
api_token=""):
|
51 |
+
model, tokenizer, prefix = get_model(model_typ)
|
52 |
+
if api_token=="" and model_typ=="falcon_api":
|
53 |
+
return "Warning: Aborted, Access token needed to access HuggingFace FalconAPI"
|
54 |
+
|
55 |
+
start_time = time.time()
|
56 |
+
input = prefix.replace("{fig}", prompt)
|
57 |
+
print(f"Input to model: \n{input}")
|
58 |
+
|
59 |
+
if model_typ == "simplet5_base" or model_typ == "simplet5_large":
|
60 |
+
inputs = tokenizer(input, return_tensors="pt")
|
61 |
+
outputs = model.generate(
|
62 |
+
inputs["input_ids"],
|
63 |
+
temperature=0.7,
|
64 |
+
max_length=max_length,
|
65 |
+
num_beams=5,
|
66 |
+
top_k=10,
|
67 |
+
do_sample=True,
|
68 |
+
num_return_sequences=1,
|
69 |
+
early_stopping=True
|
70 |
+
)
|
71 |
+
answer = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
72 |
+
elif model_typ=="gemma":
|
73 |
+
inputs = tokenizer(input, return_tensors="pt")
|
74 |
+
generate_ids = model.generate(inputs.input_ids, max_length=max_length)
|
75 |
+
output= tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
76 |
+
print(f"Model original output:{output}\n")
|
77 |
+
answer = post_process(output,input)
|
78 |
+
# pattern = r"\*\*Literal Meaning:\*\*\s*(.*?)(?:\n\n|$)"
|
79 |
+
# match = re.search(pattern, output, re.DOTALL)
|
80 |
+
# if match:
|
81 |
+
# answer = match.group(1).strip()
|
82 |
+
# else:
|
83 |
+
# answer = output
|
84 |
+
|
85 |
+
elif model_typ=="falcon":
|
86 |
+
falcon_pipeline = transformers.pipeline(
|
87 |
+
"text-generation",
|
88 |
+
model=model,
|
89 |
+
tokenizer=tokenizer,
|
90 |
+
)
|
91 |
+
sequences = falcon_pipeline(
|
92 |
+
prompt,
|
93 |
+
max_length=max_length,
|
94 |
+
do_sample=False, # processing time too long, disable sampling for deterministic output
|
95 |
+
num_return_sequences=1,
|
96 |
+
eos_token_id=falcon_tokenizer.eos_token_id,
|
97 |
+
)
|
98 |
+
for seq in sequences:
|
99 |
+
print(f"Result: \n{seq['generated_text']}")
|
100 |
+
elif model_typ=="falcon_api":
|
101 |
+
API_URL = "https://api-inference.huggingface.co/models/tiiuae/falcon-7b-instruct"
|
102 |
+
headers = {"Authorization": f"Bearer {api_token}"}
|
103 |
+
payload = {
|
104 |
+
"inputs": input,
|
105 |
+
"parameters": {
|
106 |
+
"temperature": 0.7,
|
107 |
+
"max_length": max_length,
|
108 |
+
"num_return_sequences": 1
|
109 |
+
}
|
110 |
+
}
|
111 |
+
output = api_query(API_URL=API_URL,headers=headers,payload=payload)
|
112 |
+
answer = output[0]["generated_text"]
|
113 |
+
answer = post_process(answer,input)
|
114 |
+
|
115 |
+
else:
|
116 |
+
raise ValueError('Invalid model type. Choose "gemma", "falcon", "falcon_api","simplet5_base", "simplet5_large".')
|
117 |
+
|
118 |
+
print(f"Time taken: {time.time()-start_time:.2f} seconds")
|
119 |
+
print(f"processed model output: {answer}")
|
120 |
+
|
121 |
+
return answer
|
122 |
+
|
123 |
+
model_types = ["gemma", "falcon", "falcon_api", "simplet5_base", "simplet5_large"]
|
124 |
+
|
125 |
+
single_gradio = gr.Interface(
|
126 |
+
fn=single_query,
|
127 |
+
inputs=[
|
128 |
+
|
129 |
+
gr.Dropdown(choices=model_types, label="Select Model Type"),
|
130 |
+
gr.Textbox(lines=2, placeholder="Enter a sentence...", label="Input Sentence"),
|
131 |
+
gr.Slider(minimum=50, maximum=512, step=10, value=256, label="Max Length"),
|
132 |
+
gr.Textbox(lines=1, placeholder="Enter your API token", label="HuggingFace Token",value=""),
|
133 |
+
],
|
134 |
+
outputs="text",
|
135 |
+
theme=gr.themes.Soft(),
|
136 |
+
title=globals.TITLE,
|
137 |
+
description="Select a model type from the dropdown and input a sentence to get the paraphrased literal meaning",
|
138 |
+
examples=globals.XAMPLE
|
139 |
+
)
|
140 |
+
|
141 |
+
if __name__ == '__main__':
|
142 |
+
single_gradio.launch()
|