Spaces:
Configuration error
Configuration error
File size: 22,515 Bytes
272f2fd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 |
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()
|