NeuSpaarX commited on
Commit
5a792bc
·
verified ·
1 Parent(s): 683b9bc

Upload 4 files

Browse files
Files changed (4) hide show
  1. app.py +139 -0
  2. brain_of_the_doctor.py +58 -0
  3. voice_of_the_doctor.py +104 -0
  4. voice_of_the_patient.py +78 -0
app.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from dotenv import load_dotenv
3
+ import os
4
+ from PIL import Image
5
+ import datetime
6
+
7
+
8
+ from brain_of_the_doctor import encode_image, analyze_image_with_query
9
+ from voice_of_the_patient import record_audio, transcribe_with_groq
10
+ from voice_of_the_doctor import text_to_speech_with_elevenlabs
11
+
12
+
13
+ load_dotenv()
14
+
15
+
16
+ system_prompt = """You have to act as a professional doctor, i know you are not but this is for learning purpose.
17
+ What's in this image?. Do you find anything wrong with it medically?
18
+ If you make a differential, suggest some remedies for them. Donot add any numbers or special characters in
19
+ your response. Your response should be in one long paragraph. Also always answer as if you are answering to a real person.
20
+ Donot say 'In the image I see' but say 'With what I see, I think you have ....'
21
+ Dont respond as an AI model in markdown, your answer should mimic that of an actual doctor not an AI bot,
22
+ Keep your answer concise (max 2 sentences). No preamble, start your answer right away please. Dont tell u shoud go to doctor. if user ask for medicine then suggest medicine also
23
+ Dont say this : I cannot help you with that. I strongly advise against taking any medication without a prescription from a healthcare professional.
24
+ Suggest meditions to user.
25
+ """
26
+
27
+
28
+ def display_chat_message(speaker, text, timestamp):
29
+ if speaker == "Patient":
30
+ # User message (aligned to the right)
31
+ st.markdown(
32
+ f"""
33
+ <div style="display: flex; justify-content: flex-end; margin-bottom: 10px;">
34
+ <div style="background: #DCF8C6; padding: 10px; border-radius: 10px; max-width: 70%;">
35
+ <p style="margin: 0;">{text}</p>
36
+ <small style="color: gray; text-align: right;">{timestamp}</small>
37
+ </div>
38
+ </div>
39
+ """,
40
+ unsafe_allow_html=True,
41
+ )
42
+ else:
43
+ # Doctor message (aligned to the left)
44
+ st.markdown(
45
+ f"""
46
+ <div style="display: flex; justify-content: flex-start; margin-bottom: 10px;">
47
+ <div style="background: #ECECEC; padding: 10px; border-radius: 10px; max-width: 70%;">
48
+ <p style="margin: 0;">{text}</p>
49
+ <small style="color: gray;">{timestamp}</small>
50
+ </div>
51
+ </div>
52
+ """,
53
+ unsafe_allow_html=True,
54
+ )
55
+
56
+ def main():
57
+ st.title("AI Doctor By NueSpaarx")
58
+
59
+
60
+ if 'conversation' not in st.session_state:
61
+ st.session_state.conversation = []
62
+
63
+ # Display the chat interface
64
+ st.header("Chat with AI Doctor")
65
+
66
+ # Chat container
67
+ chat_container = st.container()
68
+
69
+ # Display the entire conversation history in chat format
70
+ with chat_container:
71
+ for entry in st.session_state.conversation:
72
+ display_chat_message(entry["speaker"], entry["text"], entry["timestamp"])
73
+
74
+ # Image input
75
+ st.header("Upload an Image")
76
+ image_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
77
+
78
+ if image_file is not None:
79
+ st.image(Image.open(image_file), caption="Uploaded Image", use_column_width=True)
80
+
81
+ # Audio input
82
+ st.header("Record Your Voice")
83
+ audio_filepath = "patient_voice_test_for_patient.mp3"
84
+ if st.button("Record Audio"):
85
+ record_audio(file_path=audio_filepath)
86
+ st.audio(audio_filepath, format="audio/mp3")
87
+
88
+ if st.button("Analyze"):
89
+ if image_file is not None:
90
+ # Save the uploaded image to a temporary file
91
+ image_filepath = "temp_image.jpg"
92
+ with open(image_filepath, "wb") as f:
93
+ f.write(image_file.getbuffer())
94
+
95
+ # Process the inputs
96
+ speech_to_text_output = transcribe_with_groq(
97
+ GROQ_API_KEY=os.environ.get("GROQ_API_KEY"),
98
+ audio_filepath=audio_filepath,
99
+ stt_model="whisper-large-v3"
100
+ )
101
+
102
+ # Add user query to conversation history with timestamp
103
+ st.session_state.conversation.append({
104
+ "speaker": "Patient",
105
+ "text": speech_to_text_output,
106
+ "timestamp": datetime.datetime.now().strftime("%H:%M")
107
+ })
108
+
109
+ # Analyze the image and user query
110
+ doctor_response = analyze_image_with_query(
111
+ query=system_prompt + speech_to_text_output,
112
+ encoded_image=encode_image(image_filepath),
113
+ model="llama-3.2-11b-vision-preview"
114
+ )
115
+
116
+ # Add doctor's response to conversation history with timestamp
117
+ st.session_state.conversation.append({
118
+ "speaker": "Doctor",
119
+ "text": doctor_response,
120
+ "timestamp": datetime.datetime.now().strftime("%H:%M")
121
+ })
122
+
123
+ # Convert doctor's response to speech
124
+ voice_of_doctor = text_to_speech_with_elevenlabs(
125
+ input_text=doctor_response,
126
+ output_filepath="final.mp3"
127
+ )
128
+
129
+ # Display the doctor's voice response
130
+ st.header("Doctor's Voice")
131
+ st.audio("final.mp3", format="audio/mp3")
132
+
133
+ # Rerun the app to update the chat interface
134
+ st.rerun()
135
+ else:
136
+ st.error("Please upload an image to analyze.")
137
+
138
+ if __name__ == "__main__":
139
+ main()
brain_of_the_doctor.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ load_dotenv()
3
+
4
+ #Step1: Setup GROQ API key
5
+ import os
6
+
7
+ GROQ_API_KEY=os.environ.get("GROQ_API_KEY")
8
+
9
+
10
+ import base64
11
+
12
+
13
+ #image_path="acne.jpg"
14
+
15
+ def encode_image(image_path):
16
+ image_file=open(image_path, "rb")
17
+ return base64.b64encode(image_file.read()).decode('utf-8')
18
+
19
+
20
+ #Step3: Setup Multimodal LLM
21
+
22
+ from groq import Groq
23
+
24
+ query="Is there something wrong with my face?"
25
+ model="llama-3.2-90b-vision-preview"
26
+
27
+
28
+ def analyze_image_with_query(query, model, encoded_image):
29
+ client=Groq()
30
+ messages=[
31
+ {
32
+ "role": "user",
33
+ "content": [
34
+ {
35
+ "type": "text",
36
+ "text": query
37
+ },
38
+ {
39
+ "type": "image_url",
40
+ "image_url": {
41
+ "url": f"data:image/jpeg;base64,{encoded_image}",
42
+ },
43
+ },
44
+ ],
45
+ }]
46
+ chat_completion=client.chat.completions.create(
47
+ messages=messages,
48
+ model=model
49
+ )
50
+ # print(chat_completion)
51
+ # print(chat_completion.choices[0])
52
+ # print(chat_completion.choices[0].message)
53
+
54
+ # print(chat_completion.choices[0].message.content)
55
+
56
+ return chat_completion.choices[0].message.content
57
+
58
+
voice_of_the_doctor.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from dotenv import load_dotenv
3
+ load_dotenv()
4
+
5
+ #Step1a: Setup Text to Speech–TTS–model with gTTS
6
+ import os
7
+ from gtts import gTTS
8
+
9
+ def text_to_speech_with_gtts_old(input_text, output_filepath):
10
+ language="en"
11
+
12
+ audioobj= gTTS(
13
+ text=input_text,
14
+ lang=language,
15
+ slow=False
16
+ # slow=True
17
+ )
18
+ audioobj.save(output_filepath)
19
+
20
+
21
+ input_text="Hi this is Balkrishna Joshi!"
22
+ text_to_speech_with_gtts_old(input_text=input_text, output_filepath="gtts_testing.mp3")
23
+
24
+ #Step1b: Setup Text to Speech–TTS–model with ElevenLabs
25
+ import elevenlabs
26
+ from elevenlabs.client import ElevenLabs
27
+
28
+ ELEVENLABS_API_KEY=os.environ.get("ELEVENLABS_API_KEY")
29
+
30
+ def text_to_speech_with_elevenlabs_old(input_text, output_filepath):
31
+ client=ElevenLabs(api_key=ELEVENLABS_API_KEY)
32
+ audio=client.generate(
33
+ text= input_text,
34
+ voice= "Aria",
35
+ output_format= "mp3_22050_32",
36
+ model= "eleven_turbo_v2"
37
+ )
38
+ elevenlabs.save(audio, output_filepath)
39
+
40
+ #text_to_speech_with_elevenlabs_old(input_text, output_filepath="elevenlabs_testing.mp3")
41
+
42
+ #Step2: Use Model for Text output to Voice
43
+
44
+ import subprocess
45
+ import platform
46
+
47
+ def text_to_speech_with_gtts(input_text, output_filepath):
48
+ language="en"
49
+
50
+ audioobj= gTTS(
51
+ text=input_text,
52
+ lang=language,
53
+ slow=False
54
+ )
55
+ audioobj.save(output_filepath)
56
+ os_name = platform.system()
57
+ try:
58
+ if os_name == "Darwin": # macOS
59
+ subprocess.run(['afplay', output_filepath])
60
+ elif os_name == "Windows": # Windows
61
+ # subprocess.run(['powershell', '-c', f'(New-Object Media.SoundPlayer "{output_filepath}").PlaySync();'])
62
+ subprocess.run(['start', output_filepath], shell=True) #working but it open new mp3 player
63
+ # subprocess.run(['ffplay', '-nodisp', '-autoexit', output_filepath])
64
+
65
+
66
+ elif os_name == "Linux": # Linux
67
+ subprocess.run(['aplay', output_filepath]) # Alternative: use 'mpg123' or 'ffplay'
68
+ else:
69
+ raise OSError("Unsupported operating system")
70
+ except Exception as e:
71
+ print(f"An error occurred while trying to play the audio: {e}")
72
+
73
+
74
+ input_text="Hi this is Balkrishna Joshi from NeuspaarX, autoplay testing!"
75
+ # text_to_speech_with_gtts(input_text=input_text, output_filepath="gtts_testing_autoplay.mp3")
76
+
77
+
78
+ def text_to_speech_with_elevenlabs(input_text, output_filepath):
79
+ client=ElevenLabs(api_key=ELEVENLABS_API_KEY)
80
+ audio=client.generate(
81
+ text= input_text,
82
+ voice= "Aria",
83
+ output_format= "mp3_22050_32",
84
+ model= "eleven_turbo_v2"
85
+ )
86
+ elevenlabs.save(audio, output_filepath)
87
+ os_name = platform.system()
88
+ try:
89
+ if os_name == "Darwin": # macOS
90
+ subprocess.run(['afplay', output_filepath])
91
+ elif os_name == "Windows": # Windows
92
+ # subprocess.run(['powershell', '-c', f'(New-Object Media.SoundPlayer "{output_filepath}").PlaySync();'])
93
+ subprocess.run(['start', output_filepath], shell=True) #---working but it open new mp3 player
94
+ # subprocess.run(['ffplay', '-nodisp', '-autoexit', output_filepath])
95
+ elif os_name == "Linux": # Linux
96
+ subprocess.run(['aplay', output_filepath]) # Alternative: use 'mpg123' or 'ffplay'
97
+ else:
98
+ raise OSError("Unsupported operating system")
99
+ except Exception as e:
100
+ print(f"An error occurred while trying to play the audio: {e}")
101
+
102
+ # text_to_speech_with_elevenlabs(input_text, output_filepath="elevenlabs_testing_autoplay.mp3")
103
+
104
+
voice_of_the_patient.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ from dotenv import load_dotenv
4
+ load_dotenv()
5
+
6
+
7
+ # Setup Audio recorder (ffmpeg & portaudio)
8
+ # ffmpeg, portaudio, pyaudio
9
+
10
+ import logging
11
+ import speech_recognition as sr
12
+ from pydub import AudioSegment
13
+ from io import BytesIO
14
+
15
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
16
+
17
+ def record_audio(file_path, timeout=20, phrase_time_limit=None):
18
+ """
19
+ Simplified function to record audio from the microphone and save it as an MP3 file.
20
+
21
+ Args:
22
+ file_path (str): Path to save the recorded audio file.
23
+ timeout (int): Maximum time to wait for a phrase to start (in seconds).
24
+ phrase_time_lfimit (int): Maximum time for the phrase to be recorded (in seconds).
25
+ """
26
+ recognizer = sr.Recognizer()
27
+
28
+ try:
29
+ with sr.Microphone() as source:
30
+ logging.info("Adjusting for ambient noise...")
31
+ recognizer.adjust_for_ambient_noise(source, duration=1)
32
+ logging.info("Start speaking now...")
33
+
34
+ # Record the audio
35
+ audio_data = recognizer.listen(source, timeout=timeout, phrase_time_limit=phrase_time_limit)
36
+ logging.info("Recording complete.")
37
+
38
+ # Convert the recorded audio to an MP3 file
39
+ wav_data = audio_data.get_wav_data()
40
+ audio_segment = AudioSegment.from_wav(BytesIO(wav_data))
41
+ audio_segment.export(file_path, format="mp3", bitrate="128k")
42
+
43
+ logging.info(f"Audio saved to {file_path}")
44
+
45
+ except Exception as e:
46
+ logging.error(f"An error occurred: {e}")
47
+
48
+ audio_filepath="patient_voice_test_for_patient.mp3"
49
+ record_audio(file_path=audio_filepath)
50
+
51
+
52
+
53
+ # Setup Speech to text–STT–model for transcription
54
+ import os
55
+ from groq import Groq
56
+
57
+ GROQ_API_KEY=os.environ.get("GROQ_API_KEY")
58
+ stt_model="whisper-large-v3"
59
+
60
+ def transcribe_with_groq(stt_model, audio_filepath, GROQ_API_KEY):
61
+ client=Groq(api_key=GROQ_API_KEY)
62
+
63
+ audio_file=open(audio_filepath, "rb")
64
+ transcription=client.audio.transcriptions.create(
65
+ model=stt_model,
66
+ file=audio_file,
67
+ language="en"
68
+ )
69
+
70
+ return transcription.text
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+