jzou19950715 commited on
Commit
372c334
·
verified ·
1 Parent(s): ab272ea

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -261
app.py DELETED
@@ -1,261 +0,0 @@
1
- """
2
- Gradio Interactive Chat App for Educational Information Collection.
3
- """
4
-
5
- # Imports
6
- import gradio as gr
7
- import openai
8
- import json
9
- from datetime import datetime
10
- from typing import List, Optional, Dict
11
- from pydantic import BaseModel, Field
12
-
13
- # Constants
14
- SYSTEM_PROMPT = """You are an educational information collection assistant. Your task is to systematically collect the following information in a conversational manner:
15
-
16
- Required Information (collect in this order):
17
- 1. Institution Details:
18
- - Name
19
- - Type (e.g., university, college, etc.)
20
- - Location
21
- 2. Degree Information:
22
- - Type (e.g., Bachelor's, Master's, etc.)
23
- - Field of Study
24
- - Status (e.g., completed, ongoing)
25
- 3. Attendance Dates (start and end)
26
- 4. Academic Performance:
27
- - GPA (if provided)
28
- - Honors or awards
29
- 5. Activities:
30
- - Extracurricular activities, roles, and durations
31
-
32
- Always maintain a friendly, professional tone while systematically collecting this information."""
33
-
34
- # Data Models
35
- class Institution(BaseModel):
36
- name: str
37
- type: str
38
- location: str
39
-
40
-
41
- class Degree(BaseModel):
42
- type: str
43
- field: str
44
- status: str
45
-
46
-
47
- class Dates(BaseModel):
48
- start: str
49
- end: str
50
-
51
-
52
- class Activity(BaseModel):
53
- name: str
54
- description: str
55
- duration: str
56
-
57
-
58
- class Academic(BaseModel):
59
- gpa: Optional[float] = None
60
- honors: List[str] = Field(default_factory=list)
61
- achievements: List[str] = Field(default_factory=list)
62
-
63
-
64
- class Education(BaseModel):
65
- institution: Institution
66
- degree: Degree
67
- dates: Dates
68
- academic: Academic
69
- activities: List[Activity] = Field(default_factory=list)
70
-
71
-
72
- class EducationRecord(BaseModel):
73
- education: List[Education] = Field(default_factory=list)
74
- metadata: Dict[str, str]
75
-
76
-
77
- # Assistant Logic
78
- class EducationAssistant:
79
- """
80
- Handles conversation state, chat interactions, and JSON generation.
81
- """
82
-
83
- def __init__(self):
84
- self.conversation_history = []
85
- self.client = None
86
- self.system_prompt = SYSTEM_PROMPT
87
-
88
- def initialize_chat(self, api_key: str) -> str:
89
- """Initializes OpenAI client and provides the first prompt."""
90
- try:
91
- openai.api_key = api_key
92
- return "Hello! Let's record your educational history. What is the name of your most recent educational institution?"
93
- except Exception as e:
94
- return f"Error initializing chat: {str(e)}"
95
-
96
- def chat(self, message: str, api_key: str) -> Dict[str, str]:
97
- """Processes user messages and generates responses."""
98
- if not self.client:
99
- first_message = self.initialize_chat(api_key)
100
- self.conversation_history.append({"role": "assistant", "content": first_message})
101
- return {"role": "assistant", "content": first_message}
102
-
103
- try:
104
- # Append user message to history
105
- self.conversation_history.append({"role": "user", "content": message})
106
-
107
- # Generate response
108
- response = openai.ChatCompletion.create(
109
- model="gpt-4o-mini",
110
- messages=[{"role": "system", "content": self.system_prompt}] + self.conversation_history,
111
- temperature=0.7,
112
- max_tokens=300
113
- )
114
-
115
- # Parse and store assistant response
116
- assistant_message = {"role": "assistant", "content": response.choices[0].message.content}
117
- self.conversation_history.append(assistant_message)
118
-
119
- return assistant_message
120
-
121
- except Exception as e:
122
- return {"role": "assistant", "content": f"Error: {str(e)}"}
123
-
124
- def generate_json(self) -> Optional[str]:
125
- """Generates structured JSON from the conversation history."""
126
- try:
127
- json_prompt = """Based on our conversation, generate a structured JSON containing the educational information shared. Format it as follows:
128
- {
129
- "education": [
130
- {
131
- "institution": {
132
- "name": string,
133
- "type": string,
134
- "location": string
135
- },
136
- "degree": {
137
- "type": string,
138
- "field": string,
139
- "status": string
140
- },
141
- "dates": {
142
- "start": string,
143
- "end": string
144
- },
145
- "academic": {
146
- "gpa": float (if provided),
147
- "honors": [string],
148
- "achievements": [string]
149
- },
150
- "activities": [
151
- {
152
- "name": string,
153
- "description": string,
154
- "duration": string
155
- }
156
- ]
157
- }
158
- ],
159
- "metadata": {
160
- "timestamp": string,
161
- "source": "Education Information Assistant"
162
- }
163
- }
164
- Respond ONLY with the JSON."""
165
-
166
- # Generate JSON based on the conversation history
167
- response = openai.ChatCompletion.create(
168
- model="gpt-4o-mini",
169
- messages=[{"role": "system", "content": self.system_prompt}] + self.conversation_history +
170
- [{"role": "user", "content": json_prompt}],
171
- temperature=0.1,
172
- max_tokens=1500
173
- )
174
-
175
- # Parse response and write JSON file
176
- json_data = json.loads(response.choices[0].message.content)
177
- filename = f"education_data_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
178
- with open(filename, "w") as f:
179
- json.dump(json_data, f, indent=2)
180
-
181
- return filename
182
-
183
- except Exception as e:
184
- print(f"Error generating JSON: {str(e)}")
185
- return None
186
-
187
-
188
- # Gradio Interface
189
- def create_interface():
190
- assistant = EducationAssistant()
191
-
192
- with gr.Blocks() as demo:
193
- gr.Markdown("# 📘 Educational Information Collection Assistant")
194
-
195
- with gr.Row():
196
- api_key = gr.Textbox(
197
- label="OpenAI API Key",
198
- type="password",
199
- placeholder="Enter your OpenAI API Key",
200
- info="Required for using OpenAI's GPT model."
201
- )
202
-
203
- chatbot = gr.Chatbot(label="Assistant", height=400)
204
-
205
- with gr.Row():
206
- user_input = gr.Textbox(
207
- label="Your Message",
208
- placeholder="Type your message here...",
209
- lines=2
210
- )
211
- send_button = gr.Button("Send", variant="primary")
212
-
213
- generate_button = gr.Button("Generate JSON")
214
- download_file = gr.File(label="Generated JSON")
215
-
216
- # Event Handlers
217
- def handle_send(message, history, api_key):
218
- if not api_key.strip():
219
- return history + [{"role": "assistant", "content": "Please provide your OpenAI API key to continue."}]
220
-
221
- if not message.strip():
222
- return history
223
-
224
- response = assistant.chat(message, api_key)
225
- return history + [{"role": "user", "content": message}, response]
226
-
227
- def handle_generate():
228
- filename = assistant.generate_json()
229
- if filename:
230
- return filename
231
- return "Error generating JSON. Please ensure all required information is collected."
232
-
233
- # Button Actions
234
- send_button.click(
235
- handle_send,
236
- inputs=[user_input, chatbot, api_key],
237
- outputs=[chatbot]
238
- )
239
-
240
- user_input.submit(
241
- handle_send,
242
- inputs=[user_input, chatbot, api_key],
243
- outputs=[chatbot]
244
- )
245
-
246
- generate_button.click(
247
- handle_generate,
248
- outputs=[download_file]
249
- )
250
-
251
- return demo
252
-
253
-
254
- # Main Execution
255
- if __name__ == "__main__":
256
- demo = create_interface()
257
- demo.launch(
258
- server_name="0.0.0.0",
259
- server_port=7860,
260
- share=True
261
- )