hosseinhimself commited on
Commit
db77b63
·
verified ·
1 Parent(s): c62d678

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -60
app.py CHANGED
@@ -2,69 +2,75 @@ import gradio as gr
2
  from transformers import AutoTokenizer, AutoModelForCausalLM
3
  import torch
4
 
5
- # Set the device to CPU since Hugging Face Spaces does not support GPU
6
- device = torch.device("cpu") # Ensure it's using CPU only
7
 
8
- # Load model and tokenizer
9
- model_name = "hosseinhimself/ISANG-v1.0-8B" # Replace with your model name
10
  tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=False)
11
  model = AutoModelForCausalLM.from_pretrained(model_name).to(device)
12
 
13
- # Define the Alpaca-style prompt template
14
- alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
15
-
16
- ### Instruction:
17
- You are ISANG, a multilingual large language model made by ISANG AI. You only respond in Persian, Korean, or English. If a user uses one of these languages, reply in the same language.
18
-
19
- ### Input:
20
- {}
21
-
22
- ### Response:
23
- {}"""
24
-
25
- # Function to generate responses
26
- def generate_response(input_text, max_tokens=1024, temperature=0.7, history=[]):
27
- # Retain only the last two exchanges for context
28
- if len(history) > 2:
29
- history = history[-2:]
30
-
31
- # Format the prompt
32
- prompt = "\n".join(history + [f"User: {input_text}\nAI:"])
33
-
34
- # Tokenize the input
35
- inputs = tokenizer(prompt, return_tensors="pt").to(device)
36
-
37
- # Generate model output
38
- output = model.generate(
39
- inputs.input_ids,
40
- max_new_tokens=max_tokens,
41
- temperature=temperature
42
- )
43
-
44
- # Decode the model output
45
- response = tokenizer.decode(output[0], skip_special_tokens=True).strip()
46
-
47
- # Update the history
48
- history.append(f"User: {input_text}")
49
- history.append(f"AI: {response}")
50
-
51
- return response, history
52
-
53
- # Gradio interface
54
- iface = gr.Interface(
55
- fn=generate_response,
56
- inputs=[
57
- gr.Textbox(label="Your Message", placeholder="Type your message here..."),
58
- gr.Slider(minimum=1, maximum=2048, value=1024, step=1, label="Max Tokens"),
59
- gr.Slider(minimum=0.0, maximum=2.0, value=0.7, step=0.1, label="Temperature"),
60
- gr.State(value=[]) # To maintain conversation history
61
- ],
62
- outputs=[gr.Textbox(label="AI Response"), gr.State()],
63
- title="ISANG Chatbot",
64
- description="A chatbot powered by ISANG-v1.0-8B model. Chat with me!",
65
- theme="huggingface", # Purple theme
66
- live=False # Set to False since live updates aren't required
 
 
 
 
 
67
  )
68
 
69
- # Launch the interface
70
- iface.launch()
 
 
2
  from transformers import AutoTokenizer, AutoModelForCausalLM
3
  import torch
4
 
5
+ # Define device
6
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
7
 
8
+ # Load the model and tokenizer
9
+ model_name = "hosseinhimself/ISANG-v1.0-8B"
10
  tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=False)
11
  model = AutoModelForCausalLM.from_pretrained(model_name).to(device)
12
 
13
+ def chat_with_model(history, user_input):
14
+ """
15
+ Generate a response using the model, considering the last two interactions.
16
+
17
+ Parameters:
18
+ history (list of tuples): Conversation history as a list of (user, bot) pairs.
19
+ user_input (str): The latest user input.
20
+
21
+ Returns:
22
+ history (list of tuples): Updated conversation history.
23
+ """
24
+ # Use the last two interactions for context
25
+ context = ""
26
+ for user_message, bot_message in history[-2:]:
27
+ context += f"User: {user_message}\nBot: {bot_message}\n"
28
+
29
+ # Add the current user input
30
+ context += f"User: {user_input}\nBot:"
31
+
32
+ # Tokenize and generate a response
33
+ inputs = tokenizer(context, return_tensors="pt", truncation=True).to(device)
34
+ output = model.generate(inputs.input_ids, max_new_tokens=100)
35
+ bot_response = tokenizer.decode(output[0], skip_special_tokens=True)
36
+
37
+ # Extract only the bot's new response (to avoid repeating context)
38
+ bot_response = bot_response[len(context):].strip()
39
+
40
+ # Update the conversation history
41
+ history.append((user_input, bot_response))
42
+
43
+ return history
44
+
45
+ def gradio_format(history):
46
+ """
47
+ Format the history for Gradio ChatInterface.
48
+
49
+ Parameters:
50
+ history (list of tuples): Conversation history as a list of (user, bot) pairs.
51
+
52
+ Returns:
53
+ List of dictionaries compatible with Gradio ChatInterface.
54
+ """
55
+ return [[user, bot] for user, bot in history]
56
+
57
+ # Initialize empty history
58
+ history = []
59
+
60
+ def interface_function(user_input):
61
+ global history
62
+ history = chat_with_model(history, user_input)
63
+ return gradio_format(history)
64
+
65
+ # Create Gradio interface
66
+ chatbot = gr.ChatInterface(
67
+ fn=interface_function,
68
+ inputs=[gr.Textbox(lines=2, label="Your Input")],
69
+ outputs=[gr.Chatbot(label="Chat History")],
70
+ title="Persian Chatbot",
71
+ description="A chatbot that translates or responds to Persian prompts using ISANG-v1.0-8B model."
72
  )
73
 
74
+ # Launch the app
75
+ if __name__ == "__main__":
76
+ chatbot.launch()