sheikhDipta003 commited on
Commit
9cdcfee
·
1 Parent(s): bf43859

add all files

Browse files
.gitignore ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### Database ###
2
+ *.sqlite3
3
+
4
+ ### bin ###
5
+ *.bin
6
+
7
+ ### Python ###
8
+ # Byte-compiled / optimized / DLL files
9
+ __pycache__/
10
+ *.py[cod]
11
+ *$py.class
12
+
13
+ # C extensions
14
+ *.so
15
+
16
+ # Distribution / packaging
17
+ .Python
18
+ build/
19
+ develop-eggs/
20
+ dist/
21
+ downloads/
22
+ eggs/
23
+ .eggs/
24
+ lib/
25
+ lib64/
26
+ parts/
27
+ sdist/
28
+ var/
29
+ wheels/
30
+ share/python-wheels/
31
+ *.egg-info/
32
+ .installed.cfg
33
+ *.egg
34
+ MANIFEST
35
+
36
+ # PyInstaller
37
+ # Usually these files are written by a python script from a template
38
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
39
+ *.manifest
40
+ *.spec
41
+
42
+ # Installer logs
43
+ pip-log.txt
44
+ pip-delete-this-directory.txt
45
+
46
+ # Unit test / coverage reports
47
+ htmlcov/
48
+ .tox/
49
+ .nox/
50
+ .coverage
51
+ .coverage.*
52
+ .cache
53
+ nosetests.xml
54
+ coverage.xml
55
+ *.cover
56
+ .hypothesis/
57
+ .pytest_cache/
58
+ cover/
59
+
60
+ # Translations
61
+ *.mo
62
+ *.pot
63
+
64
+ # Django stuff:
65
+ *.log
66
+ local_settings.py
67
+ db.sqlite3
68
+ db.sqlite3-journal
69
+
70
+ # Flask stuff:
71
+ instance/
72
+ .webassets-cache
73
+
74
+ # Scrapy stuff:
75
+ .scrapy
76
+
77
+ # Sphinx documentation
78
+ docs/_build/
79
+
80
+ # PyBuilder
81
+ .pybuilder/
82
+ target/
83
+
84
+ # Jupyter Notebook
85
+ .ipynb_checkpoints
86
+
87
+ # IPython
88
+ profile_default/
89
+ ipython_config.py
90
+
91
+ # pyenv
92
+ # For a library or package, you might want to ignore these files since the code is
93
+ # intended to run in multiple environments; otherwise, check them in:
94
+ # .python-version
95
+
96
+ # pipenv
97
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
98
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
99
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
100
+ # install all needed dependencies.
101
+ #Pipfile.lock
102
+
103
+ # pdm
104
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
105
+ #pdm.lock
106
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
107
+ # in version control.
108
+ # https://pdm.fming.dev/#use-with-ide
109
+ .pdm.toml
110
+
111
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
112
+ __pypackages__/
113
+
114
+ # Environments
115
+ *.env
116
+ .venv
117
+ env/
118
+ venv/
119
+ ENV/
120
+ env.bak/
121
+ venv.bak/
122
+
123
+ # PyCharm
124
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
125
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
126
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
127
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
128
+ .idea/
129
+
130
+ ### venv ###
131
+ pyvenv.cfg
132
+ pip-selfcheck.json
133
+
134
+ ### VisualStudioCode ###
135
+ .vscode/*
136
+ !.vscode/settings.json
137
+ !.vscode/tasks.json
138
+ !.vscode/launch.json
139
+ !.vscode/extensions.json
140
+ !.vscode/*.code-snippets
141
+
142
+ # Local History for Visual Studio Code
143
+ .history/
144
+
145
+ # Built Visual Studio Code Extensions
146
+ *.vsix
147
+
148
+ ### VisualStudioCode Patch ###
149
+ # Ignore all local history of files
150
+ .history
151
+ .ionide
152
+
.gradio/certificate.pem ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -----BEGIN CERTIFICATE-----
2
+ MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
3
+ TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
4
+ cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
5
+ WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
6
+ ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
7
+ MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
8
+ h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
9
+ 0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
10
+ A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
11
+ T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
12
+ B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
13
+ B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
14
+ KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
15
+ OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
16
+ jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
17
+ qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
18
+ rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
19
+ HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
20
+ hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
21
+ ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
22
+ 3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
23
+ NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
24
+ ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
25
+ TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
26
+ jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
27
+ oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
28
+ 4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
29
+ mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
30
+ emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
31
+ -----END CERTIFICATE-----
.gradio/flagged/Upload image for emotion analysis/4e8dadac1774d97fcc36/surprised.jpeg ADDED
.gradio/flagged/dataset1.csv ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Upload image for emotion analysis,Vision Emotion Analysis Results,timestamp
2
+ .gradio\flagged\Upload image for emotion analysis\4e8dadac1774d97fcc36\surprised.jpeg,"Predicted Emotion: SURPRISE
3
+
4
+ Probabilities:
5
+ angry: 3.97%
6
+ disgust: 0.45%
7
+ fear: 10.07%
8
+ happy: 1.09%
9
+ sad: 0.99%
10
+ surprise: 82.87%
11
+ neutral: 0.55%
12
+ ",2025-01-15 02:28:39.690721
app.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ from PIL import Image
4
+ import sys
5
+ import os
6
+ from text.test import predict_sentiment, SentimentRequest
7
+ from speech.test import classify_emotion as classify_speech_emotion
8
+ from vision.test import classify_emotion as classify_vision_emotion
9
+ import librosa
10
+ import torch
11
+ import asyncio
12
+
13
+ os.environ["HF_HUB_DISABLE_SYMLINKS_WARNING"] = "1"
14
+
15
+ def process_text(text, api_key):
16
+ try:
17
+ if not api_key.strip():
18
+ return "Please provide an OpenAI API key"
19
+
20
+ # Set the API key as environment variable
21
+ os.environ["OPENAI_API_KEY"] = api_key.strip()
22
+
23
+ # Create request object
24
+ request = SentimentRequest(text=text)
25
+
26
+ # Get prediction
27
+ result = asyncio.run(predict_sentiment(request))
28
+
29
+ return f"Predicted Sentiment: {result['sentiment'].upper()}"
30
+ except Exception as e:
31
+ return f"Error processing text: {str(e)}"
32
+
33
+ def process_speech(audio_path):
34
+ try:
35
+ # Load audio file
36
+ waveform, sr = librosa.load(audio_path, sr=None)
37
+ waveform = waveform.astype(np.float32)
38
+
39
+ # Get prediction
40
+ predicted_emotion, emotion_probs = classify_speech_emotion(waveform, sr)
41
+
42
+ # Format the output
43
+ output_text = f"Predicted Emotion: {predicted_emotion.upper()}\n\nProbabilities:\n"
44
+ for emotion, prob in emotion_probs.items():
45
+ output_text += f"{emotion}: {prob:.2%}\n"
46
+
47
+ return output_text
48
+ except Exception as e:
49
+ return f"Error processing audio: {str(e)}"
50
+
51
+ def process_image(image):
52
+ try:
53
+ if image is None:
54
+ return "Please provide an image"
55
+
56
+ # Convert to PIL Image if needed
57
+ if not isinstance(image, Image.Image):
58
+ image = Image.fromarray(image)
59
+
60
+ # Get prediction
61
+ prob_dict, most_likely_emotion = classify_vision_emotion(image)
62
+
63
+ # Format the output
64
+ output_text = f"Predicted Emotion: {most_likely_emotion.upper()}\n\nProbabilities:\n"
65
+ for emotion, prob in prob_dict.items():
66
+ output_text += f"{emotion}: {prob:.2%}\n"
67
+
68
+ return output_text
69
+ except Exception as e:
70
+ return f"Error processing image: {str(e)}"
71
+
72
+ def create_interface():
73
+ # Text analysis
74
+ with gr.Row():
75
+ api_key_input = gr.Textbox(
76
+ label="OpenAI API Key",
77
+ placeholder="Enter your OpenAI API key...",
78
+ type="password"
79
+ )
80
+ text_input = gr.Textbox(
81
+ label="Enter text for sentiment analysis",
82
+ placeholder="Type your text here...",
83
+ lines=3
84
+ )
85
+ text_output = gr.Textbox(label="Text Sentiment Analysis Results")
86
+ text_interface = gr.Interface(
87
+ fn=process_text,
88
+ inputs=[text_input, api_key_input],
89
+ outputs=text_output,
90
+ title="Text Sentiment Analysis",
91
+ description="Analyze the sentiment of text input as positive or negative.",
92
+ theme=gr.themes.Soft(),
93
+ css="footer {display: none !important;}"
94
+ )
95
+
96
+ # Speech analysis
97
+ speech_input = gr.Audio(
98
+ label="Upload audio for emotion analysis",
99
+ type="filepath"
100
+ )
101
+ speech_output = gr.Textbox(label="Speech Emotion Analysis Results")
102
+ speech_interface = gr.Interface(
103
+ fn=process_speech,
104
+ inputs=speech_input,
105
+ outputs=speech_output,
106
+ title="Speech Emotion Analysis",
107
+ description="Analyze the emotion in speech audio.",
108
+ theme=gr.themes.Soft(),
109
+ css="footer {display: none !important;}"
110
+ )
111
+
112
+ # Vision analysis
113
+ vision_input = gr.Image(
114
+ label="Upload image for emotion analysis",
115
+ type="pil"
116
+ )
117
+ vision_output = gr.Textbox(label="Vision Emotion Analysis Results")
118
+ vision_interface = gr.Interface(
119
+ fn=process_image,
120
+ inputs=vision_input,
121
+ outputs=vision_output,
122
+ title="Vision Emotion Analysis",
123
+ description="Analyze the emotion in facial expressions.",
124
+ theme=gr.themes.Soft(),
125
+ css="footer {display: none !important;}"
126
+ )
127
+
128
+ demo = gr.TabbedInterface(
129
+ [text_interface, speech_interface, vision_interface],
130
+ ["Text Analysis", "Speech Analysis", "Vision Analysis"],
131
+ title="Multimodal Sentiment Analysis",
132
+ theme=gr.themes.Soft(),
133
+ css="""
134
+ .gradio-container {
135
+ max-width: 900px !important;
136
+ margin: auto;
137
+ padding: 20px;
138
+ border-radius: 10px;
139
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
140
+ }
141
+ .tabs {
142
+ margin-bottom: 20px;
143
+ border-bottom: 2px solid #eee;
144
+ }
145
+ .tab-button {
146
+ padding: 10px 20px;
147
+ margin-right: 10px;
148
+ border-radius: 5px 5px 0 0;
149
+ background-color: #f5f5f5;
150
+ }
151
+ .tab-button.selected {
152
+ background-color: #2196F3;
153
+ color: white;
154
+ }
155
+ footer {display: none !important;}
156
+ """
157
+ )
158
+
159
+ return demo
160
+
161
+ if __name__ == "__main__":
162
+ try:
163
+ demo = create_interface()
164
+ demo.launch(share=True)
165
+ except Exception as e:
166
+ print(f"Error launching application: {str(e)}")
167
+ sys.exit(1)
requirements.txt ADDED
Binary file (2.93 kB). View file
 
speech/.gitignore ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ best_ser_whisper.pkl
2
+
3
+ ### Database ###
4
+ *.sqlite3
5
+
6
+ ### bin ###
7
+ *.bin
8
+
9
+ ### Python ###
10
+ # Byte-compiled / optimized / DLL files
11
+ __pycache__/
12
+ *.py[cod]
13
+ *$py.class
14
+
15
+ # C extensions
16
+ *.so
17
+
18
+ # Distribution / packaging
19
+ .Python
20
+ build/
21
+ develop-eggs/
22
+ dist/
23
+ downloads/
24
+ eggs/
25
+ .eggs/
26
+ lib/
27
+ lib64/
28
+ parts/
29
+ sdist/
30
+ var/
31
+ wheels/
32
+ share/python-wheels/
33
+ *.egg-info/
34
+ .installed.cfg
35
+ *.egg
36
+ MANIFEST
37
+
38
+ # PyInstaller
39
+ # Usually these files are written by a python script from a template
40
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
41
+ *.manifest
42
+ *.spec
43
+
44
+ # Installer logs
45
+ pip-log.txt
46
+ pip-delete-this-directory.txt
47
+
48
+ # Unit test / coverage reports
49
+ htmlcov/
50
+ .tox/
51
+ .nox/
52
+ .coverage
53
+ .coverage.*
54
+ .cache
55
+ nosetests.xml
56
+ coverage.xml
57
+ *.cover
58
+ .hypothesis/
59
+ .pytest_cache/
60
+ cover/
61
+
62
+ # Translations
63
+ *.mo
64
+ *.pot
65
+
66
+ # Django stuff:
67
+ *.log
68
+ local_settings.py
69
+ db.sqlite3
70
+ db.sqlite3-journal
71
+
72
+ # Flask stuff:
73
+ instance/
74
+ .webassets-cache
75
+
76
+ # Scrapy stuff:
77
+ .scrapy
78
+
79
+ # Sphinx documentation
80
+ docs/_build/
81
+
82
+ # PyBuilder
83
+ .pybuilder/
84
+ target/
85
+
86
+ # Jupyter Notebook
87
+ .ipynb_checkpoints
88
+
89
+ # IPython
90
+ profile_default/
91
+ ipython_config.py
92
+
93
+ # pyenv
94
+ # For a library or package, you might want to ignore these files since the code is
95
+ # intended to run in multiple environments; otherwise, check them in:
96
+ # .python-version
97
+
98
+ # pipenv
99
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
100
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
101
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
102
+ # install all needed dependencies.
103
+ #Pipfile.lock
104
+
105
+ # pdm
106
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
107
+ #pdm.lock
108
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
109
+ # in version control.
110
+ # https://pdm.fming.dev/#use-with-ide
111
+ .pdm.toml
112
+
113
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
114
+ __pypackages__/
115
+
116
+ # Environments
117
+ *.env
118
+ .venv
119
+ env/
120
+ venv/
121
+ ENV/
122
+ env.bak/
123
+ venv.bak/
124
+
125
+ # PyCharm
126
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
127
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
128
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
129
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
130
+ .idea/
131
+
132
+ ### venv ###
133
+ pyvenv.cfg
134
+ pip-selfcheck.json
135
+
136
+ ### VisualStudioCode ###
137
+ .vscode/*
138
+ !.vscode/settings.json
139
+ !.vscode/tasks.json
140
+ !.vscode/launch.json
141
+ !.vscode/extensions.json
142
+ !.vscode/*.code-snippets
143
+
144
+ # Local History for Visual Studio Code
145
+ .history/
146
+
147
+ # Built Visual Studio Code Extensions
148
+ *.vsix
149
+
150
+ ### VisualStudioCode Patch ###
151
+ # Ignore all local history of files
152
+ .history
153
+ .ionide
154
+
speech/README.md ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### API Documentation: Speech Emotion Recognition (SER)
2
+
3
+ This API allows you to upload an audio file and get the predicted emotion along with the probabilities for all emotion classes using a fine-tuned Speech Emotion Recognition (SER) model (openai/whisper-small). I saved some audio files for testing [here](./dataset_my/pilot_test). To create the api on localhost, run [test.py](./test.py) using ```python test.py``` command.
4
+
5
+ ---
6
+
7
+ ### Base URL
8
+ ```
9
+ http://127.0.0.1:8000
10
+ ```
11
+
12
+ ---
13
+
14
+ ### Endpoints
15
+
16
+ #### 1. **Classify Emotion**
17
+ This endpoint accepts an audio file and returns the predicted emotion and probabilities for all emotion classes.
18
+
19
+ - **Endpoint**: `POST /classify-emotion/`
20
+ - **Request Body**:
21
+ - **Key**: `audio_file`
22
+ - **Value**: The audio file to analyze (e.g., `.wav`).
23
+ - **Response**:
24
+ - **Success (200 OK)**:
25
+ ```json
26
+ {
27
+ "predicted_emotion": "happy",
28
+ "emotion_probabilities": {
29
+ "neutral": 0.1,
30
+ "happy": 0.8,
31
+ "sad": 0.05,
32
+ "angry": 0.03,
33
+ "fearful": 0.01,
34
+ "disgusted": 0.005,
35
+ "surprised": 0.005
36
+ }
37
+ }
38
+ ```
39
+ - **Error (500 Internal Server Error)**:
40
+ ```json
41
+ {
42
+ "detail": "Error message describing the issue."
43
+ }
44
+ ```
45
+
46
+ ---
47
+
48
+ ### Special Instructions for Use with Postman
49
+
50
+ #### Step 1: Set Up the Request
51
+ 1. Open Postman.
52
+ 2. Set the request type to `POST`.
53
+ 3. Enter the URL:
54
+ ```
55
+ http://127.0.0.1:8000/classify-emotion/
56
+ ```
57
+
58
+ #### Step 2: Configure the Body
59
+ 1. Go to the **Body** tab.
60
+ 2. Select **form-data**.
61
+
62
+ #### Step 3: Add the File
63
+ 1. In the **Key** field, enter `audio_file` (this must match the parameter name in the API).
64
+ 2. Hover over the **Value** field, and click the dropdown that says **Text**. Change it to **File**.
65
+ 3. Click **Choose File** and select your audio file (e.g., `test_audio.wav`).
66
+
67
+ #### Step 4: Send the Request
68
+ 1. Click the **Send** button to submit the request.
69
+
70
+ ---
71
+
72
+ ### Example Postman Configuration
73
+
74
+ #### **Headers**:
75
+ - Postman automatically sets the `Content-Type` to `multipart/form-data` when you use the **form-data** option. You don’t need to manually add this header.
76
+
77
+ #### **Body**:
78
+ | Key | Value
79
+ |-------------|--------------------
80
+ | `audio_file`| `test_audio.wav`
81
+
82
+ ---
83
+
84
+ ### Example Workflow in Postman
85
+
86
+ 1. **Set Up the Request**:
87
+ - Method: `POST`
88
+ - URL: `http://127.0.0.1:8000/classify-emotion/`
89
+ - Body: `form-data`
90
+ - Key: `audio_file`
91
+ - Value: `test_audio.wav` (select as **File**)
92
+
93
+ 2. **Send the Request**:
94
+ - Click **Send**.
95
+
96
+ 3. **Check the Response**:
97
+ - If successful, you’ll see the predicted emotion and probabilities:
98
+ ```json
99
+ {
100
+ "predicted_emotion": "happy",
101
+ "emotion_probabilities": {
102
+ "neutral": 0.1,
103
+ "happy": 0.8,
104
+ "sad": 0.05,
105
+ "angry": 0.03,
106
+ "fearful": 0.01,
107
+ "disgusted": 0.005,
108
+ "surprised": 0.005
109
+ }
110
+ }
111
+ ```
112
+ - If there’s an error, check the error message and debug accordingly.
113
+
114
+ ---
115
+
speech/dataset_my/pilot_test/03-01-04-02-02-01-02.wav ADDED
Binary file (417 kB). View file
 
speech/dataset_my/pilot_test/03-02-02-01-01-02-10.wav ADDED
Binary file (523 kB). View file
 
speech/dataset_my/pilot_test/03-02-05-02-02-01-04.wav ADDED
Binary file (429 kB). View file
 
speech/dataset_my/pilot_test/03-02-06-01-02-02-09.wav ADDED
Binary file (407 kB). View file
 
speech/gradio_demo.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import librosa
4
+ import torch
5
+ from .train import label_mapping, device, MAX_DURATION, processor
6
+
7
+ label_to_name = {v: k for k, v in label_mapping.items()}
8
+ BEST_MODEL = torch.load("best_ser_whisper.pkl", map_location=torch.device('cpu'))
9
+ # BEST_MODEL = best_model
10
+
11
+ def classify_emotion(audio_input):
12
+ if audio_input is None:
13
+ return "No audio input detected. Please check your microphone or upload an audio file.", {}
14
+
15
+ # Handle both microphone and uploaded file inputs
16
+ if isinstance(audio_input, tuple): # Microphone input
17
+ sr, waveform = audio_input
18
+ waveform = waveform.astype(np.float32)
19
+ elif isinstance(audio_input, str): # File upload input
20
+ try:
21
+ waveform, sr = librosa.load(audio_input, sr=None)
22
+ waveform = waveform.astype(np.float32)
23
+ except Exception as e:
24
+ return f"Error loading audio file: {e}", {}
25
+ else:
26
+ return "Invalid audio input.", {}
27
+
28
+ # Resample if necessary
29
+ if sr != 16000:
30
+ waveform = librosa.resample(waveform, orig_sr=sr, target_sr=16000)
31
+ sr = 16000
32
+
33
+ # Trim or pad audio to max_duration
34
+ max_samples = int(MAX_DURATION * sr)
35
+ if len(waveform) > max_samples:
36
+ waveform = waveform[:max_samples]
37
+ elif len(waveform) < max_samples:
38
+ waveform = np.pad(waveform, (0, max_samples - len(waveform)), "constant")
39
+
40
+ processed_inputs = processor(
41
+ waveform, sampling_rate=sr, return_tensors="pt", return_attention_mask=True
42
+ )
43
+ inputs = processed_inputs.input_features.to(device)
44
+
45
+ with torch.no_grad():
46
+ logits = BEST_MODEL(inputs).logits
47
+ probabilities = torch.softmax(logits, dim=1).squeeze().cpu().numpy()
48
+
49
+ emotion_probs = {}
50
+ for i, prob in enumerate(probabilities):
51
+ emotion_probs[label_to_name[i + 1]] = prob
52
+
53
+ # Get the most likely class
54
+ predicted_label_index = torch.argmax(logits, dim=1).item()
55
+ predicted_label_name = label_to_name[predicted_label_index + 1]
56
+
57
+ return predicted_label_name, emotion_probs
58
+
59
+ iface = gr.Interface(
60
+ fn=classify_emotion,
61
+ inputs=gr.Audio(sources=["microphone", "upload"], type="numpy"),
62
+ outputs=[
63
+ gr.Label(label="Predicted Emotion"),
64
+ gr.Label(num_top_classes=len(label_mapping), label="Probabilities"),
65
+ ],
66
+ live=True,
67
+ )
68
+
69
+ iface.launch(share=True)
speech/requirements.txt ADDED
Binary file (3.34 kB). View file
 
speech/test.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile, HTTPException
2
+ import numpy as np
3
+ import librosa
4
+ import torch
5
+ from .train import label_mapping, device, MAX_DURATION, processor
6
+ import io
7
+ import uvicorn
8
+ import warnings
9
+ warnings.filterwarnings("ignore", category=FutureWarning)
10
+
11
+ app = FastAPI()
12
+
13
+ # Load the best model
14
+ BEST_MODEL = torch.load("F:\\sociofi_my\\projects\\sentiment_analysis\\speech\\best_ser_whisper.pkl", map_location=torch.device('cpu'), weights_only=False)
15
+ BEST_MODEL.eval()
16
+
17
+ # Reverse label mapping
18
+ label_to_name = {v: k for k, v in label_mapping.items()}
19
+
20
+ # Function to classify emotion
21
+ def classify_emotion(audio_input: np.ndarray, sr: int):
22
+ # Resample if necessary
23
+ if sr != 16000:
24
+ audio_input = librosa.resample(audio_input, orig_sr=sr, target_sr=16000)
25
+ sr = 16000
26
+
27
+ # Trim or pad audio to max_duration
28
+ max_samples = int(MAX_DURATION * sr)
29
+ if len(audio_input) > max_samples:
30
+ audio_input = audio_input[:max_samples]
31
+ elif len(audio_input) < max_samples:
32
+ audio_input = np.pad(audio_input, (0, max_samples - len(audio_input)), "constant")
33
+
34
+ # Preprocess the audio
35
+ processed_inputs = processor(
36
+ audio_input, sampling_rate=sr, return_tensors="pt", return_attention_mask=True
37
+ )
38
+ inputs = processed_inputs.input_features.to(device)
39
+
40
+ # Perform inference
41
+ with torch.no_grad():
42
+ logits = BEST_MODEL(inputs).logits
43
+ probabilities = torch.softmax(logits, dim=1).squeeze().cpu().numpy()
44
+
45
+ # Map probabilities to emotion labels
46
+ emotion_probs = {}
47
+ for i, prob in enumerate(probabilities):
48
+ emotion_probs[label_to_name[i + 1]] = float(prob) # Convert to float for JSON serialization
49
+
50
+ # Get the most likely class
51
+ predicted_label_index = torch.argmax(logits, dim=1).item()
52
+ predicted_label_name = label_to_name[predicted_label_index + 1]
53
+
54
+ return predicted_label_name, emotion_probs
55
+
56
+ # Endpoint to classify emotion
57
+ @app.post("/classify-emotion/")
58
+ async def classify_emotion_endpoint(audio_file: UploadFile = File(...)):
59
+ try:
60
+ # Read the uploaded audio file
61
+ audio_bytes = await audio_file.read()
62
+ audio_file = io.BytesIO(audio_bytes)
63
+
64
+ # Load the audio file using librosa
65
+ waveform, sr = librosa.load(audio_file, sr=None)
66
+ waveform = waveform.astype(np.float32)
67
+
68
+ # Classify the emotion
69
+ predicted_emotion, emotion_probs = classify_emotion(waveform, sr)
70
+
71
+ return {
72
+ "predicted_emotion": predicted_emotion,
73
+ "emotion_probabilities": emotion_probs
74
+ }
75
+ except Exception as e:
76
+ raise HTTPException(status_code=500, detail=f"Error processing audio file: {str(e)}")
77
+
78
+ # Run the FastAPI app
79
+ if __name__ == '__main__':
80
+ uvicorn.run(app, host="0.0.0.0", port=8000)
81
+
speech/train.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import os
4
+ from transformers import WhisperProcessor, WhisperForAudioClassification
5
+ import torch
6
+ import librosa
7
+ import numpy as np
8
+ from torch.utils.data import Dataset, DataLoader
9
+ import os
10
+ from torch.optim import AdamW
11
+ from torch.optim.lr_scheduler import ReduceLROnPlateau
12
+ from tqdm import tqdm
13
+ from sklearn.metrics import accuracy_score, f1_score
14
+ import pickle
15
+ import logging
16
+ logging.getLogger("transformers.modeling_utils").setLevel(logging.ERROR)
17
+
18
+ label_mapping = {
19
+ 'neutral': 1,
20
+ 'calm': 2,
21
+ 'happy': 3,
22
+ 'sad': 4,
23
+ 'angry': 5,
24
+ 'fearful': 6,
25
+ 'disgust': 7,
26
+ 'surprised': 8
27
+ }
28
+
29
+ MAX_DURATION = 10
30
+
31
+
32
+ model_id = "openai/whisper-small"
33
+ processor = WhisperProcessor.from_pretrained(model_id)
34
+ model = WhisperForAudioClassification.from_pretrained(model_id,
35
+ num_labels=8, # Number of emotion classes (01 = neutral, 02 = calm, 03 = happy, 04 = sad, 05 = angry, 06 = fearful, 07 = disgust, 08 = surprised)
36
+ ignore_mismatched_sizes=True
37
+ )
38
+
39
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
40
+ model.to(device)
41
+
42
+ class SpeechEmotionDataset(Dataset):
43
+ def __init__(self, data_dirs, processor, label_mapping, max_duration=MAX_DURATION):
44
+ self.data_dirs = data_dirs
45
+ self.processor = processor
46
+ self.label_mapping = label_mapping
47
+ self.max_duration = max_duration # in seconds
48
+ self.file_paths = []
49
+ self.labels = []
50
+
51
+ for data_dir in self.data_dirs:
52
+ for filename in os.listdir(data_dir):
53
+ if filename.endswith(".wav"):
54
+ self.file_paths.append(os.path.join(data_dir, filename))
55
+ parts = filename.split('-') # split the filename into parts using '-' as the delimeter
56
+ emotion_code = int(parts[2]) # extract the emotion code from the third position
57
+ self.labels.append(self.map_ravdess_emotion_to_label(emotion_code))
58
+
59
+
60
+ def __len__(self):
61
+ return len(self.file_paths)
62
+
63
+ def __getitem__(self, idx):
64
+ file_path = self.file_paths[idx]
65
+ label = self.labels[idx]
66
+ try:
67
+ audio, sr = librosa.load(file_path, sr=16000) # Whisper expects 16kHz audio
68
+ except Exception as e:
69
+ print(f"Error loading {file_path}: {e}")
70
+ return None # Skip this item on error
71
+
72
+
73
+ # Trim or pad audio to max_duration
74
+ max_samples = int(self.max_duration * sr)
75
+ if len(audio) > max_samples:
76
+ audio = audio[:max_samples]
77
+ elif len(audio) < max_samples:
78
+ audio = np.pad(audio, (0, max_samples - len(audio)), 'constant')
79
+
80
+ processed_inputs = self.processor(
81
+ audio, sampling_rate=sr, return_tensors="pt", return_attention_mask=True
82
+ )
83
+
84
+ inputs = processed_inputs.input_features
85
+ attention_mask = processed_inputs.attention_mask
86
+
87
+ return inputs.squeeze(0).to(device), \
88
+ attention_mask.squeeze(0).to(device), \
89
+ torch.tensor(label).to(device)
90
+ # num_mel_channels = 80 (generally 80 for Whisper)
91
+ # mel_length = 3000 (ensured with the padding logic in processor)
92
+ # Then:
93
+ # Before squeeze(0):
94
+ # input_features shape: [1, 80, 3000]
95
+ # attention_mask shape: [1, 3000]
96
+ # After squeeze(0):
97
+ # input_features shape: [80, 3000]
98
+ # attention_mask shape: [3000]
99
+ # When the DataLoader forms a batch of size 8:
100
+ # input_features batch shape: [8, 80, 3000]
101
+ # attention_mask batch shape: [8, 3000]
102
+
103
+ def map_ravdess_emotion_to_label(self, emotion_code):
104
+ """Maps RAVDESS emotion codes to integer labels."""
105
+ if emotion_code == 1:
106
+ return self.label_mapping['neutral']
107
+ elif emotion_code == 2:
108
+ return self.label_mapping['calm']
109
+ elif emotion_code == 3:
110
+ return self.label_mapping['happy']
111
+ elif emotion_code == 4:
112
+ return self.label_mapping['sad']
113
+ elif emotion_code == 5:
114
+ return self.label_mapping['angry']
115
+ elif emotion_code == 6:
116
+ return self.label_mapping['fearful']
117
+ elif emotion_code == 7:
118
+ return self.label_mapping['disgust']
119
+ elif emotion_code == 8:
120
+ return self.label_mapping['surprised']
121
+ else:
122
+ raise ValueError(f"Invalid emotion code: {emotion_code}")
123
+
124
+ def calculate_metrics(model, data_loader):
125
+ model.eval()
126
+ predictions = []
127
+ true_labels = []
128
+ with torch.no_grad():
129
+ for inputs, _, labels in tqdm(data_loader):
130
+ outputs = model(inputs).logits
131
+ # outputs shape: [batch_size, num_labels]
132
+ predicted_labels = torch.argmax(outputs, dim=1)
133
+ # predicted_labels shape: [batch_size]
134
+ predictions.extend(predicted_labels.cpu().numpy())
135
+ true_labels.extend(labels.cpu().numpy())
136
+
137
+ accuracy = accuracy_score(true_labels, predictions)
138
+ macro_f1 = f1_score(true_labels, predictions, average="macro")
139
+ return accuracy, macro_f1
140
+
141
+ if __name__ == "__main__":
142
+ train_data_dirs = [
143
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_01",
144
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_02",
145
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_03",
146
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_04",
147
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_05",
148
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_06",
149
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_07",
150
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_08",
151
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_09",
152
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_10",
153
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_11",
154
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_12",
155
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_13",
156
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_14"
157
+ ]
158
+ val_data_dirs = ["dataset_my\\Audio_Song_Actors_01-24\\Actor_15",
159
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_16",
160
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_17",
161
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_19",]
162
+ test_data_dirs = ["dataset_my\\Audio_Song_Actors_01-24\\Actor_20",
163
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_21",
164
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_22",
165
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_23",
166
+ "dataset_my\\Audio_Song_Actors_01-24\\Actor_24"]
167
+
168
+ train_dataset = SpeechEmotionDataset(train_data_dirs, processor, label_mapping, MAX_DURATION)
169
+ val_dataset = SpeechEmotionDataset(val_data_dirs, processor, label_mapping, MAX_DURATION)
170
+ test_dataset = SpeechEmotionDataset(test_data_dirs, processor, label_mapping, MAX_DURATION)
171
+
172
+ # filter out any None values that were returned due to error
173
+ train_dataset.file_paths = [
174
+ f for i, f in enumerate(train_dataset.file_paths) if train_dataset[i] is not None
175
+ ]
176
+ train_dataset.labels = [
177
+ l for i, l in enumerate(train_dataset.labels) if train_dataset[i] is not None
178
+ ]
179
+ val_dataset.file_paths = [
180
+ f for i, f in enumerate(val_dataset.file_paths) if val_dataset[i] is not None
181
+ ]
182
+ val_dataset.labels = [
183
+ l for i, l in enumerate(val_dataset.labels) if val_dataset[i] is not None
184
+ ]
185
+ test_dataset.file_paths = [
186
+ f for i, f in enumerate(test_dataset.file_paths) if test_dataset[i] is not None
187
+ ]
188
+ test_dataset.labels = [
189
+ l for i, l in enumerate(test_dataset.labels) if test_dataset[i] is not None
190
+ ]
191
+
192
+ batch_size = 8
193
+ train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
194
+ val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)
195
+ test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
196
+
197
+ print(f"train loader (size = {len(train_loader)}) ::")
198
+ for data, _, labels in train_loader:
199
+ print(f'Data batch shape: {data.shape}')
200
+ print(f'Labels batch shape: {labels.shape}')
201
+ break
202
+
203
+ print(f"\nval loader (size = {len(val_loader)}) ::")
204
+ for data, _, labels in val_loader:
205
+ print(f'Data batch shape: {data.shape}')
206
+ print(f'Labels batch shape: {labels.shape}')
207
+ break
208
+
209
+ print(f"\ntest loader (size = {len(test_loader)}) ::")
210
+ for data, _, labels in test_loader:
211
+ print(f'Data batch shape: {data.shape}')
212
+ print(f'Labels batch shape: {labels.shape}')
213
+ break
214
+
215
+ optimizer = AdamW(model.parameters(), lr=1e-4)
216
+ scheduler = ReduceLROnPlateau(
217
+ optimizer, mode="max", factor=0.1, patience=3, verbose=True
218
+ )
219
+ loss_fn = torch.nn.CrossEntropyLoss()
220
+ num_epochs = 10
221
+ best_val_f1 = 0.0
222
+
223
+ for epoch in range(num_epochs):
224
+ # training
225
+ model.train()
226
+ total_loss = 0
227
+ for batch in tqdm(train_loader, desc=f"Epoch {epoch+1}/{num_epochs} [Train]"):
228
+ inputs, _, labels = batch
229
+ # inputs shape: [batch_size, num_mel_channels, mel_length]
230
+ # attention_mask shape: [batch_size, mel_length]
231
+ # labels shape: [batch_size]
232
+ optimizer.zero_grad()
233
+ outputs = model(inputs).logits
234
+ # outputs shape: [batch_size, num_labels]
235
+ loss = loss_fn(outputs, labels)
236
+ loss.backward()
237
+ optimizer.step()
238
+ total_loss += loss.item()
239
+
240
+ train_loss = total_loss / len(train_loader)
241
+ train_accuracy, train_macro_f1 = calculate_metrics(model, train_loader)
242
+
243
+ # validation
244
+ val_accuracy, val_macro_f1 = calculate_metrics(model, val_loader)
245
+
246
+ # update learning rate
247
+ scheduler.step(val_macro_f1)
248
+
249
+ print(
250
+ f" Train Loss: {train_loss:.4f}, Train Acc: {train_accuracy:.4f}, Train F1: {train_macro_f1:.4f}, Val Acc: {val_accuracy:.4f}, Val F1: {val_macro_f1:.4f}"
251
+ )
252
+
253
+ # save best model
254
+ if val_macro_f1 > best_val_f1:
255
+ best_val_f1 = val_macro_f1
256
+ torch.save(model, "best_ser_whisper.pkl")
257
+
text/.gitignore ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset_my/
2
+ old_dataset/
3
+
4
+ ### Database ###
5
+ *.sqlite3
6
+
7
+ ### bin ###
8
+ *.bin
9
+
10
+ ### Python ###
11
+ # Byte-compiled / optimized / DLL files
12
+ __pycache__/
13
+ *.py[cod]
14
+ *$py.class
15
+
16
+ # C extensions
17
+ *.so
18
+
19
+ # Distribution / packaging
20
+ .Python
21
+ build/
22
+ develop-eggs/
23
+ dist/
24
+ downloads/
25
+ eggs/
26
+ .eggs/
27
+ lib/
28
+ lib64/
29
+ parts/
30
+ sdist/
31
+ var/
32
+ wheels/
33
+ share/python-wheels/
34
+ *.egg-info/
35
+ .installed.cfg
36
+ *.egg
37
+ MANIFEST
38
+
39
+ # PyInstaller
40
+ # Usually these files are written by a python script from a template
41
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
42
+ *.manifest
43
+ *.spec
44
+
45
+ # Installer logs
46
+ pip-log.txt
47
+ pip-delete-this-directory.txt
48
+
49
+ # Unit test / coverage reports
50
+ htmlcov/
51
+ .tox/
52
+ .nox/
53
+ .coverage
54
+ .coverage.*
55
+ .cache
56
+ nosetests.xml
57
+ coverage.xml
58
+ *.cover
59
+ .hypothesis/
60
+ .pytest_cache/
61
+ cover/
62
+
63
+ # Translations
64
+ *.mo
65
+ *.pot
66
+
67
+ # Django stuff:
68
+ *.log
69
+ local_settings.py
70
+ db.sqlite3
71
+ db.sqlite3-journal
72
+
73
+ # Flask stuff:
74
+ instance/
75
+ .webassets-cache
76
+
77
+ # Scrapy stuff:
78
+ .scrapy
79
+
80
+ # Sphinx documentation
81
+ docs/_build/
82
+
83
+ # PyBuilder
84
+ .pybuilder/
85
+ target/
86
+
87
+ # Jupyter Notebook
88
+ .ipynb_checkpoints
89
+
90
+ # IPython
91
+ profile_default/
92
+ ipython_config.py
93
+
94
+ # pyenv
95
+ # For a library or package, you might want to ignore these files since the code is
96
+ # intended to run in multiple environments; otherwise, check them in:
97
+ # .python-version
98
+
99
+ # pipenv
100
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
101
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
102
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
103
+ # install all needed dependencies.
104
+ #Pipfile.lock
105
+
106
+ # pdm
107
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
108
+ #pdm.lock
109
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
110
+ # in version control.
111
+ # https://pdm.fming.dev/#use-with-ide
112
+ .pdm.toml
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Environments
118
+ *.env
119
+ .venv
120
+ env/
121
+ venv/
122
+ ENV/
123
+ env.bak/
124
+ venv.bak/
125
+
126
+ # PyCharm
127
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
128
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
129
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
130
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
131
+ .idea/
132
+
133
+ ### venv ###
134
+ pyvenv.cfg
135
+ pip-selfcheck.json
136
+
137
+ ### VisualStudioCode ###
138
+ .vscode/*
139
+ !.vscode/settings.json
140
+ !.vscode/tasks.json
141
+ !.vscode/launch.json
142
+ !.vscode/extensions.json
143
+ !.vscode/*.code-snippets
144
+
145
+ # Local History for Visual Studio Code
146
+ .history/
147
+
148
+ # Built Visual Studio Code Extensions
149
+ *.vsix
150
+
151
+ ### VisualStudioCode Patch ###
152
+ # Ignore all local history of files
153
+ .history
154
+ .ionide
155
+
text/README.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### API Documentation: Text Sentiment Analysis
2
+
3
+ This API uses a fine-tuned GPT-3.5-turbo model to predict the sentiment of a given text. It accepts a short paragraph and returns the predicted sentiment (`positive`, `negative`, or `neutral`). Run `python .\test.py` to start the FastAPI server in [http://0.0.0.0:8000](http://0.0.0.0:8000).
4
+
5
+ ---
6
+
7
+ ### Base URL
8
+ ```
9
+ http://0.0.0.0:8000
10
+ ```
11
+
12
+ ---
13
+
14
+ ### Endpoints
15
+
16
+ #### 1. **Predict Sentiment**
17
+ This endpoint accepts a short paragraph of text and returns the predicted sentiment.
18
+
19
+ - **Endpoint**: `POST /predict-sentiment/`
20
+ - **Request Body**:
21
+ ```json
22
+ {
23
+ "text": "I absolutely loved the product! It exceeded all my expectations."
24
+ }
25
+ ```
26
+ - **Response**:
27
+ - **Success (200 OK)**:
28
+ ```json
29
+ {
30
+ "sentiment": "positive"
31
+ }
32
+ ```
33
+ - **Error (500 Internal Server Error)**:
34
+ ```json
35
+ {
36
+ "detail": "Error message describing the issue."
37
+ }
38
+ ```
39
+
40
+ ---
41
+
42
+ ### Example Usage
43
+
44
+ #### Request
45
+ ```bash
46
+ curl -X POST "http://0.0.0.0:8000/predict-sentiment/" \
47
+ -H "Content-Type: application/json" \
48
+ -d '{"text": "I absolutely loved the product! It exceeded all my expectations."}'
49
+ ```
50
+
51
+ #### Response
52
+ ```json
53
+ {
54
+ "sentiment": "positive"
55
+ }
56
+ ```
57
+
58
+ ---
59
+
60
+ ### Notes
61
+ - The API uses a fine-tuned GPT-3.5-turbo model for sentiment analysis.
62
+ - The `text` field in the request body should contain a short paragraph.
63
+ - The response will always include a `sentiment` field with one of the following values: `positive`, `negative`, or `neutral`.
64
+ - Replace value of the `api_key` parameter with the actual OpenAI key
text/create_dataset.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from sklearn.model_selection import train_test_split
3
+ import json
4
+
5
+ # Load the dataset
6
+ def load_dataset(filepath):
7
+ return pd.read_csv(filepath, encoding='latin-1')
8
+
9
+ def preprocess_dataset(df):
10
+ """
11
+ Preprocess the dataset:
12
+ 1. Drop rows where 'review' is NaN.
13
+ 2. Drop rows where 'review-label' is NaN.
14
+ 3. Drop rows where 'review' is an empty string.
15
+ """
16
+ # Drop rows with NaN in 'review' or 'review-label'
17
+ df = df.dropna(subset=["review", "review-label"])
18
+
19
+ # Drop rows where 'review' is an empty string
20
+ df = df[df["review"].str.strip() != ""]
21
+
22
+ return df
23
+
24
+ # Map review-label to sentiment
25
+ def map_label_to_sentiment(label):
26
+ if label > 3:
27
+ return "positive"
28
+ elif label < 3:
29
+ return "negative"
30
+ else:
31
+ return "neutral"
32
+
33
+ # Convert dataset to JSONL format
34
+ def convert_to_jsonl(df, output_file):
35
+ with open(output_file, "w") as f:
36
+ for _, row in df.iterrows():
37
+ review = row["review"]
38
+ sentiment = map_label_to_sentiment(row["review-label"])
39
+ jsonl_entry = {
40
+ "messages": [
41
+ {"role": "system", "content": "You are a sentiment analysis assistant. Classify the sentiment of the user's message as 'positive', 'negative' or 'neutral'."},
42
+ {"role": "user", "content": review},
43
+ {"role": "assistant", "content": sentiment}
44
+ ]
45
+ }
46
+ f.write(json.dumps(jsonl_entry) + "\n")
47
+
48
+ # Main function
49
+ def process_dataset(filepath, train_output="dataset_my\\train.jsonl", val_output="dataset_my\\val.jsonl", test_output="dataset_my\\test.jsonl", test_size=0.2, val_size=0.1):
50
+ # Load the dataset
51
+ df = load_dataset(filepath)
52
+
53
+ # Preprocess dataset
54
+ df = preprocess_dataset(df)
55
+
56
+ # Split the dataset into train, validation, and test sets
57
+ train_df, test_df = train_test_split(df, test_size=test_size, random_state=42)
58
+ train_df, val_df = train_test_split(train_df, test_size=val_size, random_state=42)
59
+
60
+ # Convert each split to JSONL format
61
+ convert_to_jsonl(train_df, train_output)
62
+ convert_to_jsonl(val_df, val_output)
63
+ convert_to_jsonl(test_df, test_output)
64
+
65
+ print(f"Dataset processed and saved to {train_output}, {val_output}, and {test_output}")
66
+
67
+ filepath = "dataset_my\\TeePublic_review.csv"
68
+ process_dataset(filepath)
text/requirements.txt ADDED
Binary file (1.08 kB). View file
 
text/test.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import timedelta
2
+ from tqdm import tqdm
3
+ from sklearn.metrics import accuracy_score
4
+ import json
5
+ from fastapi import FastAPI, HTTPException
6
+ from pydantic import BaseModel
7
+ from openai import OpenAI
8
+ from datetime import timedelta
9
+ from openai import OpenAI
10
+ import uvicorn
11
+ import os
12
+
13
+ app = FastAPI()
14
+
15
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
16
+
17
+ fine_tune_id = "ftjob-2nIK3dvxJf4QiAb6DQQ4A1GN"
18
+ ft_job_details = client.fine_tuning.jobs.retrieve(fine_tune_id)
19
+ fine_tuned_model = ft_job_details.fine_tuned_model
20
+
21
+ class SentimentRequest(BaseModel):
22
+ text: str # Input text (sentence / short paragraph)
23
+
24
+ class SentimentResponse(BaseModel):
25
+ sentiment: str # Predicted sentiment (positive/negative)
26
+
27
+ # Endpoint to predict sentiment
28
+ @app.post("/predict-sentiment/", response_model=SentimentResponse)
29
+ async def predict_sentiment(request: SentimentRequest):
30
+ try:
31
+ # System prompt (customize based on your fine-tuning)
32
+ system_prompt = "You are a sentiment analysis model. Analyze the sentiment of the following text and respond with 'positive' or 'negative'."
33
+
34
+ # Get the input text
35
+ input_text = request.text
36
+
37
+ # Call the fine-tuned model
38
+ response = client.chat.completions.create(
39
+ model=fine_tuned_model,
40
+ messages=[
41
+ {"role": "system", "content": system_prompt},
42
+ {"role": "user", "content": input_text}
43
+ ]
44
+ )
45
+
46
+ # Extract the predicted sentiment
47
+ predicted_sentiment = response.choices[0].message.content.strip().lower()
48
+
49
+ # Determine the most likely sentiment
50
+ if 'positive' in predicted_sentiment:
51
+ sentiment = "positive"
52
+ elif 'negative' in predicted_sentiment:
53
+ sentiment = "negative"
54
+ else:
55
+ sentiment = "neutral"
56
+
57
+ return {"sentiment": sentiment}
58
+ except Exception as e:
59
+ raise HTTPException(status_code=500, detail=f"Error predicting sentiment: {str(e)}")
60
+
61
+ if __name__ == '__main__':
62
+ uvicorn.run(app, host="0.0.0.0", port=8000)
text/train.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from openai import OpenAI
2
+ from dotenv import load_dotenv
3
+ load_dotenv()
4
+ client = OpenAI(api_key="")
5
+
6
+ train_file = client.files.create(
7
+ file=open("dataset_my\\train.jsonl", "rb"),
8
+ purpose="fine-tune"
9
+ )
10
+
11
+ print(f"train file created with id : {train_file.id}")
12
+
13
+ validation_file = client.files.create(
14
+ file=open("dataset_my\\val.jsonl", "rb"),
15
+ purpose="fine-tune"
16
+ )
17
+
18
+ print(f"validation file created with id : {validation_file.id}")
19
+
20
+ fine_tune_response = client.fine_tuning.jobs.create(
21
+ training_file=train_file.id,
22
+ model="gpt-4o-mini-2024-07-18",
23
+ suffix='shopper_review_sentiment',
24
+ validation_file=validation_file.id,
25
+ seed=88
26
+ )
27
+
28
+ fine_tune_id = fine_tune_response.id
29
+ status = client.fine_tuning.jobs.retrieve(fine_tune_id)
30
+ print(f"Fine-tuning status: {status}")
31
+
vision/.gitignore ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ best_fer_clip_vit.pkl
2
+
3
+ ### Database ###
4
+ *.sqlite3
5
+
6
+ ### bin ###
7
+ *.bin
8
+
9
+ ### Python ###
10
+ # Byte-compiled / optimized / DLL files
11
+ __pycache__/
12
+ *.py[cod]
13
+ *$py.class
14
+
15
+ # C extensions
16
+ *.so
17
+
18
+ # Distribution / packaging
19
+ .Python
20
+ build/
21
+ develop-eggs/
22
+ dist/
23
+ downloads/
24
+ eggs/
25
+ .eggs/
26
+ lib/
27
+ lib64/
28
+ parts/
29
+ sdist/
30
+ var/
31
+ wheels/
32
+ share/python-wheels/
33
+ *.egg-info/
34
+ .installed.cfg
35
+ *.egg
36
+ MANIFEST
37
+
38
+ # PyInstaller
39
+ # Usually these files are written by a python script from a template
40
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
41
+ *.manifest
42
+ *.spec
43
+
44
+ # Installer logs
45
+ pip-log.txt
46
+ pip-delete-this-directory.txt
47
+
48
+ # Unit test / coverage reports
49
+ htmlcov/
50
+ .tox/
51
+ .nox/
52
+ .coverage
53
+ .coverage.*
54
+ .cache
55
+ nosetests.xml
56
+ coverage.xml
57
+ *.cover
58
+ .hypothesis/
59
+ .pytest_cache/
60
+ cover/
61
+
62
+ # Translations
63
+ *.mo
64
+ *.pot
65
+
66
+ # Django stuff:
67
+ *.log
68
+ local_settings.py
69
+ db.sqlite3
70
+ db.sqlite3-journal
71
+
72
+ # Flask stuff:
73
+ instance/
74
+ .webassets-cache
75
+
76
+ # Scrapy stuff:
77
+ .scrapy
78
+
79
+ # Sphinx documentation
80
+ docs/_build/
81
+
82
+ # PyBuilder
83
+ .pybuilder/
84
+ target/
85
+
86
+ # Jupyter Notebook
87
+ .ipynb_checkpoints
88
+
89
+ # IPython
90
+ profile_default/
91
+ ipython_config.py
92
+
93
+ # pyenv
94
+ # For a library or package, you might want to ignore these files since the code is
95
+ # intended to run in multiple environments; otherwise, check them in:
96
+ # .python-version
97
+
98
+ # pipenv
99
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
100
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
101
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
102
+ # install all needed dependencies.
103
+ #Pipfile.lock
104
+
105
+ # pdm
106
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
107
+ #pdm.lock
108
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
109
+ # in version control.
110
+ # https://pdm.fming.dev/#use-with-ide
111
+ .pdm.toml
112
+
113
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
114
+ __pypackages__/
115
+
116
+ # Environments
117
+ *.env
118
+ .venv
119
+ env/
120
+ venv/
121
+ ENV/
122
+ env.bak/
123
+ venv.bak/
124
+
125
+ # PyCharm
126
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
127
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
128
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
129
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
130
+ .idea/
131
+
132
+ ### venv ###
133
+ pyvenv.cfg
134
+ pip-selfcheck.json
135
+
136
+ ### VisualStudioCode ###
137
+ .vscode/*
138
+ !.vscode/settings.json
139
+ !.vscode/tasks.json
140
+ !.vscode/launch.json
141
+ !.vscode/extensions.json
142
+ !.vscode/*.code-snippets
143
+
144
+ # Local History for Visual Studio Code
145
+ .history/
146
+
147
+ # Built Visual Studio Code Extensions
148
+ *.vsix
149
+
150
+ ### VisualStudioCode Patch ###
151
+ # Ignore all local history of files
152
+ .history
153
+ .ionide
154
+
vision/README.md ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### API Documentation (Markdown)
2
+
3
+ ### **Endpoints**
4
+
5
+ #### 1. **Classify Emotion**
6
+ This endpoint accepts an [image file](./dataset_my/pilot_test) and returns the predicted emotion probabilities and the most likely emotion. To create the api on localhost, run [test.py](./test.py) using ```python test.py``` command.
7
+
8
+ - **Endpoint**: `POST /classify-emotion/`
9
+ - **Request Body**:
10
+ - **Key**: `image_file`
11
+ - **Value**: The image file to analyze (e.g., `.jpg`, `.png`).
12
+ - **Response**:
13
+ - **Success (200 OK)**:
14
+ ```json
15
+ {
16
+ "most_likely_emotion": "happy",
17
+ "emotion_probabilities": {
18
+ "angry": 0.01,
19
+ "disgust": 0.02,
20
+ "fear": 0.03,
21
+ "happy": 0.8,
22
+ "sad": 0.05,
23
+ "surprise": 0.04,
24
+ "neutral": 0.05
25
+ }
26
+ }
27
+ ```
28
+ - **Error (500 Internal Server Error)**:
29
+ ```json
30
+ {
31
+ "detail": "Error message describing the issue."
32
+ }
33
+ ```
34
+
35
+ ---
36
+
37
+ ### Instructions for API Testing with Postman
38
+
39
+ #### Step 1: Set Up the Request
40
+ 1. Open Postman.
41
+ 2. Set the request type to `POST`.
42
+ 3. Enter the URL:
43
+ ```
44
+ http://127.0.0.1:8000/classify-emotion/
45
+ ```
46
+
47
+ #### Step 2: Configure the Body
48
+ 1. Go to the **Body** tab.
49
+ 2. Select **form-data**.
50
+
51
+ #### Step 3: Add the Image
52
+ 1. In the **Key** field, enter `image_file` (this must match the parameter name in the API).
53
+ 2. Hover over the **Value** field, and click the dropdown that says **Text**. Change it to **File**.
54
+ 3. Click **Choose File** and select your image file (e.g., `test_image.jpg`).
55
+
56
+ #### Step 4: Send the Request
57
+ 1. Click the **Send** button to submit the request.
58
+
59
+ ---
60
+
61
+ ### Example Postman Configuration
62
+
63
+ #### **Headers**:
64
+ - Postman automatically sets the `Content-Type` to `multipart/form-data` when you use the **form-data** option. You don’t need to manually add this header.
65
+
66
+ #### **Body**:
67
+ | Key | Value
68
+ |-------------|--------------------
69
+ | `image_file`| `angry.jpeg.jpg`
70
+
71
+ ---
72
+
73
+ ### Example Workflow in Postman
74
+
75
+ 1. **Set Up the Request**:
76
+ - Method: `POST`
77
+ - URL: `http://127.0.0.1:8000/classify-emotion/`
78
+ - Body: `form-data`
79
+ - Key: `image_file`
80
+ - Value: `angry.jpeg` (select as **File**)
81
+
82
+ 2. **Send the Request**:
83
+ - Click **Send**.
84
+
85
+ 3. **Check the Response**:
86
+ - If successful, you’ll see the predicted emotion and probabilities:
87
+ ```json
88
+ {
89
+ "most_likely_emotion": "happy",
90
+ "emotion_probabilities": {
91
+ "angry": 0.01,
92
+ "disgust": 0.02,
93
+ "fear": 0.03,
94
+ "happy": 0.8,
95
+ "sad": 0.05,
96
+ "surprise": 0.04,
97
+ "neutral": 0.05
98
+ }
99
+ }
100
+ ```
101
+ - If there’s an error, check the error message and debug accordingly.
102
+
103
+ ---
vision/dataset_my/pilot_test/angry.jpeg ADDED
vision/dataset_my/pilot_test/angry_2.jpg ADDED
vision/dataset_my/pilot_test/disgusted.png ADDED
vision/dataset_my/pilot_test/sad.jpg ADDED
vision/dataset_my/pilot_test/surprised.jpeg ADDED
vision/facial-emotion-recog-customers.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
vision/requirements.txt ADDED
Binary file (1.35 kB). View file
 
vision/test.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile, HTTPException
2
+ from fastapi.responses import JSONResponse
3
+ from PIL import Image
4
+ import torch
5
+ from torchvision import transforms
6
+ import io
7
+ import uvicorn
8
+ from transformers import CLIPProcessor, CLIPModel
9
+ import warnings
10
+ warnings.filterwarnings("ignore", category=FutureWarning)
11
+
12
+ model_id = "openai/clip-vit-base-patch32"
13
+ clip_model = CLIPModel.from_pretrained(model_id)
14
+ processor = CLIPProcessor.from_pretrained(model_id)
15
+ NUM_CLASSES = 7
16
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
17
+
18
+ class EmotionRecognitionModel(torch.nn.Module):
19
+ def __init__(self, clip_model, num_classes):
20
+ super(EmotionRecognitionModel, self).__init__()
21
+ self.clip_vision_model = clip_model.vision_model
22
+ self.fc = torch.nn.Linear(768, num_classes)
23
+
24
+ def forward(self, images):
25
+ with torch.no_grad():
26
+ vision_outputs = self.clip_vision_model(pixel_values=images)
27
+ embeddings = vision_outputs.last_hidden_state[:, 0, :] # CLS token embeddings (shape: [batch_size, 768])
28
+ outputs = self.fc(embeddings) # Shape: [batch_size, num_classes]
29
+ return outputs
30
+
31
+ model = EmotionRecognitionModel(clip_model, NUM_CLASSES).to(DEVICE)
32
+
33
+ app = FastAPI()
34
+
35
+ # Load the pre-trained model
36
+ # model = torch.load("best_fer_clip_vit.pkl", map_location=DEVICE)
37
+ model.load_state_dict(torch.load("F:\\sociofi_my\\projects\\sentiment_analysis\\vision\\best_fer_clip_vit.pkl", map_location=DEVICE, weights_only=False))
38
+ model.eval()
39
+
40
+ # Define the image transformation pipeline
41
+ transform = transforms.Compose([
42
+ transforms.Resize((224, 224)), # Resize to match model input size
43
+ transforms.ToTensor(), # Convert to tensor
44
+ transforms.Normalize( # Normalize
45
+ mean=[0.485, 0.456, 0.406],
46
+ std=[0.229, 0.224, 0.225]
47
+ )
48
+ ])
49
+
50
+ # Emotion labels
51
+ emotion_labels = ["angry", "disgust", "fear", "happy", "sad", "surprise", "neutral"]
52
+
53
+ # Function to classify emotion
54
+ def classify_emotion(input_image):
55
+ transformed_image = transform(input_image).unsqueeze(0).to(DEVICE)
56
+
57
+ with torch.no_grad():
58
+ outputs = model(transformed_image)
59
+ probabilities = torch.softmax(outputs, dim=1).squeeze(0)
60
+
61
+ prob_dict = {emotion_labels[i]: probabilities[i].item() for i in range(len(emotion_labels))}
62
+ most_likely_emotion_idx = torch.argmax(probabilities).item()
63
+ most_likely_emotion = emotion_labels[most_likely_emotion_idx]
64
+
65
+ return prob_dict, most_likely_emotion
66
+
67
+ # Endpoint to classify emotion
68
+ @app.post("/classify-emotion/")
69
+ async def classify_emotion_endpoint(image_file: UploadFile = File(...)):
70
+ try:
71
+ # Read the uploaded image file
72
+ image_bytes = await image_file.read()
73
+ image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
74
+
75
+ # Classify the emotion
76
+ prob_dict, most_likely_emotion = classify_emotion(image)
77
+
78
+ return JSONResponse({
79
+ "most_likely_emotion": most_likely_emotion,
80
+ "emotion_probabilities": prob_dict
81
+ })
82
+ except Exception as e:
83
+ raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")
84
+
85
+ # Run the FastAPI app
86
+ if __name__ == '__main__':
87
+ uvicorn.run(app, host="0.0.0.0", port=8000)