|
|
|
|
|
import logging |
|
import requests |
|
import os |
|
import json |
|
|
|
|
|
|
|
logging.basicConfig( |
|
level=logging.INFO, |
|
format='%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s', |
|
datefmt='%Y-%m-%d %H:%M:%S' |
|
) |
|
|
|
logger = logging.getLogger(__name__) |
|
|
|
import requests |
|
import json |
|
import os |
|
|
|
|
|
|
|
HF_TOKEN = os.getenv("HF_TOKEN") |
|
|
|
if not HF_TOKEN: |
|
raise ValueError("Hugging Face API token not found. Please set the HF_TOKEN environment variable.") |
|
|
|
|
|
|
|
API_URL = "https://router.huggingface.co/v1" |
|
MODEL_ID = "deepseek-ai/DeepSeek-V3-0324:fireworks-ai" |
|
|
|
def generate_crossword_clue(word: str, context: str) -> str: |
|
""" |
|
Generates a crossword-style clue for a given word using the Hugging Face API router. |
|
|
|
Args: |
|
word (str): The word for which to generate a clue. |
|
context (str): The context sentence or phrase to help define the word. |
|
|
|
Returns: |
|
str: The generated crossword clue. |
|
""" |
|
headers = { |
|
"Authorization": f"Bearer {HF_TOKEN}", |
|
"Content-Type": "application/json" |
|
} |
|
|
|
|
|
messages = [ |
|
{ |
|
"role": "system", |
|
"content": f"You are a crossword puzzle clue generator. Given a word and a context, your task is to generate a single, concise, creative, and fair crossword puzzle clue. The clue should be for the word '{word}'." |
|
}, |
|
{ |
|
"role": "user", |
|
"content": f"The word is '{word}'. The context is: '{context}'." |
|
} |
|
] |
|
|
|
|
|
|
|
payload = { |
|
"model": MODEL_ID, |
|
"messages": messages, |
|
|
|
"temperature": 0.7 |
|
} |
|
|
|
try: |
|
response = requests.post(f"{API_URL}/chat/completions", headers=headers, data=json.dumps(payload)) |
|
response.raise_for_status() |
|
|
|
result = response.json() |
|
|
|
|
|
if "choices" in result and len(result["choices"]) > 0: |
|
final_clue = result["choices"][0]["message"]["content"].strip() |
|
return final_clue |
|
else: |
|
return "No clue generated." |
|
|
|
except requests.exceptions.RequestException as e: |
|
print(f"An error occurred: {e}") |
|
|
|
if 'response' in locals(): |
|
print(f"API Response: {response.text}") |
|
return "Error generating clue." |
|
|
|
|
|
if __name__ == "__main__": |
|
target_word = "cricket" |
|
target_context = "yesterday india won test series against england" |
|
|
|
clue = generate_crossword_clue(target_word, target_context) |
|
|
|
print(f"Word: {target_word}") |
|
print(f"Context: {target_context}") |
|
print(f"Generated Clue: {clue}") |
|
|
|
|
|
print("\n--- Another example ---") |
|
target_word_2 = "Shuttle" |
|
target_context_2 = "Man landed on the moon" |
|
clue_2 = generate_crossword_clue(target_word_2, target_context_2) |
|
print(f"Word: {target_word_2}") |
|
print(f"Context: {target_context_2}") |
|
print(f"Generated Clue: {clue_2}") |
|
|
|
|