File size: 2,555 Bytes
f7c08b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()