Turbiling commited on
Commit
3309174
Β·
verified Β·
1 Parent(s): 16b7567

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -26
app.py CHANGED
@@ -13,13 +13,13 @@ client = Groq(api_key=os.environ["GROQ_API_KEY"])
13
  book_data = {
14
  "title": "",
15
  "grade": "",
16
- "slos": [],
17
  "toc": [],
18
  "chapters": {},
19
  "preface": ""
20
  }
21
 
22
  # Clean formatting
 
23
  def clean_formatting(text):
24
  text = re.sub(r"\*\*(.*?)\*\*", r"\1", text)
25
  text = re.sub(r"\*(.*?)\*", r"\1", text)
@@ -28,20 +28,17 @@ def clean_formatting(text):
28
  return text.strip()
29
 
30
  # Generate TOC and Preface
31
- def generate_book_intro(title, grade, slos_input):
 
32
  book_data["title"] = title.strip()
33
  book_data["grade"] = grade.strip()
34
- book_data["slos"] = [line.strip() for line in slos_input.split('\n') if line.strip()]
35
 
36
  prompt = f"""
37
  You are a professional educational author.
38
  Write the following sections for a textbook titled: "{title}" for Grade {grade}:
39
 
40
  1. A formal preface aligned with APA 7th Edition style.
41
- 2. A Table of Contents with 6 chapters. Title each chapter clearly according to common educational structure or inferred from the following SLOs:
42
-
43
- SLOs:
44
- {slos_input}
45
 
46
  Do NOT write any chapter content. Only return:
47
  - Preface
@@ -62,13 +59,12 @@ def generate_book_intro(title, grade, slos_input):
62
  return f"Preface:\n\n{book_data['preface']}\n\nTable of Contents:\n\n" + "\n".join(book_data["toc"])
63
 
64
  # Generate chapter by number
 
65
  def generate_chapter(ch_num):
66
  if ch_num in book_data["chapters"]:
67
  return book_data["chapters"][ch_num]
68
 
69
  ch_title = next((line for line in book_data["toc"] if line.startswith(str(ch_num))), f"Chapter {ch_num}")
70
- slos = book_data["slos"][(ch_num - 1)*5: ch_num*5] # 5 SLOs per chapter
71
- slo_text = "\n".join(f"- {slo}" for slo in slos)
72
 
73
  prompt = f"""
74
  You are an expert textbook writer. Write Chapter {ch_num} for the book titled "{book_data['title']}" for Grade {book_data['grade']}.
@@ -77,11 +73,11 @@ def generate_chapter(ch_num):
77
 
78
  Include the following sections:
79
  - Introduction
80
- - 5 to 7 Student Learning Outcomes (SLOs):\n{slo_text}
81
  - Detailed content aligned with each SLO
82
- - Examples / Case Studies
83
- - Chapter Summary
84
- - 10 Review Questions or Activities (no answers)
85
 
86
  Follow APA 7th edition tone. Do NOT use any asterisks, markdown, emojis, or non-printable characters.
87
  """
@@ -97,6 +93,7 @@ def generate_chapter(ch_num):
97
  return chapter
98
 
99
  # Export full textbook to Word
 
100
  def export_book():
101
  doc = Document()
102
  style = doc.styles['Normal']
@@ -133,17 +130,11 @@ def export_book():
133
  add_paragraph(line)
134
  doc.add_page_break()
135
 
136
- # SLOs
137
- add_heading("Student Learning Outcomes (SLOs)", level=1)
138
- for i, slo in enumerate(book_data['slos'], 1):
139
- add_paragraph(f"{i}. {slo}")
140
- doc.add_page_break()
141
-
142
  # Chapters
143
  for num in sorted(book_data['chapters'].keys()):
144
  add_heading(f"{book_data['toc'][num-1]}", level=1)
145
  for line in book_data['chapters'][num].split('\n'):
146
- if any(keyword in line.lower() for keyword in ["introduction", "summary", "examples", "review", "student learning outcomes"]):
147
  add_heading(line, level=2)
148
  else:
149
  add_paragraph(line)
@@ -155,23 +146,22 @@ def export_book():
155
 
156
  # Gradio Interface
157
  with gr.Blocks() as demo:
158
- gr.Markdown("## πŸ“˜ AI Textbook Generator – Step-by-Step (APA Style)")
159
 
160
  with gr.Row():
161
  title = gr.Textbox(label="Subject Title")
162
  grade = gr.Textbox(label="Grade Level")
163
 
164
- slos = gr.Textbox(label="Paste SLOs (One per Line)", lines=10)
165
  generate_structure = gr.Button("🧠 Generate TOC + Preface")
166
  structure_output = gr.Textbox(label="Generated Preface and TOC", lines=15)
167
 
168
- generate_structure.click(fn=generate_book_intro, inputs=[title, grade, slos], outputs=structure_output)
169
 
170
  gr.Markdown("### πŸ“₯ Generate Chapters One by One")
171
  chapter_output = gr.Textbox(label="Generated Chapter Content", lines=25)
172
 
173
  with gr.Row():
174
- for i in range(1, 7):
175
  gr.Button(f"Generate Chapter {i}").click(fn=generate_chapter, inputs=gr.Number(value=i, visible=False), outputs=chapter_output)
176
 
177
  gr.Markdown("### πŸ’Ύ Download Complete Textbook")
@@ -180,7 +170,6 @@ with gr.Blocks() as demo:
180
 
181
  download_btn.click(fn=export_book, outputs=download_file)
182
 
183
- gr.Markdown("Developed by **Najaf Ali Sharqi** | Powered by **Groq + Gradio**")
184
 
185
- # πŸ‘‡ This makes it work on Colab/Hugging Face
186
  demo.launch(share=True)
 
13
  book_data = {
14
  "title": "",
15
  "grade": "",
 
16
  "toc": [],
17
  "chapters": {},
18
  "preface": ""
19
  }
20
 
21
  # Clean formatting
22
+
23
  def clean_formatting(text):
24
  text = re.sub(r"\*\*(.*?)\*\*", r"\1", text)
25
  text = re.sub(r"\*(.*?)\*", r"\1", text)
 
28
  return text.strip()
29
 
30
  # Generate TOC and Preface
31
+
32
+ def generate_book_intro(title, grade):
33
  book_data["title"] = title.strip()
34
  book_data["grade"] = grade.strip()
 
35
 
36
  prompt = f"""
