Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
|
| 2 |
import os
|
| 3 |
import gradio as gr
|
| 4 |
import pdfplumber
|
|
@@ -19,49 +18,22 @@ LANGUAGE_CODES = {
|
|
| 19 |
"Arabic": "ar"
|
| 20 |
}
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
PROMPT_TEMPLATES = {
|
| 23 |
-
"English": ""
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
{text}
|
| 29 |
-
""",
|
| 30 |
-
"Turkish": """
|
| 31 |
-
Lütfen aşağıdaki metni {style} tarzında ve yaklaşık {char_limit} karakter olacak şekilde özetle.
|
| 32 |
-
Ardından 5 anahtar kelime ver.
|
| 33 |
-
|
| 34 |
-
METİN:
|
| 35 |
-
{text}
|
| 36 |
-
""",
|
| 37 |
-
"French": """
|
| 38 |
-
Veuillez résumer le texte suivant dans un style {style}, en environ {char_limit} caractères.
|
| 39 |
-
Fournissez ensuite 5 mots-clés pertinents.
|
| 40 |
-
|
| 41 |
-
TEXTE :
|
| 42 |
-
{text}
|
| 43 |
-
""",
|
| 44 |
-
"German": """
|
| 45 |
-
Fassen Sie den folgenden Text im {style}-Stil mit etwa {char_limit} Zeichen zusammen.
|
| 46 |
-
Geben Sie anschließend 5 relevante Schlüsselwörter an.
|
| 47 |
-
|
| 48 |
-
TEXT:
|
| 49 |
-
{text}
|
| 50 |
-
""",
|
| 51 |
-
"Spanish": """
|
| 52 |
-
Resume el siguiente texto en un estilo {style} y con un límite de aproximadamente {char_limit} caracteres.
|
| 53 |
-
Luego proporciona 5 palabras clave relevantes.
|
| 54 |
-
|
| 55 |
-
TEXTO:
|
| 56 |
-
{text}
|
| 57 |
-
""",
|
| 58 |
-
"Arabic": """
|
| 59 |
-
الرجاء تلخيص النص التالي بأسلوب {style}، على ألا يتجاوز {char_limit} حرفًا.
|
| 60 |
-
ثم قدم 5 كلمات مفتاحية مهمة.
|
| 61 |
-
|
| 62 |
-
النص:
|
| 63 |
-
{text}
|
| 64 |
-
"""
|
| 65 |
}
|
| 66 |
|
| 67 |
QUIZ_PROMPTS = {
|
|
@@ -70,7 +42,7 @@ QUIZ_PROMPTS = {
|
|
| 70 |
"French": "Sur la base du texte ci-dessous, générez 2 questions à choix multiples (4 options A à D) :\n\n{text}",
|
| 71 |
"German": "Erstelle basierend auf dem folgenden Text 2 Multiple-Choice-Fragen (mit jeweils 4 Optionen A–D):\n\n{text}",
|
| 72 |
"Spanish": "Con base en el siguiente texto, genera 2 preguntas de opción múltiple (cada una con 4 opciones A–D):\n\n{text}",
|
| 73 |
-
"Arabic": "قم بإنشاء سؤالين اختيار من متعدد استنادًا إلى النص أدناه، مع أربعة خيارات لكل سؤال (
|
| 74 |
}
|
| 75 |
|
| 76 |
def extract_text_from_pdf(file):
|
|
@@ -81,98 +53,81 @@ def extract_text_from_pdf(file):
|
|
| 81 |
page_text = page.extract_text()
|
| 82 |
if page_text:
|
| 83 |
text += page_text + "\n"
|
| 84 |
-
|
| 85 |
-
return None, "The PDF appears to contain no extractable text."
|
| 86 |
-
return text.strip(), None
|
| 87 |
except Exception as e:
|
| 88 |
-
return None,
|
| 89 |
|
| 90 |
def translate_text(text, target_lang):
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
|
| 103 |
def generate_summary_and_keywords(text, summary_lang, style, char_limit):
|
| 104 |
-
|
| 105 |
-
prompt =
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
return response.choices[0].message.content
|
| 114 |
-
except Exception as e:
|
| 115 |
-
return f"OpenAI error: {str(e)}"
|
| 116 |
|
| 117 |
def generate_quiz(summary_text, summary_lang):
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
def process_input(text_input, pdf_file, summary_lang, style, char_limit, quiz_check):
|
| 131 |
if not char_limit.isdigit():
|
| 132 |
return "⚠️ Please enter a numeric character limit."
|
| 133 |
-
|
| 134 |
-
error = None
|
| 135 |
-
if
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
if
|
| 140 |
-
return f"⚠️ {error}"
|
| 141 |
-
if not text:
|
| 142 |
-
return "⚠️ No text provided."
|
| 143 |
-
|
| 144 |
-
detected_lang = detect(text)
|
| 145 |
-
target_lang_code = LANGUAGE_CODES.get(summary_lang, "en")
|
| 146 |
-
if detected_lang != target_lang_code:
|
| 147 |
text = translate_text(text, summary_lang)
|
| 148 |
|
| 149 |
summary = generate_summary_and_keywords(text, summary_lang, style, char_limit)
|
| 150 |
-
if
|
| 151 |
quiz = generate_quiz(summary, summary_lang)
|
| 152 |
-
return summary + "\n\n
|
| 153 |
-
|
| 154 |
-
return summary
|
| 155 |
|
| 156 |
with gr.Blocks() as demo:
|
| 157 |
gr.Markdown("## 🌍 Multilingual Summarizer + Quiz Generator")
|
|
|
|
|
|
|
| 158 |
|
| 159 |
with gr.Row():
|
| 160 |
-
summary_lang = gr.Dropdown(
|
| 161 |
-
summary_style = gr.Dropdown(
|
| 162 |
char_limit = gr.Textbox(label="Character Limit", value="300")
|
| 163 |
|
| 164 |
-
|
| 165 |
|
| 166 |
with gr.Row():
|
| 167 |
-
text_input = gr.Textbox(lines=
|
| 168 |
pdf_file = gr.File(label="Or Upload PDF")
|
| 169 |
|
| 170 |
-
output = gr.Textbox(label="Output", lines=
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
run_btn.click(fn=process_input,
|
| 175 |
-
inputs=[text_input, pdf_file, summary_lang, summary_style, char_limit, quiz_check],
|
| 176 |
-
outputs=[output])
|
| 177 |
|
| 178 |
-
demo.launch()
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import pdfplumber
|
|
|
|
| 18 |
"Arabic": "ar"
|
| 19 |
}
|
| 20 |
|
| 21 |
+
QUIZ_TITLES = {
|
| 22 |
+
"English": "### 📘 Quiz Questions:",
|
| 23 |
+
"Turkish": "### 📘 Test Soruları:",
|
| 24 |
+
"French": "### 📘 Questions à Choix Multiples :",
|
| 25 |
+
"German": "### 📘 Quizfragen:",
|
| 26 |
+
"Spanish": "### 📘 Preguntas del cuestionario:",
|
| 27 |
+
"Arabic": "### 📘 أسئلة الاختيار من متعدد:"
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
PROMPT_TEMPLATES = {
|
| 31 |
+
"English": "Please summarize the following text in a {style} style and keep it within approximately {char_limit} characters.\nThen provide 5 relevant keywords.\n\nTEXT:\n{text}",
|
| 32 |
+
"Turkish": "Lütfen aşağıdaki metni {style} tarzında ve yaklaşık {char_limit} karakter olacak şekilde özetle.\nArdından 5 anahtar kelime ver.\n\nMETİN:\n{text}",
|
| 33 |
+
"French": "Veuillez résumer le texte suivant dans un style {style}, en environ {char_limit} caractères.\nFournissez ensuite 5 mots-clés pertinents.\n\nTEXTE :\n{text}",
|
| 34 |
+
"German": "Fassen Sie den folgenden Text im {style}-Stil mit etwa {char_limit} Zeichen zusammen.\nGeben Sie anschließend 5 relevante Schlüsselwörter an.\n\nTEXT:\n{text}",
|
| 35 |
+
"Spanish": "Resume el siguiente texto en un estilo {style} y con un límite de aproximadamente {char_limit} caracteres.\nLuego proporciona 5 palabras clave relevantes.\n\nTEXTO:\n{text}",
|
| 36 |
+
"Arabic": "الرجاء تلخيص النص التالي بأسلوب {style}، على ألا يتجاوز {char_limit} حرفًا.\nثم قدم 5 كلمات مفتاحية مهمة.\n\nالنص:\n{text}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
}
|
| 38 |
|
| 39 |
QUIZ_PROMPTS = {
|
|
|
|
| 42 |
"French": "Sur la base du texte ci-dessous, générez 2 questions à choix multiples (4 options A à D) :\n\n{text}",
|
| 43 |
"German": "Erstelle basierend auf dem folgenden Text 2 Multiple-Choice-Fragen (mit jeweils 4 Optionen A–D):\n\n{text}",
|
| 44 |
"Spanish": "Con base en el siguiente texto, genera 2 preguntas de opción múltiple (cada una con 4 opciones A–D):\n\n{text}",
|
| 45 |
+
"Arabic": "قم بإنشاء سؤالين اختيار من متعدد استنادًا إلى النص أدناه، مع أربعة خيارات لكل سؤال (أ، ب، ج، د):\n\n{text}"
|
| 46 |
}
|
| 47 |
|
| 48 |
def extract_text_from_pdf(file):
|
|
|
|
| 53 |
page_text = page.extract_text()
|
| 54 |
if page_text:
|
| 55 |
text += page_text + "\n"
|
| 56 |
+
return text.strip() if text.strip() else None, None
|
|
|
|
|
|
|
| 57 |
except Exception as e:
|
| 58 |
+
return None, str(e)
|
| 59 |
|
| 60 |
def translate_text(text, target_lang):
|
| 61 |
+
prompt = f"Translate the following text into {target_lang}:\n\n{text}"
|
| 62 |
+
response = client.chat.completions.create(
|
| 63 |
+
model="gpt-3.5-turbo",
|
| 64 |
+
messages=[{"role": "user", "content": prompt}],
|
| 65 |
+
temperature=0.3,
|
| 66 |
+
max_tokens=1000
|
| 67 |
+
)
|
| 68 |
+
return response.choices[0].message.content
|
| 69 |
+
|
| 70 |
+
def replace_arabic_choices(quiz_text):
|
| 71 |
+
return quiz_text.replace("A)", "أ.").replace("B)", "ب.").replace("C)", "ج.").replace("D)", "د.")
|
| 72 |
|
| 73 |
def generate_summary_and_keywords(text, summary_lang, style, char_limit):
|
| 74 |
+
template = PROMPT_TEMPLATES[summary_lang]
|
| 75 |
+
prompt = template.format(style=style, char_limit=char_limit, text=text[:2000])
|
| 76 |
+
response = client.chat.completions.create(
|
| 77 |
+
model="gpt-3.5-turbo",
|
| 78 |
+
messages=[{"role": "user", "content": prompt}],
|
| 79 |
+
temperature=0.7,
|
| 80 |
+
max_tokens=700
|
| 81 |
+
)
|
| 82 |
+
return response.choices[0].message.content
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
def generate_quiz(summary_text, summary_lang):
|
| 85 |
+
prompt = QUIZ_PROMPTS[summary_lang].format(text=summary_text)
|
| 86 |
+
response = client.chat.completions.create(
|
| 87 |
+
model="gpt-3.5-turbo",
|
| 88 |
+
messages=[{"role": "user", "content": prompt}],
|
| 89 |
+
temperature=0.7,
|
| 90 |
+
max_tokens=500
|
| 91 |
+
)
|
| 92 |
+
result = response.choices[0].message.content
|
| 93 |
+
return replace_arabic_choices(result) if summary_lang == "Arabic" else result
|
| 94 |
+
|
| 95 |
+
def process(text_input, pdf_file, summary_lang, style, char_limit, make_quiz):
|
|
|
|
|
|
|
| 96 |
if not char_limit.isdigit():
|
| 97 |
return "⚠️ Please enter a numeric character limit."
|
| 98 |
+
|
| 99 |
+
text, error = extract_text_from_pdf(pdf_file) if pdf_file else (text_input.strip(), None)
|
| 100 |
+
if error or not text:
|
| 101 |
+
return f"⚠️ Error: {error or 'No valid text provided.'}"
|
| 102 |
+
|
| 103 |
+
detected = detect(text)
|
| 104 |
+
if detected != LANGUAGE_CODES[summary_lang]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
text = translate_text(text, summary_lang)
|
| 106 |
|
| 107 |
summary = generate_summary_and_keywords(text, summary_lang, style, char_limit)
|
| 108 |
+
if make_quiz:
|
| 109 |
quiz = generate_quiz(summary, summary_lang)
|
| 110 |
+
return summary + "\n\n" + QUIZ_TITLES[summary_lang] + "\n" + quiz
|
| 111 |
+
return summary
|
|
|
|
| 112 |
|
| 113 |
with gr.Blocks() as demo:
|
| 114 |
gr.Markdown("## 🌍 Multilingual Summarizer + Quiz Generator")
|
| 115 |
+
with gr.Accordion("📘 View README / Usage Guide", open=False):
|
| 116 |
+
gr.Markdown("This app creates summaries and quizzes from PDFs or text, in multiple languages.")
|
| 117 |
|
| 118 |
with gr.Row():
|
| 119 |
+
summary_lang = gr.Dropdown(LANGUAGES, value="English", label="Summary Language")
|
| 120 |
+
summary_style = gr.Dropdown(SUMMARY_STYLES, value="Academic", label="Summary Style")
|
| 121 |
char_limit = gr.Textbox(label="Character Limit", value="300")
|
| 122 |
|
| 123 |
+
make_quiz = gr.Checkbox(label="Generate Quiz Questions", value=True)
|
| 124 |
|
| 125 |
with gr.Row():
|
| 126 |
+
text_input = gr.Textbox(lines=6, label="Text Input")
|
| 127 |
pdf_file = gr.File(label="Or Upload PDF")
|
| 128 |
|
| 129 |
+
output = gr.Textbox(label="Output", lines=20)
|
| 130 |
+
btn = gr.Button("Summarize")
|
| 131 |
+
btn.click(process, [text_input, pdf_file, summary_lang, summary_style, char_limit, make_quiz], output)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
+
demo.launch()
|