Spaces:
Build error
Build error
Update app.py
Browse files8 unmodified lines91011121314154 unmodified lines2021222324252621 unmodified lines48495051525354137 unmodified lines192193194195196197198199200201202203204205206207254 unmodified lines462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517100 unmodified lines6186196206216226236248 unmodified linesfrom md2pdf.core import md2pdffrom dotenv import load_dotenvfrom datetime import datetimeimport backoffimport requestsfrom requests.exceptions import RequestExceptionfrom typing import Optional, Dict, Any4 unmodified linesMAX_FILE_SIZE = 41943040 # 40MBFILE_TOO_LARGE_MESSAGE = "File too large. Maximum size is 40MB."# Load environment variablesload_dotenv()# Initialize session states21 unmodified linesLLM_MODEL = "deepseek-r1-distill-llama-70b"TRANSCRIPTION_MODEL = "distil-whisper-large-v3-en"# Configure exponential backoff for API retriesMAX_RETRIES = 5INITIAL_WAIT = 0.5MAX_WAIT = 30137 unmodified linesmarkdown_content += self.get_markdown_content(content, level + 1)return markdown_content# Add backoff decorator for retrying transcription@backoff.on_exception(backoff.expo,(RequestException, GroqAPIError),max_tries=MAX_RETRIES,factor=INITIAL_WAIT,max_value=MAX_WAIT,jitter=backoff.full_jitter,on_backoff=lambda details: st.info(f"Retrying transcription... (Attempt {details['tries']}/{MAX_RETRIES})"))def transcribe_audio_with_groq(audio_data) -> str:"""Transcribe audio file using Groq's transcription API with retry capability254 unmodified linesst.title("π§ββοΈ ScribeWizard")st.markdown("Transform speech into highly structured notes with AI magic")# Sidebar for configurationwith st.sidebar:st.header("Configuration")# Improved API key handlingapi_key_input = st.text_input("Groq API Key",value=st.session_state.api_key,type="password",help="Enter your Groq API key. Get one at https://console.groq.com/keys")# Only update if changedif api_key_input != st.session_state.api_key:st.session_state.api_key = api_key_input# Reinitialize client with new keyst.session_state.groq_client = initialize_groq_client(api_key_input)if st.session_state.groq_client:st.success("β API key validated!")# Initialize client if not done alreadyif st.session_state.api_key and not st.session_state.groq_client:st.session_state.groq_client = initialize_groq_client(st.session_state.api_key)# API key instructionswith st.expander("How to get a Groq API key"):st.markdown("""1. Visit [Groq Cloud Console](https://console.groq.com/)2. Sign up or log in to your account3. Navigate to API Keys in the sidebar4. Click "Create API Key" and give it a name5. Copy the generated key (you won't see it again!)**Security tip**: For production use, store your API key as an environment variable:```bashexport GROQ_API_KEY="your-api-key-here"```""")st.markdown("---")st.info("Using DeepSeek-R1-Distill-Llama-70B model for note generation and Distil Whisper for transcription")# Check if API key is valid before proceedingif not st.session_state.api_key:st.warning("β οΈ Please enter your Groq API key in the sidebar to use ScribeWizard")st.stop()if not st.session_state.groq_client:st.error("β Failed to initialize Groq client. Please check your API key.")st.stop()# Input methods tabs100 unmodified linesif "Audio file too large" in str(e) or "exceeds" in str(e):st.info("π‘ Try trimming your audio file or uploading a shorter segment.")elif "API key" in str(e) or "Authentication" in str(e):st.info("π‘ Check that your Groq API key is correct and has access to the transcription API.")elif "Rate limit" in str(e):st.info("π‘ You've hit Groq's rate limits. Please wait a few minutes before trying again.")8 unmodified lines910111213144 unmodified lines1920212223242521 unmodified lines47484950515253137 unmodified lines191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229254 unmodified lines484485486487488489490491492493494495496497498499500501502503504100 unmodified lines6056066076086096106118 unmodified linesfrom md2pdf.core import md2pdffrom dotenv import load_dotenvfrom datetime import datetimeimport requestsfrom requests.exceptions import RequestExceptionfrom typing import Optional, Dict, Any4 unmodified linesMAX_FILE_SIZE = 41943040 # 40MBFILE_TOO_LARGE_MESSAGE = "File too large. Maximum size is 40MB."# Load environment variables - will also load from Hugging Face secretsload_dotenv()# Initialize session states21 unmodified linesLLM_MODEL = "deepseek-r1-distill-llama-70b"TRANSCRIPTION_MODEL = "distil-whisper-large-v3-en"# Configure retry parameters without backoff libraryMAX_RETRIES = 5INITIAL_WAIT = 0.5MAX_WAIT = 30137 unmodified linesmarkdown_content += self.get_markdown_content(content, level + 1)return markdown_content# Manual implementation of retry logic (replacing backoff library)def retry_with_exponential_backoff(max_tries=MAX_RETRIES, initial_wait=INITIAL_WAIT, max_wait=MAX_WAIT):"""Custom retry decorator with exponential backoff"""def decorator(func):def wrapper(*args, **kwargs):wait = initial_waittries = 0while tries < max_tries:try:return func(*args, **kwargs)except (RequestException, GroqAPIError) as e:tries += 1if tries == max_tries:raise# Calculate next wait time with exponential backoffwait = min(wait * 2, max_wait)# Add some jitter (Β±20%)jitter = wait * 0.4 * (np.random.random() - 0.5)wait_with_jitter = wait + jitter# Inform user of retry attemptst.info(f"Retrying transcription... (Attempt {tries}/{max_tries})")time.sleep(wait_with_jitter)return wrapperreturn decorator@retry_with_exponential_backoff()def transcribe_audio_with_groq(audio_data) -> str:"""Transcribe audio file using Groq's transcription API with retry capability254 unmodified linesst.title("π§ββοΈ ScribeWizard")st.markdown("Transform speech into highly structured notes with AI magic")# Initialize API key from environment (Hugging Face secrets)if st.session_state.api_key and not st.session_state.groq_client:st.session_state.groq_client = initialize_groq_client(st.session_state.api_key)# Display model info in the sidebarwith st.sidebar:st.info("Using DeepSeek-R1-Distill-Llama-70B model for note generation and Distil Whisper for transcription")# Check if API key is valid before proceedingif not st.session_state.api_key:st.error("β No API key found. Please set the GROQ_API_KEY secret in your Hugging Face Space settings.")st.stop()if not st.session_state.groq_client:st.error("β Failed to initialize Groq client. Please check your API key secret in Hugging Face Space settings.")st.stop()# Input methods tabs100 unmodified linesif "Audio file too large" in str(e) or "exceeds" in str(e):st.info("π‘ Try trimming your audio file or uploading a shorter segment.")elif "API key" in str(e) or "Authentication" in str(e):st.info("π‘ Check that your Groq API key is correct in your Hugging Face Space settings.")elif "Rate limit" in str(e):st.info("π‘ You've hit Groq's rate limits. Please wait a few minutes before trying again.")
app.py+43-56