sukanya15's picture
Create app.py
272f2fd verified
import streamlit as st
import speech_recognition as sr
from gtts import gTTS
import io
import base64
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
import torch
import tempfile
import os
import time
import warnings
warnings.filterwarnings("ignore")
st.set_page_config(
page_title="GenBridge - Voice AI Document Generator",
page_icon="🧠",
layout="wide"
)
# Initialize session state
if 'generated_content' not in st.session_state:
st.session_state.generated_content = ""
if 'audio_file' not in st.session_state:
st.session_state.audio_file = None
if 'user_input' not in st.session_state:
st.session_state.user_input = ""
@st.cache_resource
def load_granite_model():
"""Load IBM Granite model optimized for Hugging Face Spaces"""
try:
st.info("πŸ”„ Loading IBM Granite AI model...")
# Using IBM Granite 3B - optimized for Hugging Face Spaces
model_name = "ibm-granite/granite-3b-code-instruct"
# Use pipeline for easier handling in HF Spaces
generator = pipeline(
"text-generation",
model=model_name,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
device_map="auto" if torch.cuda.is_available() else None,
trust_remote_code=True,
max_new_tokens=512,
temperature=0.7,
do_sample=True,
repetition_penalty=1.1
)
st.success("βœ… IBM Granite model loaded successfully!")
return generator
except Exception as e:
st.warning(f"Granite model loading issue: {e}")
st.info("πŸ”„ Loading alternative model for demo...")
try:
# Fallback to a reliable model available on HF
generator = pipeline(
"text-generation",
model="microsoft/DialoGPT-medium",
max_new_tokens=300,
temperature=0.7,
do_sample=True
)
st.warning("⚠ Using demo model. Upgrade to Granite for production.")
return generator
except Exception as e2:
st.error(f"Model loading failed: {e2}")
return None
def speech_to_text_demo():
"""Demo speech-to-text (simulated for HF Spaces)"""
# Note: Microphone access is limited in HF Spaces
st.info("🎀 In a full deployment, this would capture your voice input!")
# For demo purposes, provide sample inputs
sample_inputs = {
"Resume": "I am a software engineer with 5 years experience in Python, web development, and machine learning. I have worked at tech startups and have skills in React, Django, and cloud platforms.",
"Cover Letter": "I am applying for a senior software developer position at your company. I have expertise in full-stack development and have led multiple successful projects.",
"Email": "I want to write a professional email to my manager requesting a meeting to discuss my career development and potential promotion opportunities.",
"Job Application": "I am interested in applying for the data scientist position. I have a Masters in Computer Science and 3 years experience in machine learning and data analysis."
}
return sample_inputs
def create_granite_prompt(user_input, document_type, tone):
"""Create optimized prompt for IBM Granite model"""
base_instruction = "You are a professional document writer. Create a complete, well-structured, and professional document."
prompts = {
"Resume": f"""{base_instruction}
Create a professional resume with {tone.lower()} tone based on this information:
{user_input}
Include these sections:
- Professional Summary
- Core Skills
- Professional Experience
- Education
- Additional Qualifications
Make it comprehensive and {tone.lower()}:
""",
"Cover Letter": f"""{base_instruction}
Write a {tone.lower()} cover letter based on:
{user_input}
Include:
- Professional greeting
- Strong opening paragraph
- Body highlighting qualifications
- Professional closing
- {tone.lower()} tone throughout
Cover Letter:
""",
"Email": f"""{base_instruction}
Compose a {tone.lower()} professional email based on:
{user_input}
Include:
- Clear subject line
- Professional greeting
- Well-structured body
- Appropriate closing
- {tone.lower()} tone
Email:
""",
"Job Application": f"""{base_instruction}
Create a {tone.lower()} job application letter based on:
{user_input}
Include:
- Formal business format
- Statement of interest
- Relevant qualifications
- Request for interview
- Professional closing
- {tone.lower()} tone
Job Application:
"""
}
return prompts.get(document_type, f"Create a {tone.lower()} {document_type} based on: {user_input}")
def generate_document_with_granite(user_input, document_type, tone):
"""Generate document using IBM Granite model"""
generator = load_granite_model()
if generator is None:
return create_professional_template(document_type, user_input, tone)
prompt = create_granite_prompt(user_input, document_type, tone)
try:
# Generate with the model
results = generator(prompt, max_new_tokens=400, num_return_sequences=1)
generated_text = results[0]['generated_text']
# Extract the generated content (remove the prompt)
if len(generated_text) > len(prompt):
generated_content = generated_text[len(prompt):].strip()
# Clean up and validate content
if generated_content and len(generated_content) > 100:
return generated_content
# Fallback to template if generation is insufficient
return create_professional_template(document_type, user_input, tone)
except Exception as e:
st.error(f"Generation error: {e}")
return create_professional_template(document_type, user_input, tone)
def create_professional_template(document_type, user_input, tone):
"""Create high-quality professional templates"""
templates = {
"Resume": f"""PROFESSIONAL RESUME
═══════════════════════════════════════════════════
CONTACT INFORMATION
[Your Full Name]
Email: [your.email@domain.com] | Phone: [Your Number]
LinkedIn: [LinkedIn Profile] | Location: [Your City, State]
PROFESSIONAL SUMMARY
{tone} and results-driven professional with proven expertise in the field. {user_input[:100]}... Demonstrated ability to deliver high-quality results while maintaining excellent professional standards.
CORE COMPETENCIES
β€’ Technical Skills & Expertise β€’ Leadership & Team Management
β€’ Strategic Planning & Execution β€’ Communication & Collaboration
β€’ Problem-Solving & Innovation β€’ Project Management
β€’ Quality Assurance & Best Practices β€’ Continuous Learning & Development
PROFESSIONAL EXPERIENCE
Senior Professional | [Company Name] | [Years]
β€’ Led cross-functional teams to achieve strategic objectives and deliver exceptional results
β€’ Developed and implemented innovative solutions that improved efficiency by 25%
β€’ Collaborated with stakeholders to identify requirements and exceed expectations
β€’ Mentored junior team members and contributed to professional development initiatives
Professional Specialist | [Previous Company] | [Years]
β€’ Executed complex projects while maintaining high standards of quality and accuracy
β€’ Analyzed requirements and delivered solutions that aligned with business objectives
β€’ Built strong professional relationships with clients and internal teams
β€’ Contributed to process improvements that enhanced overall productivity
EDUCATION & CERTIFICATIONS
[Degree] in [Field of Study] | [University Name] | [Year]
β€’ Relevant coursework: [Key subjects related to your field]
β€’ Professional certifications and continuing education
ADDITIONAL QUALIFICATIONS
β€’ Industry-specific knowledge and best practices
β€’ Strong analytical and technical capabilities
β€’ Excellent written and verbal communication skills
β€’ Proven track record of professional excellence
References available upon request
---
Generated based on: "{user_input}" """,
"Cover Letter": f"""[Your Name]
[Your Address]
[City, State ZIP Code]
[Your Email]
[Your Phone Number]
[Date]
[Hiring Manager's Name]
[Company Name]
[Company Address]
[City, State ZIP Code]
Dear Hiring Manager,
I am writing to express my strong interest in joining your organization. Your company's reputation for excellence and innovation aligns perfectly with my professional values and career aspirations.
Based on your requirements and my background: {user_input}
I am confident that my qualifications and {tone.lower()} approach to professional challenges make me an ideal candidate for this opportunity. Throughout my career, I have consistently demonstrated:
β€’ Strong technical and analytical capabilities
β€’ Excellent communication and interpersonal skills
β€’ Proven ability to work effectively in team environments
β€’ Commitment to delivering high-quality results
β€’ Adaptability and eagerness to embrace new challenges
I am particularly drawn to this opportunity because it would allow me to contribute meaningfully to your organization's continued success while further developing my professional expertise. My background has prepared me well for the responsibilities outlined in your position description.
I would welcome the opportunity to discuss how my experience and enthusiasm can benefit your team. Thank you for your time and consideration. I look forward to hearing from you soon.
{tone}ly yours,
[Your Signature]
[Your Printed Name]
---
Tailored based on: "{user_input}" """,
"Email": f"""Subject: Professional Inquiry - {user_input[:30]}...
Dear [Recipient Name],
I hope this message finds you well.
I am reaching out regarding: {user_input}
[MAIN MESSAGE CONTENT]
Thank you for taking the time to consider this matter. I have structured this communication to provide you with all relevant information while respecting your time.
Key points for your consideration:
β€’ Clear objective and professional context
β€’ Relevant background information and details
β€’ Specific next steps or requested actions
β€’ Timeline considerations if applicable
I am committed to maintaining the highest standards of professionalism in all communications and interactions. Please let me know if you require any additional information or clarification.
I appreciate your attention to this matter and look forward to your response at your earliest convenience.
Best professional regards,
[Your Name]
[Your Title/Position]
[Your Contact Information]
[Your Organization]
---
Email generated based on: "{user_input}" """,
"Job Application": f"""[Your Name]
[Your Address]
[City, State ZIP Code]
[Your Email] | [Your Phone]
[Date]
[Hiring Manager Name]
[Company Name]
[Company Address]
[City, State ZIP Code]
Dear Hiring Manager,
I am writing to submit my formal application for the position advertised by your esteemed organization. After careful review of your requirements, I am excited about the opportunity to contribute to your team's continued success.
Your position requirements align excellently with my background: {user_input}
I am confident that my qualifications, combined with my {tone.lower()} approach to professional responsibilities, position me as a strong candidate for this role. My career has been built on a foundation of:
CORE QUALIFICATIONS:
β€’ Comprehensive educational background and relevant training
β€’ Proven professional experience in related fields
β€’ Strong analytical and problem-solving capabilities
β€’ Excellent communication and collaboration skills
β€’ Demonstrated commitment to professional excellence
β€’ Track record of contributing to organizational success
PROFESSIONAL ATTRIBUTES:
β€’ Results-oriented mindset with attention to detail
β€’ Ability to work effectively both independently and in teams
β€’ Strong work ethic and reliability
β€’ Adaptability and eagerness to learn new skills
β€’ Commitment to maintaining high professional standards
I am particularly interested in this opportunity because it represents the perfect intersection of my professional expertise and career objectives. I am confident that I can make immediate and lasting contributions to your organization.
I would be honored to discuss my qualifications in greater detail during an interview. Thank you for your time and consideration of my application. I look forward to the opportunity to speak with you soon.
Respectfully submitted,
[Your Signature]
[Your Printed Name]
Enclosures: Resume, References
---
Application created based on: "{user_input}" """
}
return templates.get(document_type, f"Professional {document_type} created based on your requirements: {user_input}")
def text_to_speech(text):
"""Convert text to speech - optimized for HF Spaces"""
try:
# Limit text length for better performance in HF Spaces
if len(text) > 2000:
text = text[:2000] + "..."
tts = gTTS(text=text, lang='en', slow=False)
# Create temporary file
with tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as tmp_file:
tts.save(tmp_file.name)
return tmp_file.name
except Exception as e:
st.error(f"Audio generation error: {e}")
return None
def main():
# Custom CSS for better styling
st.markdown("""
<style>
.main-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 2rem;
border-radius: 10px;
text-align: center;
color: white;
margin-bottom: 2rem;
}
.feature-box {
background: #f8f9fa;
padding: 1rem;
border-radius: 8px;
border-left: 4px solid #667eea;
margin: 1rem 0;
}
</style>
""", unsafe_allow_html=True)
# Header
st.markdown("""
<div class="main-header">
<h1>🧠 GenBridge</h1>
<h3>Voice-Powered AI Document Generator</h3>
<p>Powered by IBM Granite AI | Built for Accessibility</p>
</div>
""", unsafe_allow_html=True)
# Sidebar
with st.sidebar:
st.header("βš™ Configuration")
document_type = st.selectbox(
"πŸ“‹ Document Type:",
["Resume", "Cover Letter", "Email", "Job Application"],
help="Choose the type of document to generate"
)
tone = st.selectbox(
"🎨 Writing Tone:",
["Professional", "Friendly", "Formal", "Assertive"],
help="Select the tone for your document"
)
st.markdown("---")
st.markdown("### 🎯 Key Features")
st.markdown("""
- 🎀 *Voice Input*: Natural speech interface
- 🧠 *IBM Granite AI*: Advanced text generation
- πŸ”Š *Audio Output*: Text-to-speech playback
- πŸ’Ύ *Downloads*: Text & audio files
- β™Ώ *Accessible*: Built for everyone
""")
st.markdown("---")
st.markdown("### πŸ‘₯ Target Users")
st.markdown("""
- Visually impaired individuals
- Elderly users
- Job seekers
- Non-native speakers
- Anyone preferring voice interaction
""")
st.markdown("---")
st.info("πŸ’‘ *Demo Note*: This is running on Hugging Face Spaces. Voice input is simulated with sample data.")
# Main content
col1, col2 = st.columns([1, 1])
with col1:
st.header("🎀 Input Method")
input_choice = st.radio(
"Choose input method:",
["🎀 Voice Input (Demo)", "⌨ Custom Text Input"]
)
if input_choice == "🎀 Voice Input (Demo)":
st.markdown("### πŸŽ™ Voice Input Simulation")
st.info("In production, this would capture live voice input!")
samples = speech_to_text_demo()
selected_sample = st.selectbox(
"Choose a sample voice input:",
list(samples.keys()),
help="These represent typical voice inputs"
)
if st.button("🎀 Simulate Voice Input", type="primary"):
st.session_state.user_input = samples[selected_sample]
st.success(f"βœ… Voice input captured!")
else:
custom_input = st.text_area(
"Enter your requirements:",
height=120,
placeholder="Describe your background, skills, experience, or what you want to include in your document...",
help="Provide detailed information for better document generation"
)
if custom_input:
st.session_state.user_input = custom_input
# Show current input
if st.session_state.user_input:
st.markdown("### πŸ“ Current Input:")
st.success(st.session_state.user_input)
with col2:
st.header("🧠 AI Generation")
if st.session_state.user_input:
if st.button("✨ Generate with IBM Granite AI", type="primary", use_container_width=True):
with st.spinner(f"πŸ€– Creating your {document_type.lower()} using IBM Granite..."):
# Add progress bar for better UX
progress_bar = st.progress(0)
progress_bar.progress(25)
generated_content = generate_document_with_granite(
st.session_state.user_input,
document_type,
tone
)
progress_bar.progress(75)
st.session_state.generated_content = generated_content
# Generate audio
audio_file = text_to_speech(generated_content)
st.session_state.audio_file = audio_file
progress_bar.progress(100)
st.success("βœ… Document generated successfully!")
else:
st.info("πŸ‘† Please provide input to generate your document")
# Results section
if st.session_state.generated_content:
st.markdown("---")
st.header("πŸ“„ Generated Document")
# Display tabs for better organization
tab1, tab2, tab3 = st.tabs(["πŸ“„ Document", "πŸ”Š Audio", "πŸ’Ύ Downloads"])
with tab1:
st.markdown("### Your Generated Document:")
st.text_area(
"Generated Content:",
value=st.session_state.generated_content,
height=400,
disabled=True
)
# Word and character count
word_count = len(st.session_state.generated_content.split())
char_count = len(st.session_state.generated_content)
st.caption(f"πŸ“Š Statistics: {word_count} words | {char_count} characters")
with tab2:
st.markdown("### πŸ”Š Audio Playback:")
if st.session_state.audio_file and os.path.exists(st.session_state.audio_file):
with open(st.session_state.audio_file, 'rb') as audio_file:
audio_bytes = audio_file.read()
st.audio(audio_bytes, format='audio/mp3')
st.success("🎡 Audio generated successfully!")
else:
st.warning("Audio generation in progress...")
with tab3:
st.markdown("### πŸ’Ύ Download Your Files:")
col1, col2 = st.columns(2)
with col1:
# Text download
filename_text = f"{document_type.lower().replace(' ', '')}{int(time.time())}.txt"
st.download_button(
label="πŸ“„ Download Text Document",
data=st.session_state.generated_content,
file_name=filename_text,
mime="text/plain",
use_container_width=True
)
with col2:
# Audio download
if st.session_state.audio_file and os.path.exists(st.session_state.audio_file):
with open(st.session_state.audio_file, 'rb') as audio_file:
audio_bytes = audio_file.read()
filename_audio = f"{document_type.lower().replace(' ', '')}{int(time.time())}.mp3"
st.download_button(
label="πŸ”Š Download Audio Version",
data=audio_bytes,
file_name=filename_audio,
mime="audio/mp3",
use_container_width=True
)
# Action buttons
col1, col2 = st.columns(2)
with col1:
if st.button("πŸ”„ Generate New Version", use_container_width=True):
st.session_state.generated_content = ""
st.session_state.audio_file = None
st.rerun()
with col2:
if st.button("🎀 New Input", use_container_width=True):
st.session_state.user_input = ""
st.session_state.generated_content = ""
st.session_state.audio_file = None
st.rerun()
# Footer
st.markdown("---")
st.markdown("""
<div style='text-align: center; background: #f8f9fa; padding: 1rem; border-radius: 8px;'>
<h4>🧠 GenBridge - Democratizing Document Creation</h4>
<p><strong>Powered by:</strong> IBM Granite AI β€’ Hugging Face β€’ Streamlit</p>
<p><strong>Built for:</strong> Accessibility β€’ Inclusion β€’ Professional Excellence</p>
<p style='color: #666; font-size: 0.9em;'>Empowering visually impaired, elderly, and all users to create professional documents through voice</p>
</div>
""", unsafe_allow_html=True)
if _name_ == "_main_":
Β Β Β Β main()