Spaces:
Build error
Build error
| import os | |
| import json | |
| import tempfile | |
| import gradio as gr | |
| import requests | |
| from docx import Document | |
| # Retrieve the API token from the environment | |
| api_token = os.getenv("API_TOKEN") | |
| if not api_token: | |
| raise ValueError("API token not found. Please set the API_TOKEN environment variable.") | |
| # Define the API URL and headers for the Hugging Face Inference API | |
| API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3" | |
| HEADERS = {"Authorization": f"Bearer {api_token}"} | |
| def analyze_figure_of_speech(verse): | |
| """ | |
| Send the Bible verse to the LLM for analysis of figures of speech. | |
| The prompt instructs the model to analyze the verse and return a JSON array. | |
| """ | |
| if not verse.strip(): | |
| return "Please enter a Bible verse." | |
| prompt = f"""<s>[INST] You are JR-Sacred Syntax, an expert biblical scholar specializing in Bible analysis. | |
| Analyze the following Bible verse to identify any figures of speech (e.g., Metaphor, Synecdoche, Hyperbole, Simile, Paradox). | |
| Return your answer as a JSON array where each element includes: | |
| - "verses": the Bible verse reference, | |
| - "figure": the type of figure of speech, | |
| - "phrase": the exact phrase from the verse, | |
| - "explanation": a brief explanation in biblical context. | |
| Bible Verse: "{verse}" | |
| [/INST] Figures:</s>""" | |
| payload = {"inputs": prompt} | |
| try: | |
| response = requests.post(API_URL, headers=HEADERS, json=payload) | |
| response.raise_for_status() | |
| result = response.json() | |
| if isinstance(result, list) and len(result) > 0: | |
| generated_text = result[0].get("generated_text", "") | |
| marker = "Figures:" | |
| if marker in generated_text: | |
| generated_text = generated_text.split(marker, 1)[1].strip() | |
| try: | |
| output_json = json.loads(generated_text) | |
| return json.dumps(output_json, indent=2) | |
| except json.JSONDecodeError: | |
| return generated_text | |
| else: | |
| return "Error: Unexpected response format." | |
| except requests.exceptions.RequestException as e: | |
| return f"API Error: {e}" | |
| def generate_docx(analysis_json): | |
| """ | |
| Parse the analysis JSON and create a formatted DOCX file. | |
| Each entry is added with headings and bullet points. | |
| Returns the file path of the generated DOCX. | |
| """ | |
| try: | |
| analysis_data = json.loads(analysis_json) | |
| except json.JSONDecodeError: | |
| # If not valid JSON, treat the entire text as one entry. | |
| analysis_data = [{"verses": "", "figure": "", "phrase": "", "explanation": analysis_json}] | |
| document = Document() | |
| document.add_heading("Bible Figures of Speech Analysis", level=1) | |
| for item in analysis_data: | |
| verses = item.get("verses", "Unknown Verse") | |
| figure = item.get("figure", "Unknown Figure") | |
| phrase = item.get("phrase", "Unknown Phrase") | |
| explanation = item.get("explanation", "No explanation provided.") | |
| document.add_heading(f"Verse: {verses}", level=2) | |
| document.add_paragraph(f"Figure: {figure}", style='List Bullet') | |
| document.add_paragraph(f"Phrase: {phrase}", style='List Bullet') | |
| document.add_paragraph(f"Explanation: {explanation}", style='List Bullet') | |
| document.add_paragraph("") # Add an empty paragraph for spacing | |
| temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".docx") | |
| document.save(temp_file.name) | |
| return temp_file.name | |
| def process_and_download(verse): | |
| """ | |
| Process the Bible verse: | |
| 1. Get the analysis result as JSON. | |
| 2. Generate a formatted DOCX file from the analysis. | |
| Returns both the JSON result (as text) and the DOCX file path. | |
| """ | |
| analysis = analyze_figure_of_speech(verse) | |
| docx_file = generate_docx(analysis) | |
| return analysis, docx_file | |
| # Create the Gradio Interface with two outputs: JSON analysis and a DOCX download. | |
| iface = gr.Interface( | |
| fn=process_and_download, | |
| inputs=gr.Textbox(label="Enter Bible Verse", | |
| placeholder="E.g., 'I am the vine, you are the branches' - John 15:5", | |
| lines=3), | |
| outputs=[ | |
| gr.Textbox(label="Figures of Speech Analysis (JSON)"), | |
| gr.File(label="Download Analysis (.docx)") | |
| ], | |
| title="JR-Sacred Syntax: Bible Figures of Speech Detector", | |
| description="Enter a Bible verse to detect and analyze figures of speech with detailed biblical explanations. Download the formatted analysis as a DOCX file." | |
| ) | |
| if __name__ == "__main__": | |
| iface.launch() | |