Spaces:
Running
Running
import gradio as gr | |
import requests | |
import os | |
# Hugging Face API Key from environment variables | |
HF_API_KEY = os.getenv('HF_API_KEY') | |
# Function to fetch word details from Hugging Face API | |
def fetch_word_details(word): | |
if not word: | |
return {"error": "Word is required"} | |
api_url = "https://api-inference.huggingface.co/models/gauravkai/Llama-3-8B-English-Dictionary" | |
prompt = f"Provide the following details for the word '{word}': \n - Definition\n - Syllables\n - Phonetic Transcription\n - Example Sentence\n - Phonemes\n Please return the result in a structured JSON" | |
headers = { | |
"Authorization": f"Bearer {HF_API_KEY}", | |
"Content-Type": "application/json", | |
} | |
# Sending the request to Hugging Face API | |
response = requests.post(api_url, headers=headers, json={"inputs": prompt}) | |
if response.status_code == 200: | |
result = response.json() | |
word_details = parse_details(result[0]['generated_text']) | |
return word_details | |
else: | |
return {"error": "Failed to fetch data"} | |
def parse_details(text): | |
# Extract the JSON part of the string | |
json_start = text.find("{") | |
json_end = text.rfind("}") | |
if json_start != -1 and json_end != -1: | |
json_string = text[json_start:json_end+1] | |
# Fix unquoted values for JSON compatibility | |
json_string = json_string.replace(r'\/', "/") | |
try: | |
return eval(json_string) # Safely parse the string to a dictionary | |
except Exception as e: | |
return {"error": f"Failed to parse JSON: {str(e)}"} | |
return {"error": "No valid JSON found."} | |
# Gradio Interface | |
def word_details_interface(word): | |
details = fetch_word_details(word) | |
if "error" in details: | |
return details["error"] | |
return f""" | |
<h3>Word Details</h3> | |
<b>Word:</b> {details.get('word', 'N/A')}<br> | |
<b>Definition:</b> {details.get('definition', 'N/A')}<br> | |
<b>Syllables:</b> {details.get('syllables', 'N/A')}<br> | |
<b>Phonetic Transcription:</b> {details.get('phonetic_transcription', 'N/A')}<br> | |
<b>Example Sentence:</b> {details.get('example_sentence', 'N/A')}<br> | |
<b>Phonemes:</b> {details.get('phonemes', 'N/A')}<br> | |
""" | |
# Gradio UI Setup | |
interface = gr.Interface( | |
fn=word_details_interface, | |
inputs=gr.Textbox(label="Enter a Word"), | |
outputs=gr.HTML(), | |
live=True, | |
) | |
if __name__ == "__main__": | |
interface.launch() | |