SivaResearch commited on
Commit
e7d9402
·
verified ·
1 Parent(s): 6c4d912

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -112
app.py CHANGED
@@ -1,128 +1,65 @@
1
- import gradio as gr
2
  from transformers import AutoTokenizer, AutoModelForCausalLM
 
3
 
4
- tokenizer = AutoTokenizer.from_pretrained("ai4bharat/Airavata")
5
- model = AutoModelForCausalLM.from_pretrained("ai4bharat/Airavata")
6
-
7
- def generate_response(prompt):
8
- input_ids = tokenizer.encode(prompt, return_tensors="pt", max_length=50)
9
- output_ids = model.generate(input_ids, max_length=100, num_beams=5, no_repeat_ngram_size=2)
10
- response = tokenizer.decode(output_ids[0], skip_special_tokens=True)
11
- return response
12
-
13
- iface = gr.Interface(
14
- fn=generate_response,
15
- inputs="text",
16
- outputs="text",
17
- live=True,
18
- title="Airavata LLMs Chatbot",
19
- description="Ask me anything, and I'll generate a response!",
20
- theme="light",
21
- )
22
-
23
- iface.launch()
24
-
25
-
26
-
27
-
28
-
29
-
30
-
31
-
32
-
33
-
34
-
35
-
36
- # import torch
37
- # from transformers import AutoTokenizer, AutoModelForCausalLM
38
- # import gradio as gr
39
-
40
- # model_name = "ai4bharat/Airavata"
41
- # tokenizer = AutoTokenizer.from_pretrained(model_name, padding_side="left")
42
- # model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16)
43
-
44
- # SYSTEM_PROMPT = """<s>[INST] <<SYS>>
45
- # नमस्कार! आप अब कृषि विशेषज्ञता बॉट के साथ इंटरैक्ट कर रहे हैं—एक उन्नत AI जो कृषि क्षेत्र में विशेषज्ञता प्रदान करने के लिए डिज़ाइन किया गया है।
46
-
47
- # कृपया ध्यान दें कि यह बॉट केवल हिंदी में जवाब देगा। इसकी क्षमताएँ शामिल हैं:
48
-
49
- # 1. आधुनिक फसल प्रबंधन तकनीकों में गहरा ज्ञान।
50
- # 2. कृषि में कीट और रोग नियंत्रण के लिए प्रभावी रणनीतियाँ।
51
- # 3. मृदा स्वास्थ्य का सुधारने और पुनर्निर्माण के लिए विशेषज्ञता।
52
- # 4. सतत और प्रेसिजन खेती के अभ्यासों का ज्ञान।
53
- # 5. सिंचाई और जल प्रबंधन के लिए सर्वोत्तम अभ्यासों के लिए सुझाव।
54
- # 6. रणनीतिक फसल चक्रण और इंटरक्रॉपिंग विधियों पर मार्गदर्शन।
55
- # 7. नवीनतम कृषि प्रौद्योगिकियों और नवाचारों की जानकारी।
56
- # 8. विशेष फसलों, जलवायु, और क्षेत्रों के लिए विशेषज्ञ सलाह।
57
-
58
- # कृपया पेशेवर रूप से बराबरी बनाए रखें और सुनिश्चित करें कि आपके जवाब सही और मूल्यवान हैं। उपयोगकर्ताओं से आगे की स्पष्टीकरण के लिए पूछने के लिए प्रोत्साहित करें।
59
-
60
- # आपका प्रमुख लक्ष्य है यह है कि आप कृषि क्षेत्र में उपयुक्त ज्ञान प्रदान करें। आपके ज्ञान का धन्यवाद।
61
- # <</SYS>>
62
- # """
63
-
64
- # device = "cuda" if torch.cuda.is_available() else "cpu"
65
-
66
- # def create_prompt_with_chat_format(messages, bos="<s>", eos="</s>", add_bos=True, system_prompt="System: "):
67
- # formatted_text = ""
68
- # for message in messages:
69
- # if message["role"] == "system":
70
- # formatted_text += system_prompt + message["content"] + "\n"
71
- # elif message["role"] == "user":
72
- # if isinstance(message["content"], list):
73
- # formatted_text += "\n" + "\n".join(message["content"]) + "\n"
74
- # else:
75
- # formatted_text += "\n" + message["content"] + "\n"
76
- # elif message["role"] == "assistant":
77
- # if isinstance(message["content"], list):
78
- # formatted_text += "\n" + "\n".join(message["content"]).strip() + eos + "\n"
79
- # else:
80
- # formatted_text += "\n" + message["content"].strip() + eos + "\n"
81
- # else:
82
- # raise ValueError(
83
- # "Tulu chat template only supports 'system', 'user', and 'assistant' roles. Invalid role: {}.".format(
84
- # message["role"]
85
- # )
86
- # )
87
- # formatted_text += "\n"
88
- # formatted_text = bos + formatted_text if add_bos else formatted_text
89
- # return formatted_text
90
 
91
 
