Bofandra commited on
Commit
7ff406f
·
verified ·
1 Parent(s): b0034fc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -27
app.py CHANGED
@@ -1,65 +1,67 @@
1
  import gradio as gr
2
- from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
3
- import json
 
4
 
5
- # Load words and languages from JSON files
6
  with open("top_500_quran_lemmas_fixed.json", encoding="utf-8") as f:
7
  word_list = json.load(f)
8
 
9
  with open("language_list.json", encoding="utf-8") as f:
10
  language_list = json.load(f)
11
 
12
- # Format dropdown options
13
  word_options = [f"{word['text']} ({word['english']})" for word in word_list]
14
  language_options = [f"{lang['name']} ({lang['code']})" for lang in language_list]
15
 
16
- # Load DeepSeek-V3 model
17
- model_id = "deepseek-ai/DeepSeek-V3"
18
- tokenizer = AutoTokenizer.from_pretrained(model_id)
19
- model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype="auto", device_map="auto")
20
- generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
 
 
21
 
22
- # Generate prompt
23
  def create_prompt(word_entry, language_code):
24
- prompt = f"""
25
  You are a friendly Quranic AI assistant.
26
 
27
- The word is: {word_entry['text']} ({word_entry['english']})
28
 
29
- Please provide the following in simple, easy-to-understand language, translated into {language_code}:
30
  1. Translation of the word.
31
- 2. Its root word and any related words (derivatives).
32
- 3. Where it appears in the Qur'an list the Surah and Ayah numbers.
33
- 4. Give an explanation of each appearance (based on context), in {language_code}.
34
 
35
- Avoid technical terms. Make it feel like a helpful teacher explaining to a student.
36
- """
37
- return prompt.strip()
38
 
39
- # Function to call the model
40
  def process(word_label, lang_label):
41
- # Extract selected word data
42
  selected_word = next((w for w in word_list if w['text'] in word_label), None)
43
  language_code = lang_label.split("(")[-1].strip(")")
44
-
45
  if not selected_word:
46
- return "Word not found in list."
47
 
48
  prompt = create_prompt(selected_word, language_code)
49
- result = generator(prompt, max_new_tokens=800, do_sample=True, temperature=0.7)[0]["generated_text"]
50
 
51
- return result.replace(prompt, "").strip()
 
 
 
 
 
 
52
 
53
  # Gradio UI
54
  with gr.Blocks() as demo:
55
- gr.Markdown("## 📖 Quran Word Explorer with DeepSeek-V3")
56
  with gr.Row():
57
  word_input = gr.Dropdown(choices=word_options, label="Select a Quran Word")
58
  lang_input = gr.Dropdown(choices=language_options, label="Select Language")
59
 
60
  output = gr.Textbox(label="DeepSeek-V3 Output", lines=20)
61
  run_btn = gr.Button("Get Info")
62
-
63
  run_btn.click(fn=process, inputs=[word_input, lang_input], outputs=output)
64
 
65
  demo.launch()
 
1
  import gradio as gr
2
+ import requests
3
+ import os
4
+ import requests
5
 
6
+ # Gradio-compatible data loading (as before)
7
  with open("top_500_quran_lemmas_fixed.json", encoding="utf-8") as f:
8
  word_list = json.load(f)
9
 
10
  with open("language_list.json", encoding="utf-8") as f:
11
  language_list = json.load(f)
12
 
 
13
  word_options = [f"{word['text']} ({word['english']})" for word in word_list]
14
  language_options = [f"{lang['name']} ({lang['code']})" for lang in language_list]
15
 
16
+ # Use Hugging Face Inference API
17
+ API_URL = "https://api-inference.huggingface.co/models/deepseek-ai/DeepSeek-V3"
18
+ HEADERS = {"Authorization": f"Bearer {os.getenv('HF_API_TOKEN')}"}
19
+
20
+ def query_hf_model(payload):
21
+ response = requests.post(API_URL, headers=HEADERS, json=payload)
22
+ return response.json()
23
 
 
24
  def create_prompt(word_entry, language_code):
25
+ return f"""
26
  You are a friendly Quranic AI assistant.
27
 
28
+ The word is: {word_entry['text']} ({word_entry['english']}).
29
 
30
+ Please provide the following in easy-to-understand {language_code}:
31
  1. Translation of the word.
32
+ 2. Its root word and any related derivatives.
33
+ 3. Where it appears in the Qur'an (surah and ayah).
34
+ 4. Simple explanation for each occurrence.
35
 
36
+ Avoid technical terms. Think like a teacher explaining clearly to students.
37
+ """.strip()
 
38
 
 
39
  def process(word_label, lang_label):
 
40
  selected_word = next((w for w in word_list if w['text'] in word_label), None)
41
  language_code = lang_label.split("(")[-1].strip(")")
 
42
  if not selected_word:
43
+ return "Word not found."
44
 
45
  prompt = create_prompt(selected_word, language_code)
46
+ output = query_hf_model({"inputs": prompt})
47
 
48
+ # Some formatting safety
49
+ if isinstance(output, dict) and "error" in output:
50
+ return f"Error: {output['error']}"
51
+ elif isinstance(output, list):
52
+ return output[0].get("generated_text", "No response.")
53
+ else:
54
+ return str(output)
55
 
56
  # Gradio UI
57
  with gr.Blocks() as demo:
58
+ gr.Markdown("## 📖 Quran Word Explorer using DeepSeek-V3 (HF Inference API)")
59
  with gr.Row():
60
  word_input = gr.Dropdown(choices=word_options, label="Select a Quran Word")
61
  lang_input = gr.Dropdown(choices=language_options, label="Select Language")
62
 
63
  output = gr.Textbox(label="DeepSeek-V3 Output", lines=20)
64
  run_btn = gr.Button("Get Info")
 
65
  run_btn.click(fn=process, inputs=[word_input, lang_input], outputs=output)
66
 
67
  demo.launch()