import gradio as gr import os import re import numpy as np from openai import OpenAI import speech_recognition as sr from io import BytesIO import soundfile as sf from gtts import gTTS AVINASH_CONTEXT = { "personal_details": { "full_name": "Avinash Vikram Singh", "professional_identity": "Data Scientist and AI Engineer", "current_location": "Bengaluru, India", "contact": { "email": "avinashvs0052@gmail.com", "phone": "7052985015", "linkedin": "linkedin.com/in/avinash-vikram-singh-40b263233", "github": "github.com/AVINASH0052" } }, "education": { "degree": "BSc(Honours) Computer Science", "university": "Delhi University", "graduation_year": "2023", "gpa": "7.5" }, "professional_experience": { "most_recent_role": { "company": "ARD INFORMATION SYSTEMS", "position": "Data Scientist", "duration": "November 2023 - March 2025", "responsibilities": [ "Developed AI models for predictive analytics", "Implemented NLP solutions", "Worked with machine learning and deep learning models" ], "current_status": "Completed in March 2025" }, "previous_roles": [ { "company": "ARD INFORMATION SYSTEMS", "position": "Data Scientist Intern", "duration": "July 2023 - September 2023" }, { "company": "AMIGA INFORMATICS", "position": "Java Programmer Intern", "duration": "December 2021 - March 2022" } ] }, "technical_skills": { "core_competencies": [ "Retrieval-Augmented Generation (RAG)", "LLM Fine-tuning", "AI API Development", "Speech Recognition Systems" ], "programming": ["Python", "Java", "R", "C++"], "ml_frameworks": ["TensorFlow", "PyTorch", "Keras"], "data_tools": ["Pandas", "NumPy", "SQL", "Tableau"] }, "projects": [ { "name": "Flickr8K Image Captioning", "description": "Computer vision model generating captions for images", "tech_stack": ["TensorFlow", "OpenCV", "Keras"] }, { "name": "Movie Assistant Chatbot", "description": "LLM-powered conversational agent for movie recommendations", "tech_stack": ["Langchain", "Transformers"] } ], "current_focus": [ "Exploring new career opportunities in AI/ML", "Enhancing skills in LLM fine-tuning", "Contributing to open-source AI projects" ], "career_preferences": { "seeking": "Data Scientist/AI Engineer roles", "availability": "Immediate", "work_preference": "Hybrid/Remote with Bengaluru preference" }, "personal_interests": [ "Exploring new AI research papers", "Contributing to open-source projects", "Bengaluru's coffee culture", "Hiking and outdoor activities" ] } # Initialize NVIDIA client client = OpenAI( base_url="https://integrate.api.nvidia.com/v1", api_key=os.getenv("NVIDIA_API_KEY") ) def sanitize_text(text): """Clean text for proper formatting""" text = re.sub(r'[^.!?]*$', '', text) return re.sub(r'([$`"\\])', r'\\\1', text) def text_to_speech(text): """Convert text to audio using gTTS""" try: tts = gTTS(text=text, lang='en') audio_buffer = BytesIO() tts.write_to_fp(audio_buffer) audio_buffer.seek(0) return (16000, np.frombuffer(audio_buffer.read(), dtype=np.int16)) except Exception as e: print(f"TTS Error: {str(e)}") return None def audio_to_text(audio_data): """Convert audio input to text""" recognizer = sr.Recognizer() try: sample_rate, audio_array = audio_data audio_array = np.array(audio_array, dtype=np.float32) with BytesIO() as buffer: sf.write(buffer, audio_array, sample_rate, format='WAV') buffer.seek(0) with sr.AudioFile(buffer) as source: audio = recognizer.record(source) return recognizer.recognize_google(audio) except Exception as e: return f"Error in speech recognition: {str(e)}" def generate_response(prompt): """Generate response using NVIDIA API""" try: response = client.chat.completions.create( model="meta/llama3-70b-instruct", messages=[{ "role": "system", "content": f"""You are Avinash. Use this context: {AVINASH_CONTEXT} Speak responses naturally as if you're having a conversation. Response Guidelines: 1. Keep responses under 3 sentences 2. Maintain professional but friendly tone 3. Speak in first person 4. Never mention being an AI""" }, { "role": "user", "content": prompt }], temperature=0.7, max_tokens=150 ) response_text = response.choices[0].message.content.strip() if not response_text.endswith(('.','!','?')): response_text += '.' return sanitize_text(response_text) except Exception as e: return f"Sorry, I encountered an error: {str(e)}" def process_input(audio, text, chat_history): """Handle both voice and text input""" user_input = audio_to_text(audio) if audio is not None else text if not user_input.strip(): return chat_history, "", None, None response = generate_response(user_input) speech = text_to_speech(response) chat_history.append({"role": "user", "content": user_input}) chat_history.append({"role": "assistant", "content": response}) return chat_history, "", None, speech # Gradio Interface with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown("# Avinash AI Assistant 🤖") gr.Markdown("### Professional Voice-Enabled Assistant") with gr.Row(): with gr.Column(scale=2): chatbot = gr.Chatbot( label="Conversation History", bubble_full_width=False, type="messages" ) with gr.Row(): audio_input = gr.Audio( sources=["microphone"], type="numpy", label="Speak Here" ) text_input = gr.Textbox( label="Or Type Here", placeholder="Ask me about my professional background..." ) audio_output = gr.Audio(label="Response Audio", autoplay=True) clear_btn = gr.Button("Clear Conversation") with gr.Column(scale=1): gr.Markdown("### Professional Profile") gr.JSON(value=AVINASH_CONTEXT, label="Career Details") audio_input.change( process_input, [audio_input, text_input, chatbot], [chatbot, text_input, audio_input, audio_output] ) text_input.submit( process_input, [audio_input, text_input, chatbot], [chatbot, text_input, audio_input, audio_output] ) clear_btn.click( lambda: ([], "", None, None), None, [chatbot, text_input, audio_input, audio_output] ) if __name__ == "__main__": demo.launch()