Turbiling commited on
Commit
7632479
Β·
verified Β·
1 Parent(s): e2ec734

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -119
app.py CHANGED
@@ -1,125 +1,90 @@
1
- import os
2
  from datetime import datetime
3
  from groq import Groq
4
  from docx import Document
5
  from docx.shared import Pt
6
- import gradio as gr
7
 
8
- # Load GROQ API Key from environment
9
- client = Groq(api_key=os.environ["GROQ_API_KEY"])
10
-
11
- # Memory to store TOC and chapters
12
- toc_memory = {"toc": ""}
13
- chapters_memory = {}
14
-
15
- # Generate TOC
16
- def generate_toc(topic):
17
- prompt = f"""
18
- You are an expert curriculum developer. Create a detailed Table of Contents for an absolute beginner-level textbook on the topic: "{topic}".
19
-
20
- The textbook should include 5 to 7 chapters. Each chapter must have:
21
- - A clear title
22
- - 5 to 6 subheadings (titles only)
23
-
24
- Do NOT write the chapter content. Only return the Table of Contents clearly organized.
25
- """
26
- response = client.chat.completions.create(
27
- model="llama3-70b-8192",
28
- messages=[{"role": "user", "content": prompt}],
29
- temperature=0.7
30
- )
31
- toc = response.choices[0].message.content.strip()
32
- toc_memory["toc"] = toc
33
- return toc
34
-
35
- # Generate Chapter
36
- def generate_chapter(topic, chapter_number):
37
- toc = toc_memory["toc"]
38
- if toc == "":
39
- return "⚠️ Please generate the Table of Contents first."
40
-
41
- prompt = f"""
42
- Using the following Table of Contents for a beginner-level textbook on **{topic}**, generate the complete content of **Chapter {chapter_number}**.
43
-
44
- The chapter must include:
45
- 1. Chapter Title
46
- 2. Chapter Introduction
47
- 3. Unit SLOs (Student Learning Outcomes)
48
- 4. Detailed content organized under 5–6 subheadings (as per the TOC)
49
- 5. Relevant Examples under appropriate subheadings
50
- 6. 10 Multiple Choice Questions (MCQs) – just questions and options
51
- 7. Answer Key at the end (numbered 1 to 10)
52
- 8. A Glossary of at least 5 important terms with simple definitions
53
-
54
- Do NOT include system messages like β€œHere is the content of...” Just return clean, structured educational content.
55
- """
56
- response = client.chat.completions.create(
57
- model="llama3-70b-8192",
58
- messages=[{"role": "user", "content": prompt}],
59
- temperature=0.7
60
- )
61
- chapter = response.choices[0].message.content.strip()
62
- chapters_memory[chapter_number] = chapter
63
- return chapter
64
-
65
- # Generate DOCX
66
- def download_textbook(topic, grade):
67
- doc = Document()
68
- doc.add_heading(topic, 0)
69
- doc.add_paragraph(f"Author: Najaf Ali Sharqi")
70
- doc.add_paragraph(f"Grade: {grade}")
71
- doc.add_paragraph(f"Date of Publication: {datetime.now().strftime('%B %d, %Y')}")
72
- doc.add_page_break()
73
-
74
- doc.add_heading("Table of Contents", level=1)
75
- doc.add_paragraph(toc_memory["toc"])
76
- doc.add_page_break()
77
-
78
- for num in sorted(chapters_memory.keys()):
79
- doc.add_heading(f"Chapter {num}", level=1)
80
- doc.add_paragraph(chapters_memory[num])
81
- doc.add_page_break()
82
-
83
- file_path = "/tmp/Generated_Textbook.docx"
84
- doc.save(file_path)
85
- return file_path
86
-
87
- # Gradio UI
88
- with gr.Blocks() as demo:
89
- gr.Markdown("## πŸ“˜ AI Textbook Generator App")
90
- gr.Markdown("""
91
- Welcome to the AI Textbook Generator developed by **Najaf Ali Sharqi**.
92
-
93
- ### πŸ‘‰ Instructions:
94
- 1. Enter the **textbook topic** and **grade level**
95
- 2. Click **Generate Table of Contents**
96
- 3. Tap a chapter button to generate its content
97
- 4. After generating all chapters, click **Download Word File**
98
  """)
99
-
100
- with gr.Row():
101
- topic_input = gr.Textbox(label="Textbook Topic", placeholder="e.g., Basics of AI")
102
- grade_input = gr.Textbox(label="Grade Level", placeholder="e.g., 6")
103
-
104
- toc_btn = gr.Button("πŸ”Ή Generate Table of Contents")
105
- toc_output = gr.Textbox(label="πŸ“‘ Table of Contents", lines=10)
106
-
107
- toc_btn.click(fn=generate_toc, inputs=topic_input, outputs=toc_output)
108
-
109
- gr.Markdown("### πŸ“₯ Generate Chapter Content")
110
-
111
- with gr.Row():
112
- for i in range(1, 8):
113
- btn = gr.Button(f"Chapter {i}")
114
- btn.click(fn=generate_chapter, inputs=[topic_input, gr.Textbox(value=str(i), visible=False)], outputs=gr.Textbox(label="πŸ“– Chapter Content", lines=30))
115
-
116
- gr.Markdown("### πŸ“€ Export Full Textbook")
117
- download_btn = gr.Button("⬇️ Download Word File")
118
- download_file = gr.File()
119
-
120
- download_btn.click(fn=download_textbook, inputs=[topic_input, grade_input], outputs=download_file)
121
-
122
- gr.Markdown("---")
123
- gr.Markdown("App developed by **Najaf Ali Sharqi** | Powered by **Groq + Gradio**")
124
-
125
- demo.launch()
 
