Garvitj commited on
Commit
18a71f5
·
verified ·
1 Parent(s): 47f5bd3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +128 -63
app.py CHANGED
@@ -1,64 +1,129 @@
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
  import gradio as gr
2
+ import numpy as np
3
+ import librosa
4
+ import cv2
5
+ import moviepy.editor as mp
6
+ import speech_recognition as sr
7
+ from transformers import AutoModelForCausalLM, AutoTokenizer
8
+ import tensorflow as tf
9
+ from tensorflow.keras.preprocessing.text import tokenizer_from_json
10
+ from tensorflow.keras.models import load_model
11
+ from tensorflow.keras.preprocessing.sequence import pad_sequences
12
+ from tensorflow.keras.preprocessing.image import img_to_array, load_img
13
+ from collections import Counter
14
+
15
+ # Load necessary models and files
16
+ text_model = load_model('model_for_text_emotion_updated(1).keras') # Load your text emotion model
17
+ with open('tokenizer.json') as json_file:
18
+ tokenizer = tokenizer_from_json(json.load(json_file)) # Tokenizer for text emotion
19
+ audio_model = load_model('my_model.h5') # Load audio emotion model
20
+ image_model = load_model('model_emotion.h5') # Load image emotion model
21
+
22
+ # Load LLM model from Hugging Face
23
+ llama_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m") # Example: small OPT model
24
+ llama_tokenizer = AutoTokenizer.from_pretrained("facebook/opt-125m")
25
+
26
+ # Emotion mapping (from your model output)
27
+ emotion_mapping = {0: "anger", 1: "disgust", 2: "fear", 3: "joy", 4: "neutral", 5: "sadness", 6: "surprise"}
28
+
29
+ # Preprocess text for emotion prediction
30
+ def preprocess_text(text):
31
+ tokens = [word for word in text.lower().split() if word.isalnum()]
32
+ return ' '.join(tokens)
33
+
34
+ # Predict emotion from text
35
+ def predict_text_emotion(text):
36
+ preprocessed_text = preprocess_text(text)
37
+ seq = tokenizer.texts_to_sequences([preprocessed_text])
38
+ padded_seq = pad_sequences(seq, maxlen=35)
39
+ prediction = text_model.predict(padded_seq)
40
+ emotion_index = np.argmax(prediction)
41
+ return emotion_mapping[emotion_index]
42
+
43
+ # Extract audio features and predict emotion
44
+ def extract_audio_features(audio_data, sample_rate):
45
+ mfcc = np.mean(librosa.feature.mfcc(y=audio_data, sr=sample_rate).T, axis=0)
46
+ return np.expand_dims(mfcc, axis=0)
47
+
48
+ def predict_audio_emotion(audio_data, sample_rate):
49
+ features = extract_audio_features(audio_data, sample_rate)
50
+ prediction = audio_model.predict(features)
51
+ emotion_index = np.argmax(prediction)
52
+ return emotion_mapping[emotion_index]
53
+
54
+ # Process video and predict emotions from frames
55
+ def process_video(video_path):
56
+ cap = cv2.VideoCapture(video_path)
57
+ frame_rate = cap.get(cv2.CAP_PROP_FPS)
58
+ predictions = []
59
+
60
+ while cap.isOpened():
61
+ ret, frame = cap.read()
62
+ if not ret:
63
+ break
64
+ if int(cap.get(cv2.CAP_PROP_POS_FRAMES)) % int(frame_rate) == 0:
65
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
66
+ frame = cv2.resize(frame, (48, 48))
67
+ frame = img_to_array(frame) / 255.0
68
+ frame = np.expand_dims(frame, axis=0)
69
+ prediction = image_model.predict(frame)
70
+ predictions.append(np.argmax(prediction))
71
+
72
+ cap.release()
73
+ most_common_emotion = Counter(predictions).most_common(1)[0][0]
74
+ return emotion_mapping[most_common_emotion]
75
+
76
+ # Extract audio from video and process
77
+ def extract_audio_from_video(video_path):
78
+ video = mp.VideoFileClip(video_path)
79
+ audio = video.audio
80
+ audio_file = 'audio.wav'
81
+ audio.write_audiofile(audio_file)
82
+ return audio_file
83
+
84
+ def transcribe_audio(audio_file):
85
+ recognizer = sr.Recognizer()
86
+ with sr.AudioFile(audio_file) as source:
87
+ audio_record = recognizer.record(source)
88
+ return recognizer.recognize_google(audio_record)
89
+
90
+ # Integrating with LLM to adjust responses based on detected emotion
91
+ def interact_with_llm(emotion, user_input):
92
+ prompt = f"The user is feeling {emotion}. Respond to their question in an empathetic and appropriate manner: {user_input}"
93
+
94
+ inputs = llama_tokenizer(prompt, return_tensors="pt")
95
+ outputs = llama_model.generate(**inputs, max_length=200)
96
+ response = llama_tokenizer.decode(outputs[0], skip_special_tokens=True)
97
+
98
+ return response
99
+
100
+ # Main function to process video and predict emotions
101
+ def transcribe_and_predict_video(video_path):
102
+ # Extract audio from video and predict text-based emotion
103
+ audio_file = extract_audio_from_video(video_path)
104
+ text = transcribe_audio(audio_file)
105
+ text_emotion = predict_text_emotion(text)
106
+
107
+ # Predict emotion from video frames (image-based)
108
+ image_emotion = process_video(video_path)
109
+
110
+ # Predict emotion from audio (sound-based)
111
+ sample_rate, audio_data = librosa.load(audio_file, sr=None)
112
+ audio_emotion = predict_audio_emotion(audio_data, sample_rate)
113
+
114
+ # Combine the detected emotions for final output (you could average them or choose the most common)
115
+ final_emotion = image_emotion # Or decide based on some logic (e.g., majority vote)
116
+
117
+ # Get response from LLM
118
+ llm_response = interact_with_llm(final_emotion, text)
119
+
120
+ return f"Emotion Detected: {final_emotion}\nLLM Response: {llm_response}"
121
+
122
+ # Create Gradio interface
123
+ iface = gr.Interface(fn=transcribe_and_predict_video,
124
+ inputs=gr.Video(),
125
+ outputs="text",
126
+ title="Emotion-Responsive LLM for Video",
127
+ description="Upload a video to get emotion predictions and LLM responses based on detected emotions.")
128
+
129
+ iface.launch()