Turbiling commited on
Commit
545111b
Β·
verified Β·
1 Parent(s): 1cb7ffa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -45
app.py CHANGED
@@ -6,16 +6,18 @@ from docx import Document
6
  from docx.shared import Pt
7
  import gradio as gr
8
 
9
- # Load GROQ API key from Hugging Face secret environment
10
  client = Groq(api_key=os.environ["GROQ_API_KEY"])
11
 
12
- # Memory to store TOC and chapters
13
  toc_memory = {"toc": ""}
14
  chapters_memory = {}
15
 
16
- # πŸ”§ Clean markdown, emojis, bullets
17
  def clean_formatting(text):
18
- text = re.sub(r"[*#β€’β—β†’βœ…πŸ”ΉπŸ”ΈπŸ“˜πŸ“–πŸ“‘πŸ“€πŸ“₯β¬‡οΈπŸŽ‰>]+", "", text)
 
 
19
  text = re.sub(r"\s{2,}", " ", text)
20
  return text.strip()
21
 
@@ -39,12 +41,8 @@ Do NOT write the chapter content. Only return the Table of Contents clearly orga
39
  toc_memory["toc"] = toc
40
  return toc
41
 
42
- # πŸ“– Generate Chapter
43
  def generate_chapter(topic, chapter_number):
44
- toc = toc_memory["toc"]
45
- if toc == "":
46
- return "⚠️ Please generate the Table of Contents first."
47
-
48
  prompt = f"""
49
  Using the following Table of Contents for a beginner-level textbook on **{topic}**, generate the complete content of **Chapter {chapter_number}**.
50
 
@@ -65,15 +63,27 @@ Do NOT include system messages like β€œHere is the content of...” Just return
65
  messages=[{"role": "user", "content": prompt}],
66
  temperature=0.7
67
  )
68
- chapter = response.choices[0].message.content.strip()
69
- chapters_memory[chapter_number] = chapter
70
- return chapter
71
 
72
- # πŸ“„ Generate Word document
 
 
 
 
 
 
 
 
 
 
 
 
73
  def download_textbook(topic, grade):
74
  doc = Document()
75
 
76
- # === Set Default Font ===
77
  style = doc.styles['Normal']
78
  font = style.font
79
  font.name = 'Times New Roman'
@@ -93,19 +103,19 @@ def download_textbook(topic, grade):
93
  size_map = {1: 16, 2: 14}
94
  return add_paragraph(text.strip(), size=size_map.get(level, 12), bold=True)
95
 
96
- # === Cover Page ===
97
  add_heading(topic.upper(), level=1)
98
  add_paragraph(f"Author: Najaf Ali Sharqi")
99
  add_paragraph(f"Grade: {grade}")
100
  add_paragraph(f"Date of Publication: {datetime.now().strftime('%B %d, %Y')}")
101
  doc.add_page_break()
102
 
103
- # === Table of Contents ===
104
  add_heading("Table of Contents", level=1)
105
  add_paragraph(toc_memory["toc"])
106
  doc.add_page_break()
107
 
108
- # === Chapters ===
109
  for num in sorted(chapters_memory.keys()):
110
  add_heading(f"Chapter {num}", level=1)
111
  cleaned = clean_formatting(chapters_memory[num])
@@ -118,50 +128,39 @@ def download_textbook(topic, grade):
118
  add_paragraph(line.strip())
119
  doc.add_page_break()
120
 
121
- # Save file
122
  file_path = "/tmp/Generated_Textbook.docx"
123
  doc.save(file_path)
124
  return file_path
125
-
126
- # 🌐 Gradio Interface
127
  with gr.Blocks() as demo:
128
  gr.Markdown("## πŸ“˜ AI Textbook Generator App")
129
  gr.Markdown("""
130
- Welcome to the AI Textbook Generator developed by **Najaf Ali Sharqi**.
131
-
132
- ### πŸ‘‰ Instructions:
133
- 1. Enter the **textbook topic** and **grade level**
134
- 2. Click **Generate Table of Contents**
135
- 3. Tap a chapter button to generate that chapter
136
- 4. After generating all chapters, click **Download Word File**
 
137
  """)
138
 
139
  with gr.Row():
140
- topic_input = gr.Textbox(label="Textbook Topic", placeholder="e.g., Basics of AI")
141
- grade_input = gr.Textbox(label="Grade Level", placeholder="e.g., 6")
142
-
143
- toc_btn = gr.Button("πŸ”Ή Generate Table of Contents")
144
- toc_output = gr.Textbox(label="πŸ“‘ Table of Contents", lines=10)
145
 
 
 
146
  toc_btn.click(fn=generate_toc, inputs=topic_input, outputs=toc_output)
147
 
148
- gr.Markdown("### πŸ“₯ Generate Chapter Content")
 
 
149
 
150
- chapter_display = gr.Textbox(label="πŸ“– Chapter Content", lines=30)
151
-
152
- with gr.Row():
153
- for i in range(1, 8):
154
- btn = gr.Button(f"Chapter {i}")
155
- btn.click(fn=generate_chapter, inputs=[topic_input, gr.Textbox(value=str(i), visible=False)], outputs=chapter_display)
156
-
157
- gr.Markdown("### πŸ“€ Export Full Textbook")
158
-
159
- download_btn = gr.Button("⬇️ Download Word File")
160
  download_file = gr.File()
161
-
162
  download_btn.click(fn=download_textbook, inputs=[topic_input, grade_input], outputs=download_file)
163
 
164
  gr.Markdown("---")
165
- gr.Markdown("App developed by **Najaf Ali Sharqi** | Powered by **Groq + Gradio**")
166
 
167
  demo.launch()
 
6
  from docx.shared import Pt
7
  import gradio as gr
8
 
9
+ # πŸ” Load Groq API Key from Hugging Face Secrets
10
  client = Groq(api_key=os.environ["GROQ_API_KEY"])
11
 
12
+ # Memory to store TOC and Chapters
13
  toc_memory = {"toc": ""}
14
  chapters_memory = {}
15
 
16
+ # βœ… Clean Markdown, Symbols, Emojis
17
  def clean_formatting(text):
18
+ text = re.sub(r"\*\*(.*?)\*\*", r"\1", text) # Remove **bold**
19
+ text = re.sub(r"\*(.*?)\*", r"\1", text) # Remove *italic*
20
+ text = re.sub(r"[#β€’β—β†’βœ…πŸ”ΉπŸ”ΈπŸ“˜πŸ“–πŸ“‘πŸ“€πŸ“₯β¬‡οΈπŸŽ‰>]", "", text)
21
  text = re.sub(r"\s{2,}", " ", text)
22
  return text.strip()
23
 
 
41
  toc_memory["toc"] = toc
42
  return toc
43
 
44
+ # πŸ“˜ Generate One Chapter
45
  def generate_chapter(topic, chapter_number):
 
 
 
 
46
  prompt = f"""
