TejAndrewsACC commited on
Commit
534f131
·
verified ·
1 Parent(s): a7e257a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +118 -63
app.py CHANGED
@@ -1,64 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
-
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hugging Face Space Adaptation for Autistic Assistant 2024 Ultra
2
+
3
+ # Install necessary libraries (if running locally)
4
+ # !pip install transformers torch textblob numpy gradio
5
+
6
+ # Import necessary libraries
7
+ import torch
8
+ import random
9
+ import torch.nn as nn
10
+ from transformers import GPT2LMHeadModel, GPT2Tokenizer
11
+ from textblob import TextBlob
12
  import gradio as gr
13
+ import pickle
14
+ import numpy as np
15
+
16
+ # ---- Constants and Setup ----
17
+ model_name = 'gpt2'
18
+ tokenizer = GPT2Tokenizer.from_pretrained(model_name)
19
+ model = GPT2LMHeadModel.from_pretrained(model_name)
20
+ model.eval()
21
+
22
+ if tokenizer.pad_token is None:
23
+ tokenizer.pad_token = tokenizer.eos_token
24
+
25
+ tokenizer.clean_up_tokenization_spaces = True
26
+
27
+ # Ensure model and tensors are moved to the GPU if available
28
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
29
+ model.to(device)
30
+
31
+ # ---- Memory Management ----
32
+ session_memory = []
33
+
34
+ def save_memory(memory, filename='chat_memory.pkl'):
35
+ with open(filename, 'wb') as f:
36
+ pickle.dump(memory, f)
37
+
38
+ def load_memory(filename='chat_memory.pkl'):
39
+ try:
40
+ with open(filename, 'rb') as f:
41
+ return pickle.load(f)
42
+ except FileNotFoundError:
43
+ return []
44
+
45
+ session_memory = load_memory()
46
+
47
+ # ---- Sentiment Analysis ----
48
+ def analyze_sentiment(text):
49
+ blob = TextBlob(text)
50
+ return blob.sentiment.polarity # Range from -1 (negative) to 1 (positive)
51
+
52
+ def adjust_for_emotion(response, sentiment):
53
+ if sentiment > 0.2:
54
+ return f"That's wonderful! I'm glad you're feeling good: {response}"
55
+ elif sentiment < -0.2:
56
+ return f"I'm truly sorry to hear that: {response}. How can I make it better?"
57
+ return response
58
+
59
+ # ---- Response Generation ----
60
+ def generate_response(prompt, max_length=1024):
61
+ inputs = tokenizer(prompt, return_tensors='pt', padding=True, truncation=True, max_length=max_length)
62
+ input_ids = inputs['input_ids'].to(device)
63
+ attention_mask = inputs['attention_mask'].to(device)
64
+ pad_token_id = tokenizer.pad_token_id
65
+
66
+ with torch.no_grad():
67
+ output = model.generate(
68
+ input_ids,
69
+ attention_mask=attention_mask,
70
+ max_length=max_length,
71
+ num_return_sequences=1,
72
+ no_repeat_ngram_size=2,
73
+ do_sample=True,
74
+ temperature=0.9,
75
+ top_k=50,
76
+ top_p=0.95,
77
+ early_stopping=False,
78
+ pad_token_id=pad_token_id
79
+ )
80
+
81
+ response = tokenizer.decode(output[0], skip_special_tokens=True)
82
+ return response.strip()
83
+
84
+ # ---- Interactive Chat Function ----
85
+ def advanced_agi_chat(user_input):
86
+ # Add user input to session memory
87
+ session_memory.append({"input": user_input})
88
+ save_memory(session_memory)
89
+
90
+ # Sentiment analysis
91
+ user_sentiment = analyze_sentiment(user_input)
92
+
93
+ # Generate the response
94
+ prompt = f"User: {user_input}\nAutistic-Assistant:"
95
+ response = generate_response(prompt)
96
+
97
+ # Adjust response for emotional alignment
98
+ adjusted_response = adjust_for_emotion(response, user_sentiment)
99
+
100
+ return adjusted_response
101
+
102
+ # ---- Gradio Interface ----
103
+ def chat_interface(user_input):
104
+ response = advanced_agi_chat(user_input)
105
+ return response
106
+
107
+ with gr.Blocks() as app:
108
+ gr.Markdown("# Autistic Assistant 2024 Ultra")
109
+ with gr.Row():
110
+ with gr.Column():
111
+ user_input = gr.Textbox(label="Your Message", placeholder="Type something here...")
112
+ submit_button = gr.Button("Send")
113
+ with gr.Column():
114
+ chatbot = gr.Textbox(label="Assistant Response", interactive=False)
115
+
116
+ submit_button.click(chat_interface, inputs=user_input, outputs=chatbot)
117
+
118
+ # Launch the Gradio app
119
+ app.launch()