YashsharmaPhD commited on
Commit
b69af29
·
verified ·
1 Parent(s): 68d4170

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -45
app.py CHANGED
@@ -1,46 +1,82 @@
1
  import streamlit as st
2
- from ftplib import FTP, error_perm, error_temp
3
-
4
- # FTP server credentials
5
- host = "cph.v4one.co.uk"
6
- username = "yash.sharma"
7
- password = "8x]EnG/Z%DXvcjt[%<;S" # Replace with your actual password
8
-
9
- # Streamlit UI for FTP connection
10
- st.title("FTP File Browser")
11
-
12
- st.sidebar.header("FTP Connection Details")
13
- host_input = st.sidebar.text_input("Host", host)
14
- username_input = st.sidebar.text_input("Username", username)
15
- password_input = st.sidebar.text_input("Password", type="password", value=password)
16
-
17
- if st.sidebar.button("🔄 Connect & List Files"):
18
- try:
19
- # Connect to FTP server with a timeout of 120 seconds
20
-
21
- ftp = FTP(host_input, timeout=120)
22
- ftp.connect(host, 21)
23
- ftp.login(user=username_input, passwd=password_input)
24
-
25
- # Enable passive mode
26
- ftp.set_pasv(True)
27
-
28
- # List files in the root directory
29
- files = []
30
- ftp.retrlines('LIST', lambda x: files.append(x.split()[-1])) # Get filenames from LIST command
31
-
32
- ftp.quit()
33
-
34
- # Show files in dropdown
35
- if files:
36
- selected_file = st.selectbox("Select a file", files)
37
- st.write(f"File selected: {selected_file}")
38
- else:
39
- st.warning("No files found on the FTP server.")
40
-
41
- except error_perm as e:
42
- st.error(f"FTP Permission Error: {e}")
43
- except error_temp as e:
44
- st.error(f"FTP Temporary Error: {e}")
45
- except Exception as e:
46
- st.error(f"Error: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import librosa
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ from pydub import AudioSegment
6
+ from transformers import pipeline
7
+ import os
8
+
9
+ # Load pre-trained sentiment analysis model
10
+ sentiment_analyzer = pipeline("sentiment-analysis")
11
+
12
+ # Streamlit UI
13
+ st.title("🎤 Audio Sentiment Analysis")
14
+ st.write("Upload multiple MP3 files to analyze sentiment and tone.")
15
+
16
+ # Upload multiple audio files
17
+ uploaded_files = st.file_uploader("Choose MP3 files", type=["mp3"], accept_multiple_files=True)
18
+
19
+ # Function to process audio and get sentiment
20
+ def analyze_audio(file_path):
21
+ # Convert MP3 to WAV
22
+ audio = AudioSegment.from_mp3(file_path)
23
+ wav_path = file_path.replace(".mp3", ".wav")
24
+ audio.export(wav_path, format="wav")
25
+
26
+ # Load audio
27
+ y, sr = librosa.load(wav_path, sr=None)
28
+
29
+ # Extract MFCCs (Mel-frequency cepstral coefficients)
30
+ mfccs = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13)
31
+ mfccs_mean = np.mean(mfccs, axis=1) # Take mean across time axis
32
+
33
+ # Dummy text for sentiment analysis (replace with actual text from speech-to-text if needed)
34
+ sentiment_result = sentiment_analyzer("This is a placeholder for sentiment analysis based on audio!")
35
+
36
+ # Remove WAV file after processing
37
+ os.remove(wav_path)
38
+
39
+ return sentiment_result[0], mfccs_mean, y, sr
40
+
41
+ # Process and plot if files are uploaded
42
+ if uploaded_files:
43
+ # Create a directory to store temporary files
44
+ os.makedirs("temp", exist_ok=True)
45
+
46
+ for uploaded_file in uploaded_files:
47
+ # Save the uploaded file
48
+ file_path = f"temp/{uploaded_file.name}"
49
+ with open(file_path, "wb") as f:
50
+ f.write(uploaded_file.getbuffer())
51
+
52
+ # Analyze sentiment and extract features
53
+ sentiment, mfccs, audio_data, sample_rate = analyze_audio(file_path)
54
+
55
+ # Display sentiment result
56
+ st.subheader(f"📊 Sentiment Analysis Result for {uploaded_file.name}")
57
+ st.write(f"**Sentiment:** {sentiment['label']}")
58
+ st.write(f"**Confidence:** {sentiment['score']:.2f}")
59
+
60
+ # Agent Tone Plot (Sentiment over time)
61
+ st.subheader(f"🎵 Agent Tone Plot for {uploaded_file.name}")
62
+ tone_score = sentiment['score'] if sentiment['label'] == 'POSITIVE' else -sentiment['score']
63
+ fig, ax = plt.subplots()
64
+ ax.plot([tone_score] * len(audio_data), label="Agent's Tone")
65
+ ax.set_xlabel("Time (seconds)")
66
+ ax.set_ylabel("Tone Score")
67
+ ax.set_title("Agent's Tone Plot Over Time")
68
+ ax.legend()
69
+ st.pyplot(fig)
70
+
71
+ # Patient Tone Curve (MFCC features)
72
+ st.subheader(f"🎶 Patient Tone Curve for {uploaded_file.name}")
73
+ fig, ax = plt.subplots()
74
+ ax.plot(np.mean(mfccs, axis=0), label="Patient's Tone Curve (MFCCs)")
75
+ ax.set_xlabel("MFCC Coefficients")
76
+ ax.set_ylabel("Mean Value")
77
+ ax.set_title("Patient Tone Curve")
78
+ ax.legend()
79
+ st.pyplot(fig)
80
+
81
+ # Clean up temp file
82
+ os.remove(file_path)