Spaces:
Runtime error
Runtime error
Oviya commited on
Commit Β·
c32259d
1
Parent(s): 48fc519
add findingword
Browse filesFiles changed (2)
- Findingword.pyAdded+251
- verification.py+2
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251import openaifrom flask import Flask, jsonify, request, send_from_directory, send_file, Blueprintimport osfrom google.cloud import texttospeechfrom flask_cors import CORSimport io # NEW: for streaming S3 bytes in HF/AWS mode
# Optional (only used in AWS mode)try: import boto3 from botocore.exceptions import BotoCoreError, ClientErrorexcept Exception: # Not required for local; will be imported dynamically in AWS mode boto3 = None BotoCoreError = ClientError = Exception
app = Flask(__name__)CORS(app)
# --- NEW: Blueprint ---finding_bp = Blueprint("findingword", __name__)
# Directories for video, audio, and transcriptsVIDEO_FOLDER = 'static/videos'AUDIO_FOLDER = 'static/audio' # Ensure this folder existsTRANSCRIPT_FOLDER = 'static/transcripts'
# Set your OpenAI API key (left as-is per your request)# openai.api_key = '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'openai.api_key = os.getenv("OPENAI_API_KEY", "")# Initialize Google Cloud TTS client (local mode)client = texttospeech.TextToSpeechClient()
# Ensure required folders exist (used in local mode)os.makedirs(AUDIO_FOLDER, exist_ok=True)
# ---------------------- audio-mode helpers (UNCHANGED) ----------------------def _is_aws_mode() -> bool: """ Switch to AWS Polly + S3 on Hugging Face / prod. Local stays on Google TTS + disk. """ if os.getenv("USE_AWS_AUDIO", "0") == "1": return True if os.getenv("SPACE_ID"): # set on Hugging Face Spaces return True if os.getenv("ENV", "dev").lower() == "prod": return True return False
def _sanitize_filename(word: str) -> str: # Keep your current style but ensure safe S3 key/filename return word.strip().replace(" ", "_").replace(".", "").lower()
# ---------------------------------------------------------------------
@finding_bp.route('/generate-vocabulary', methods=['GET'])def get_vocabulary_word_from_openai(): #prompt = "Pick a random vocabulary word suitable for children and provide its meaning. Do not repeat words from previous responses. Format: 'Word: [word]. Meaning: [meaning].'" prompt = "Pick a simple vocabulary word suitable for children (ages 6β8) and provide its meaning in very easy English. Do not repeat words from previous responses. Format: 'Word: [word]. Meaning: [meaning].'"
try: response = openai.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": prompt}, ] )
result = response.choices[0].message.content.strip() print(f"Full Response: {result}")
if "Word:" in result and "Meaning:" in result: parts = result.split("Meaning:") word = parts[0].replace("Word:", "").strip() # β
Ensure the extracted word does not contain trailing dots or special characters word = word.rstrip('.') meaning = parts[1].strip()
# Generate the sentence sentence = generate_sentence(word, meaning)
# Generate audio file for the vocabulary word audio_file_path_or_name = generate_audio(word) # may be local path or just filename in AWS mode
# Convert for frontend exactly as before audio_url = f"/static/audio/{os.path.basename(audio_file_path_or_name)}"
return jsonify({ "word": word, "meaning": meaning, "sentence": sentence, "audio_file_path": audio_url # Returning the same field as before })
else: return jsonify({"response": result, "message": "Meaning not provided in the expected format"})
except Exception as e: return jsonify({"error": str(e)})
def generate_sentence(word, meaning): prompt = f"Create a sentence using the word '{word}' that fully demonstrates its meaning: {meaning}"
response = openai.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": prompt}, ] )
sentence = response.choices[0].message.content.strip() return sentence
def generate_audio(word): """ Local (default): Google TTS β write MP3 to ./static/audio/<word>.mp3 β return full path (unchanged). Hugging Face / AWS mode: Polly β upload to S3 (findingword/<word>.mp3) β return just the filename, and let /static/audio/<filename> stream from S3 (see route below). """ sanitized_word = _sanitize_filename(word) filename = f"{sanitized_word}.mp3"
if _is_aws_mode(): # ---- AWS Polly + S3 path (no local write) ---- if boto3 is None: raise RuntimeError("boto3 is required in AWS audio mode but not available")
region = os.getenv("AWS_DEFAULT_REGION", "eu-north-1") bucket = os.getenv("S3_BUCKET_NAME") if not bucket: raise RuntimeError("S3_BUCKET_NAME is not set")
polly = boto3.client("polly", region_name=region) s3 = boto3.client("s3", region_name=region)
try: resp = polly.synthesize_speech( Text=word, OutputFormat="mp3", VoiceId=os.getenv("POLLY_VOICE_ID", "Joanna"), Engine=os.getenv("POLLY_ENGINE", "standard"), LanguageCode="en-US", ) stream = resp.get("AudioStream") if not stream: raise RuntimeError("Polly returned no AudioStream") audio_bytes = stream.read() except (BotoCoreError, ClientError, Exception) as e: raise RuntimeError(f"Polly TTS failed: {e}")
key = f"findingword/{filename}" try: s3.put_object(Bucket=bucket, Key=key, Body=audio_bytes, ContentType="audio/mpeg") except (BotoCoreError, ClientError, Exception) as e: raise RuntimeError(f"S3 upload failed: {e}")
# Return only the filename; /static/audio/<filename> will proxy from S3 return filename
# ---- Local Google TTS path (unchanged) ---- os.makedirs(AUDIO_FOLDER, exist_ok=True) audio_file_path = os.path.join(AUDIO_FOLDER, filename)
if not os.path.exists(audio_file_path): synthesis_input = texttospeech.SynthesisInput(text=word) voice = texttospeech.VoiceSelectionParams( language_code="en-US", ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL ) audio_config = texttospeech.AudioConfig(audio_encoding=texttospeech.AudioEncoding.MP3)
response = client.synthesize_speech(input=synthesis_input, voice=voice, audio_config=audio_config)
with open(audio_file_path, "wb") as out: out.write(response.audio_content)
print(f"β
Audio saved: {audio_file_path}")
return audio_file_path
@finding_bp.route('/validate-word', methods=['POST'])def validate_word(): try: data = request.get_json() print("π₯ Received data for validation:", data) # Log input data
if not data or 'user_input' not in data or 'correct_word' not in data: print("β Missing user_input or correct_word in request data.") return jsonify({"error": "Invalid request, missing fields"}), 400
user_input = data.get('user_input', '').strip() correct_word = data.get('correct_word', '').strip()
print(f"π Validating: User Input - '{user_input}' | Correct Word - '{correct_word}'")
if user_input.lower() == correct_word.lower(): print("β
Validation Success") return jsonify({"status": "success", "message": "Correct! You typed the word correctly."}) else: print("β Validation Failed") return jsonify({"status": "failure", "message": f"Incorrect. The correct word was '{correct_word}'."})
except Exception as e: print("β Exception in validate-word API:", str(e)) return jsonify({"error": str(e)}), 500
@finding_bp.route('/static/audio/<filename>')def serve_audio(filename): """ Local: serve from disk (unchanged). AWS mode (HF): fetch the object from S3 and stream it (no local storage). """ if _is_aws_mode(): if boto3 is None: return jsonify({"error": "boto3 missing in AWS mode"}), 500
region = os.getenv("AWS_DEFAULT_REGION", "eu-north-1") bucket = os.getenv("S3_BUCKET_NAME") if not bucket: return jsonify({"error": "S3_BUCKET_NAME not set"}), 500
s3 = boto3.client("s3", region_name=region) key = f"findingword/{filename}"
try: obj = s3.get_object(Bucket=bucket, Key=key) data = obj["Body"].read() # Stream as an MP3 without saving locally return send_file( io.BytesIO(data), mimetype="audio/mpeg", download_name=filename, as_attachment=False ) except (BotoCoreError, ClientError, Exception) as e: return jsonify({"error": f"S3 fetch failed: {str(e)}"}), 404
# Local: serve file from disk as before return send_from_directory(AUDIO_FOLDER, filename)
# Run the Flask server (local dev): keep URLs unchanged by registering with empty prefixif __name__ == '__main__': app.register_blueprint(finding_bp, url_prefix='') # Local: /generate-vocabulary, /validate-word, /static/audio/... app.run(host='0.0.0.0', port=5005, debug=True)308 unmodified lines309310311312313314315316317318319308 unmodified linesfrom reading import reading_bpfrom writting import writting_bp # match the exact file name on Linuxfrom vocabularyBuilder import vocab_bpapp.register_blueprint(movie_bp, url_prefix="/media")app.register_blueprint(questions_bp, url_prefix="/media")app.register_blueprint(reading_bp, url_prefix="/media")app.register_blueprint(writting_bp, url_prefix="/media")app.register_blueprint(vocab_bp, url_prefix="/media")# app.register_blueprint(questions_bp, url_prefix="/media") # <-- add this# ------------------------------------------------------------------------------# Local run (Gunicorn will import `verification:app` on Spaces)308 unmodified lines309310311312313314315316317318319320321308 unmodified linesfrom reading import reading_bpfrom writting import writting_bp # match the exact file name on Linuxfrom vocabularyBuilder import vocab_bpfrom Findingword import finding_bpapp.register_blueprint(movie_bp, url_prefix="/media")app.register_blueprint(questions_bp, url_prefix="/media")app.register_blueprint(reading_bp, url_prefix="/media")app.register_blueprint(writting_bp, url_prefix="/media")app.register_blueprint(vocab_bp, url_prefix="/media")app.register_blueprint(finding_bp, url_prefix="/media")# app.register_blueprint(questions_bp, url_prefix="/media") # <-- add this# ------------------------------------------------------------------------------# Local run (Gunicorn will import `verification:app` on Spaces)
Findingword.pyAdded+251
verification.py+2