37
  You are a professional educational author.
38
  Write the following sections for a textbook titled: "{title}" for Grade {grade}:
39
 
40
  1. A formal preface aligned with APA 7th Edition style.
41
+ 2. A Table of Contents with 7 chapters. Title each chapter clearly according to a logical structure for beginners.
 
 
 
42
 
43
  Do NOT write any chapter content. Only return:
44
  - Preface
 
59
  return f"Preface:\n\n{book_data['preface']}\n\nTable of Contents:\n\n" + "\n".join(book_data["toc"])
60
 
61
  # Generate chapter by number
62
+
63
  def generate_chapter(ch_num):
64
  if ch_num in book_data["chapters"]:
65
  return book_data["chapters"][ch_num]
66
 
67
  ch_title = next((line for line in book_data["toc"] if line.startswith(str(ch_num))), f"Chapter {ch_num}")
 
 
68
 
69
  prompt = f"""
70
  You are an expert textbook writer. Write Chapter {ch_num} for the book titled "{book_data['title']}" for Grade {book_data['grade']}.
 
73
 
74
  Include the following sections:
75
  - Introduction
76
+ - Student Learning Outcomes (5 to 7)
77
  - Detailed content aligned with each SLO
78
+ - Activities or Case Studies
79
+ - Assessment (15 MCQs with no answers)
80
+ - Glossary
81
 
82
  Follow APA 7th edition tone. Do NOT use any asterisks, markdown, emojis, or non-printable characters.
83
  """
 
93
  return chapter
94
 
95
  # Export full textbook to Word
96
+
97
  def export_book():
98
  doc = Document()
99
  style = doc.styles['Normal']
 
130
  add_paragraph(line)
131
  doc.add_page_break()
132
 
 
 
 
 
 
 
133
  # Chapters
134
  for num in sorted(book_data['chapters'].keys()):
135
  add_heading(f"{book_data['toc'][num-1]}", level=1)
136
  for line in book_data['chapters'][num].split('\n'):
137
+ if any(keyword in line.lower() for keyword in ["introduction", "summary", "examples", "review", "student learning outcomes", "assessment", "glossary", "activities"]):
138
  add_heading(line, level=2)
139
  else:
140
  add_paragraph(line)
 
146
 
147
  # Gradio Interface
148
  with gr.Blocks() as demo:
149
+ gr.Markdown("## πŸ“˜ AI Textbook Generator – APA Style | Developed by Najaf Ali Sharqi")
150
 
151
  with gr.Row():
152
  title = gr.Textbox(label="Subject Title")
153
  grade = gr.Textbox(label="Grade Level")
154
 
 
155
  generate_structure = gr.Button("🧠 Generate TOC + Preface")
156
  structure_output = gr.Textbox(label="Generated Preface and TOC", lines=15)
157
 
158
+ generate_structure.click(fn=generate_book_intro, inputs=[title, grade], outputs=structure_output)
159
 
160
  gr.Markdown("### πŸ“₯ Generate Chapters One by One")
161
  chapter_output = gr.Textbox(label="Generated Chapter Content", lines=25)
162
 
163
  with gr.Row():
164
+ for i in range(1, 8):
165
  gr.Button(f"Generate Chapter {i}").click(fn=generate_chapter, inputs=gr.Number(value=i, visible=False), outputs=chapter_output)
166
 
167
  gr.Markdown("### πŸ’Ύ Download Complete Textbook")
 
170
 
171
  download_btn.click(fn=export_book, outputs=download_file)
172
 
173
+ gr.Markdown("Created with ❀️ using Gradio + Groq | All content APA 7th aligned")
174
 
 
175
  demo.launch(share=True)