47
  Using the following Table of Contents for a beginner-level textbook on **{topic}**, generate the complete content of **Chapter {chapter_number}**.
48
 
 
63
  messages=[{"role": "user", "content": prompt}],
64
  temperature=0.7
65
  )
66
+ content = response.choices[0].message.content.strip()
67
+ chapters_memory[chapter_number] = content
68
+ return content
69
 
70
+ # πŸ” Generate All Chapters (1 to 7)
71
+ def generate_all_chapters(topic):
72
+ toc = toc_memory["toc"]
73
+ if toc == "":
74
+ return "⚠️ Please generate the Table of Contents first."
75
+
76
+ summary = ""
77
+ for i in range(1, 8):
78
+ content = generate_chapter(topic, str(i))
79
+ summary += f"\n\n--- Chapter {i} Generated ---\n\n"
80
+ return summary + "\n\nβœ… All chapters generated. Now download the book."
81
+
82
+ # πŸ“„ Download Final Book
83
  def download_textbook(topic, grade):
84
  doc = Document()
85
 
86
+ # Font settings
87
  style = doc.styles['Normal']
88
  font = style.font
89
  font.name = 'Times New Roman'
 
103
  size_map = {1: 16, 2: 14}
104
  return add_paragraph(text.strip(), size=size_map.get(level, 12), bold=True)
105
 
106
+ # Cover Page
107
  add_heading(topic.upper(), level=1)
108
  add_paragraph(f"Author: Najaf Ali Sharqi")
109
  add_paragraph(f"Grade: {grade}")
110
  add_paragraph(f"Date of Publication: {datetime.now().strftime('%B %d, %Y')}")
111
  doc.add_page_break()
112
 
113
+ # Table of Contents
114
  add_heading("Table of Contents", level=1)
115
  add_paragraph(toc_memory["toc"])
116
  doc.add_page_break()
117
 
118
+ # Chapters
119
  for num in sorted(chapters_memory.keys()):
120
  add_heading(f"Chapter {num}", level=1)
121
  cleaned = clean_formatting(chapters_memory[num])
 
128
  add_paragraph(line.strip())
129
  doc.add_page_break()
130
 
 
131
  file_path = "/tmp/Generated_Textbook.docx"
132
  doc.save(file_path)
133
  return file_path
 
 
134
  with gr.Blocks() as demo:
135
  gr.Markdown("## πŸ“˜ AI Textbook Generator App")
136
  gr.Markdown("""
137
+ Developed by **Najaf Ali Sharqi**
138
+ Generate a complete beginner-level textbook with SLOs, examples, MCQs, glossary, and export it in MS Word.
139
+
140
+ ### πŸ› οΈ Steps:
141
+ 1. Enter your textbook **topic** and **grade level**
142
+ 2. Click **Generate TOC**
143
+ 3. Then click **Generate All Chapters**
144
+ 4. Finally, click **Download Word File**
145
  """)
146
 
147
  with gr.Row():
148
+ topic_input = gr.Textbox(label="πŸ“š Textbook Topic", placeholder="e.g., Basics of AI")
149
+ grade_input = gr.Textbox(label="πŸŽ“ Grade Level", placeholder="e.g., Grade 6")
 
 
 
150
 
151
+ toc_btn = gr.Button("πŸ“‘ Generate Table of Contents")
152
+ toc_output = gr.Textbox(label="πŸ“˜ Table of Contents", lines=10)
153
  toc_btn.click(fn=generate_toc, inputs=topic_input, outputs=toc_output)
154
 
155
+ generate_all_btn = gr.Button("🧠 Generate All Chapters (1–7)")
156
+ status = gr.Textbox(label="πŸ“– Generation Log", lines=10)
157
+ generate_all_btn.click(fn=generate_all_chapters, inputs=topic_input, outputs=status)
158
 
159
+ download_btn = gr.Button("⬇️ Download Textbook (.docx)")
 
 
 
 
 
 
 
 
 
160
  download_file = gr.File()
 
161
  download_btn.click(fn=download_textbook, inputs=[topic_input, grade_input], outputs=download_file)
162
 
163
  gr.Markdown("---")
164
+ gr.Markdown("Made with ❀️ by **Najaf Ali Sharqi** | Powered by **Groq + Gradio**")
165
 
166
  demo.launch()