92
- # def inference(input_prompts, model, tokenizer, system_prompt="System: "):
93
- # output_texts = []
94
- # model = model.to(device) # Move the model to the same device as the input data
95
- # for input_prompt in input_prompts:
96
- # formatted_query = create_prompt_with_chat_format([{"role": "user", "content": input_prompt}], add_bos=False, system_prompt=system_prompt)
97
- # encodings = tokenizer(formatted_query, padding=True, return_tensors="pt")
98
- # encodings = {key: value.to(device) for key, value in encodings.items()} # Move input data to the same device as the model
 
 
 
 
 
 
 
 
 
 
 
99
 
100
- # with torch.no_grad():
101
- # outputs = model.generate(encodings["input_ids"], do_sample=False, max_length=250)
102
 
103
- # output_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
104
- # output_texts.append(output_text[len(input_prompt):])
105
- # return output_texts
 
 
106
 
 
 
107
 
 
 
108
 
 
109
 
110
- # examples = [
111
- # ["मुझे अपने करियर के बारे में सुझाव दो", "मैं कैसे अध्ययन कर सकता हूँ?"],
112
- # ["कृपया मुझे एक कहानी सुनाएं", "ताजमहल के बारे में कुछ बताएं"],
113
- # ["मेरा नाम क्या है?", "आपका पसंदीदा फिल्म कौन सी है?"],
114
- # ]
115
 
116
 
117
- # def get_llama_response(message: str, history: list, system_prompt=SYSTEM_PROMPT) -> str:
118
- # formatted_history = [{"role": "user", "content": hist} for hist in history]
119
- # formatted_message = {"role": "user", "content": message}
120
 
121
- # formatted_query = create_prompt_with_chat_format(formatted_history + [formatted_message], add_bos=False, system_prompt=system_prompt)
122
- # response = inference([formatted_query], model, tokenizer)
 
123
 
124
- # print("Chatbot:", response[0].strip())
125
- # return response[0].strip()
 
 
 
 
126
 
 
 
 
127
 
128
- # gr.ChatInterface(fn=get_llama_response).launch()
 
1
+ import torch
2
  from transformers import AutoTokenizer, AutoModelForCausalLM
3
+ import gradio as gr
4
 
5
+ device = "cuda" if torch.cuda.is_available() else "cpu"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
 
8
+ def create_prompt_with_chat_format(messages, bos="<s>", eos="</s>", add_bos=True):
9
+ formatted_text = ""
10
+ for message in messages:
11
+ if message["role"] == "system":
12
+ formatted_text += "<|system|>\n" + message["content"] + "\n"
13
+ elif message["role"] == "user":
14
+ formatted_text += "<|user|>\n" + message["content"] + "\n"
15
+ elif message["role"] == "assistant":
16
+ formatted_text += "<|assistant|>\n" + message["content"].strip() + eos + "\n"
17
+ else:
18
+ raise ValueError(
19
+ "Tulu chat template only supports 'system', 'user' and 'assistant' roles. Invalid role: {}.".format(
20
+ message["role"]
21
+ )
22
+ )
23
+ formatted_text += "<|assistant|>\n"
24
+ formatted_text = bos + formatted_text if add_bos else formatted_text
25
+ return formatted_text
26
 
 
 
27
 
28
+ def inference(input_prompts, model, tokenizer):
29
+ input_prompts = [
30
+ create_prompt_with_chat_format([{"role": "user", "content": input_prompt}], add_bos=False)
31
+ for input_prompt in input_prompts
32
+ ]
33
 
34
+ encodings = tokenizer(input_prompts, padding=True, return_tensors="pt")
35
+ encodings = encodings.to(device)
36
 
37
+ with torch.inference_mode():
38
+ outputs = model.generate(encodings.input_ids, do_sample=False, max_new_tokens=250)
39
 
40
+ output_texts = tokenizer.batch_decode(outputs.detach(), skip_special_tokens=True)
41
 
42
+ input_prompts = [
43
+ tokenizer.decode(tokenizer.encode(input_prompt), skip_special_tokens=True) for input_prompt in input_prompts
44
+ ]
45
+ output_texts = [output_text[len(input_prompt) :] for input_prompt, output_text in zip(input_prompts, output_texts)]
46
+ return output_texts
47
 
48
 
49
+ model_name = "ai4bharat/Airavata"
 
 
50
 
51
+ tokenizer = AutoTokenizer.from_pretrained(model_name, padding_side="left")
52
+ tokenizer.pad_token = tokenizer.eos_token
53
+ model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16).to(device)
54
 
55
+ examples= [
56
+ "मैं अपने समय प्रबंधन कौशल को कैसे सुधार सकता हूँ? मुझे पांच बिंदु बताएं।",
57
+ "मैं अपने समय प्रबंधन कौशल को कैसे सुधार सकता हूँ? मुझे पांच बिंदु बताएं और उनका वर्णन करें।",
58
+ ]
59
+ # outputs = inference(input_prompts, model, tokenizer)
60
+ # print(outputs)
61
 
62
+ gr.ChatInterface(fn=inference,
63
+ examples = examples,
64
+ title = "CAMAI ChatBot").launch()
65