1
+ import os
2
  from datetime import datetime
3
  from groq import Groq
4
  from docx import Document
5
  from docx.shared import Pt
 
6
 
7
+ import streamlit as st
8
+
9
+ # ==== PAGE CONFIG ====
10
+ st.set_page_config(page_title="Smart Career Advisor", layout="centered")
11
+
12
+ # ==== GROQ CLIENT SETUP ====
13
+ client = Groq(api_key=os.getenv("GROQ_API_KEY"))
14
+ MODEL = "llama3-70b-8192"
15
+
16
+ def query_groq(prompt):
17
+ try:
18
+ response = client.chat.completions.create(
19
+ model=MODEL,
20
+ messages=[{"role": "user", "content": prompt}]
21
+ )
22
+ return response.choices[0].message.content
23
+ except Exception as e:
24
+ return f"Error: {str(e)}"
25
+
26
+ # ==== SIDEBAR FORM ====
27
+ with st.sidebar:
28
+ st.title("🧠 User Input")
29
+ user_name = st.text_input("πŸ‘€ Your Full Name")
30
+ education = st.selectbox("πŸ“˜ Education Level", ["Matric", "Intermediate", "Bachelor", "Master", "PhD"])
31
+ major = st.text_input("πŸ“š Field of Study / Major")
32
+ interests = st.multiselect("🎯 Interests", ["Technology", "Arts", "Business", "Healthcare", "Teaching", "Design", "Public Service", "Engineering", "Law", "Science"])
33
+ work_style = st.radio("🏒 Preferred Work Style", ["Remote", "Field-based", "Office", "Freelance"])
34
+ goal = st.selectbox("🌟 Career Goal", ["High Income", "Flexibility", "Social Impact", "Research", "Innovation"])
35
+ skills = st.text_area("πŸ› οΈ Your Skills or Strengths", placeholder="e.g., communication, coding, writing")
36
+ industry = st.text_input("🏭 Preferred Industry (optional)")
37
+ submit = st.button("πŸš€ Generate Career Report")
38
+
39
+ # ==== MAIN TITLE ====
40
+ st.title("πŸŽ“ Smart Career Advisor")
41
+ st.markdown("AI-powered suggestions based on your background and preferences.")
42
+
43
+ # ==== MAIN LOGIC ====
44
+ if submit and user_name and interests:
45
+ user_profile = f"""
46
+ Name: {user_name}
47
+ Education: {education}
48
+ Field of Study: {major}
49
+ Interests: {', '.join(interests)}
50
+ Preferred Work Style: {work_style}
51
+ Career Goal: {goal}
52
+ Skills: {skills}
53
+ Preferred Industry: {industry}
54
+ """
55
+
56
+ groq_prompt = f"""
57
+ You are a professional career counselor. Based on the following user profile, provide a comprehensive advisory report in 5 clear sections:
58
+ 1. Suitable Career Paths
59
+ 2. Job Roles/Occupations
60
+ 3. Required Skills or Certifications
61
+ 4. Recommended Learning Resources
62
+ 5. Tips to Get Started
63
+
64
+ Please be specific, practical, and professional.
65
+
66
+ USER PROFILE:
67
+ {user_profile}
68
+ """
69
+
70
+ with st.spinner("πŸ” Analyzing your profile..."):
71
+ groq_response = query_groq(groq_prompt)
72
+
73
+ # ==== DISPLAY RESULT ====
74
+ st.success("βœ… Career Report Generated")
75
+ st.markdown(f"**Name:** {user_name}")
76
+
77
+ sections = groq_response.split('\n\n')
78
+ for sec in sections:
79
+ if sec.strip():
80
+ with st.expander(sec.strip().split('\n')[0]):
81
+ st.markdown(sec.strip())
82
+
83
+ # ==== FOOTER ====
84
+ st.markdown("---")
85
+ st.markdown("**πŸ‘¨β€πŸ’» Developed by Najaf Ali Sharqi**")
86
+ st.markdown("""
87
+ **About the Developer:**
88
+ Najaf Ali Sharqi is an educationist and AI trainer with a strong background in Educational Technology and Curriculum Development.
89
+ He specializes in developing user-friendly GenAI tools for educators and students in low-resource environments, and is passionate about integrating technology with social impact.
 
 
 
 
 
 
 
90
  """)