sbatool commited on
Commit
ffbc5f7
Β·
verified Β·
1 Parent(s): 3d662ee

Upload folder using huggingface_hub

Browse files
Files changed (5) hide show
  1. .github/workflows/update_space.yml +28 -0
  2. .gitignore +27 -0
  3. README.md +3 -9
  4. app.py +735 -0
  5. requirements.txt +13 -0
.github/workflows/update_space.yml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Run Python script
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+
12
+ steps:
13
+ - name: Checkout
14
+ uses: actions/checkout@v2
15
+
16
+ - name: Set up Python
17
+ uses: actions/setup-python@v2
18
+ with:
19
+ python-version: '3.9'
20
+
21
+ - name: Install Gradio
22
+ run: python -m pip install gradio
23
+
24
+ - name: Log in to Hugging Face
25
+ run: python -c 'import huggingface_hub; huggingface_hub.login(token="${{ secrets.hf_token }}")'
26
+
27
+ - name: Deploy to Spaces
28
+ run: gradio deploy
.gitignore ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python cache
2
+ __pycache__/
3
+ *.pyc
4
+ *.pyo
5
+ *.pyd
6
+
7
+ # Virtual environments
8
+ .venv/
9
+ env/
10
+ venv/
11
+
12
+ # Environment variables
13
+ .env
14
+
15
+ # Jupyter / IPython
16
+ .ipynb_checkpoints/
17
+ *.ipynb
18
+
19
+ # OS files
20
+ .DS_Store
21
+ Thumbs.db
22
+
23
+ # Logs
24
+ *.log
25
+
26
+ # Temporary files
27
+ *.tmp
README.md CHANGED
@@ -1,12 +1,6 @@
1
  ---
2
- title: Resume Builder
3
- emoji: πŸ“Š
4
- colorFrom: indigo
5
- colorTo: red
6
- sdk: gradio
7
- sdk_version: 5.43.1
8
  app_file: app.py
9
- pinned: false
 
10
  ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: resume-builder
 
 
 
 
 
3
  app_file: app.py
4
+ sdk: gradio
5
+ sdk_version: 5.42.0
6
  ---
 
 
app.py ADDED
@@ -0,0 +1,735 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import os
3
+ import uuid
4
+ from datetime import datetime
5
+ from typing import Annotated, TypedDict, List, Any, Optional, Dict
6
+
7
+ from dotenv import load_dotenv
8
+ from pydantic import BaseModel, Field
9
+
10
+ import fitz # PyMuPDF
11
+ import gradio as gr
12
+ from langchain_openai import ChatOpenAI
13
+ from langchain.schema import SystemMessage, HumanMessage, AIMessage
14
+ from langchain.memory import ConversationSummaryMemory
15
+ from langgraph.graph import StateGraph, START, END
16
+ from langgraph.graph.message import add_messages
17
+ from langgraph.checkpoint.memory import MemorySaver
18
+
19
+ # ---------------------------
20
+ # Load environment variables
21
+ # ---------------------------
22
+ load_dotenv()
23
+
24
+ # ---------------------------
25
+ # State Definition
26
+ # ---------------------------
27
+ class State(TypedDict):
28
+ messages: Annotated[list[Any], add_messages]
29
+ job_desc: str # keep the original job description
30
+ user_tone: str # user-specified tone
31
+ selected_tone: str # optional tone selection
32
+ phases: list # <-- replace `job_data` with the phases output
33
+ proposal_text: str # generated proposal text
34
+ evaluation_scores: dict # scoring for AI detection etc.
35
+ user_portfolio_text: str # user’s portfolio content
36
+ user_feedback: dict # feedback if any
37
+ session_summary: str # summary of the chat/session
38
+ success_status: str # success/failure flag
39
+ instructions: str # instruction for proposal edits
40
+ count_loop: int # for retry or loop logic
41
+
42
+ # ---------------------------
43
+ # Phase Models
44
+ # ---------------------------
45
+ class PhaseStep(BaseModel):
46
+ step_number: int = Field(
47
+ description="The sequential order of this step within the phase, starting from 1"
48
+ )
49
+ title: str = Field(
50
+ description="A short, descriptive title summarizing the step's action, e.g., 'Analyze Job Description'"
51
+ )
52
+ description: str = Field(
53
+ description="A detailed explanation of what needs to be done in this step"
54
+ )
55
+ tools_required: List[str] = Field(
56
+ default=[],
57
+ description="A list of tools, software, or platforms required to complete this step"
58
+ )
59
+ output_example: Optional[str] = Field(
60
+ default=None,
61
+ description="An example of the expected output or deliverable for this step, if applicable"
62
+ )
63
+ notes: Optional[str] = Field(
64
+ default=None,
65
+ description="Additional notes, tips, or context to ensure the step is carried out correctly"
66
+ )
67
+
68
+ class Phase(BaseModel):
69
+ phase_name: str = Field(
70
+ description="The name of the phase, grouping related steps, e.g., 'Preparation', 'Execution', 'Delivery'"
71
+ )
72
+ tasks: List[PhaseStep] = Field(
73
+ description="A list of PhaseStep objects detailing each actionable task in this phase"
74
+ )
75
+
76
+ class Phases(BaseModel):
77
+ phases: List[Phase] = Field(
78
+ description="A complete list of all phases for the job, each containing structured step-by-step tasks"
79
+ )
80
+
81
+
82
+
83
+ # ---------------------------
84
+ # Load environment variables and initialize LLM
85
+ # ---------------------------
86
+
87
+
88
+ load_dotenv()
89
+
90
+ # Get OpenAI API key
91
+ api_key = os.getenv("OPENAI_API_KEY")
92
+ if not api_key:
93
+ raise ValueError("OPENAI_API_KEY not found in environment variables")
94
+ print("βœ… API Key loaded successfully.")
95
+
96
+ # Initialize LLM agent
97
+ agent = ChatOpenAI(
98
+ model="gpt-4o-mini",
99
+ api_key=api_key,
100
+ temperature=0.0,
101
+ streaming=True
102
+ )
103
+
104
+ # Structured output wrapper for Phases
105
+ node1_agent_llm_with_output = agent.with_structured_output(Phases)
106
+
107
+ # ---------------------------
108
+ # Phase Maker Function
109
+ # ---------------------------
110
+ def phase_maker(state: State) -> Dict[str, Any]:
111
+ """Generates structured phases from job description and portfolio text."""
112
+ print("---- Entered PhaseMaker ----")
113
+ job_description = state["job_desc"]
114
+ portfolio_text = state.get("user_portfolio_text", "")
115
+
116
+ print(f"[PhaseMaker] Received job_desc: {job_description[:100]}...")
117
+ print(f"[PhaseMaker] Received portfolio_text: {portfolio_text[:100]}...")
118
+
119
+ node_1_user_prompt = f"""
120
+ You are a step-by-step implementation assistant. Your task is to convert the following job description and past work history into a fully structured plan that can be used to generate a proposal.
121
+
122
+ Output MUST follow the Pydantic model `Phases`:
123
+ - Phases β†’ Phase β†’ PhaseStep
124
+ - Every step must have: step_number, title, description, tools_required, output_example, notes
125
+ - Every variable must be fully populated with realistic, specific information. Do NOT leave placeholders or generic statements.
126
+ - Include all relevant tools, software, and platforms needed for each step.
127
+ - Include expected deliverables/output in each step if applicable.
128
+ - Provide actionable instructions that someone could follow to complete each step.
129
+ - Organize steps logically into phases like Preparation, Execution, Delivery.
130
+
131
+ Requirements:
132
+ - Ensure clarity, specificity, and actionable content.
133
+ - Avoid generic or filler text.
134
+ - Reflect relevant skills and tools used in your past projects if applicable.
135
+ - Strictly make these 3 phases only: Preparation, Execution, Delivery.
136
+
137
+ Example expected output:
138
+ {{
139
+ "phases": [
140
+ {{
141
+ "phase_name": "Preparation",
142
+ "tasks": [
143
+ {{
144
+ "step_number": 1,
145
+ "title": "Analyze Job Description",
146
+ "description": "Carefully read the job posting to identify core tasks and client expectations...",
147
+ "tools_required": ["Notion", "Google Docs"],
148
+ "output_example": "List of required skills and deliverables",
149
+ "notes": "Focus on mandatory skills and desired experience"
150
+ }}
151
+ ]
152
+ }}
153
+ ]
154
+ }}
155
+
156
+ Generate the full Phases JSON now.
157
+ Job Description:
158
+ {job_description}
159
+
160
+ Past Work History:
161
+ {portfolio_text}
162
+ """
163
+
164
+ if not state.get("phases"):
165
+ print("[PhaseMaker] No existing phases found β†’ generating new ones...")
166
+ messages = [HumanMessage(content=node_1_user_prompt)]
167
+ response = node1_agent_llm_with_output.invoke(messages)
168
+ print("[PhaseMaker] Generated Phases response successfully βœ…")
169
+ return {"phases": response}
170
+
171
+ print("[PhaseMaker] Existing phases found β†’ skipping generation.")
172
+ return {"phases": state.get("phases")}
173
+
174
+
175
+
176
+ # ---------------------------
177
+ # Node 2 Prompt Template
178
+ # ---------------------------
179
+
180
+
181
+ node_2_prompt = """
182
+ You are a professional proposal writing assistant. Your task is to generate a personalized proposal using a predefined template. Follow these rules strictly:
183
+
184
+ 1. Use the `phases` JSON provided as structured output from the previous step.
185
+ 2. Replace all placeholders in the template with the actual, specific content from `phases` and the job description.
186
+ 3. Do NOT invent new content beyond what is in `phases`, `job_description`, or `user_portfolio_text`.
187
+ 4. Maintain a natural, human-like writing style to minimize AI detection.
188
+ 5. Output the proposal as a single coherent text, ready to send to the client.
189
+ 6. If `instructions` are provided by the user, apply them carefully without regenerating phases.
190
+
191
+ When filling the placeholders, extract details directly from phases.
192
+ """
193
+
194
+ # ---------------------------
195
+ # Proposal Output & LLM Wrapper
196
+ # ---------------------------
197
+ from pydantic import BaseModel, Field
198
+ from typing import Dict, Any, List
199
+ from langchain_openai import ChatOpenAI
200
+ from langchain.schema import HumanMessage, AIMessage, SystemMessage
201
+
202
+ class ProposalOutput(BaseModel):
203
+ """The full, ready-to-send proposal generated for the client."""
204
+ proposal: str = Field(
205
+ description="The full, ready-to-send proposal generated for the client, written in natural human-like style."
206
+ )
207
+
208
+ # Wrap LLM output with structured ProposalOutput
209
+ agent_llm_with_output = agent.with_structured_output(ProposalOutput)
210
+
211
+ # ---------------------------
212
+ # Template Selection Function
213
+ # ---------------------------
214
+ def get_template_by_tone(tone: str) -> str:
215
+ """Return proposal template text based on user-selected tone."""
216
+ print(f"[Template] Getting template for tone: {tone}")
217
+ templates = {
218
+ "Professional & Confident": "[HOOK] Hi {client_name}, I had a look at your project on {final_phase_main_output} ...",
219
+ "Friendly & Conversational": "[HOOK] Hi {client_name}, I just checked out your project on {project_type} ...",
220
+ "Creative & Narrative-Driven": "[HOOK] Hi {client_name}, I came across your project on {project_type} ...",
221
+ "Analytical & Problem-Solver": "[HOOK] from {preparation_phase_decription_short} to the '{final_phase_delieverable}' ...",
222
+ "Persuasive & Client-Focused": "[HOOK] Picture this: your {project_type} not only looks amazing, but actually works hard ..."
223
+ }
224
+ return templates.get(tone, "Tone not found. Please choose a valid tone.")
225
+
226
+ # ---------------------------
227
+ # Worker Node Function
228
+ # ---------------------------
229
+ def worker(state: State) -> Dict[str, Any]:
230
+ """Generate a client-ready proposal based on job description, phases, and user portfolio."""
231
+ print("---- Entered Worker ----")
232
+
233
+ job_message = state["job_desc"]
234
+ tone = state.get("user_tone", "")
235
+ portfolio_text = state.get("user_portfolio_text", "")
236
+ instructions = state.get("instructions", "")
237
+ template_text = get_template_by_tone(tone)
238
+ phases = state.get("phases", [])
239
+
240
+ print(f"[Worker] Job description received: {job_message[:100]}...")
241
+ print(f"[Worker] Tone: {tone}")
242
+ print(f"[Worker] Instructions: {instructions[:100]}...")
243
+ print(f"[Worker] Portfolio text: {portfolio_text[:100]}...")
244
+ print(f"[Worker] Phases present? {'Yes' if phases else 'No'}")
245
+
246
+ node_2_user_prompt = f"""
247
+ - job_description: {job_message}
248
+
249
+ - phases: structured step-by-step implementation
250
+ {phases}
251
+
252
+ - user_portfolio_text:
253
+ {portfolio_text}
254
+
255
+ - instructions: optional user edits for the proposal
256
+ {instructions}
257
+
258
+ Template: {template_text}
259
+ """
260
+
261
+ # Handle feedback
262
+ if state.get("feedback_on_work"):
263
+ print("[Worker] Feedback found β†’ appending to system message.")
264
+ feedback_text = f"""
265
+ Previous submission was rejected.
266
+ Here is the feedback you received:
267
+ {state['feedback_on_work']}
268
+
269
+ Use this feedback to revise and improve the proposal to meet the success criteria.
270
+ """
271
+ else:
272
+ feedback_text = ""
273
+ print("[Worker] No feedback found β†’ proceeding normally.")
274
+
275
+ # Build messages
276
+ found_system_message = False
277
+ messages = state.get("messages", [])
278
+ for message in messages:
279
+ if isinstance(message, SystemMessage):
280
+ message.content = node_2_user_prompt + feedback_text
281
+ found_system_message = True
282
+
283
+ if not found_system_message:
284
+ print("[Worker] No existing SystemMessage β†’ creating a new one.")
285
+ messages = [SystemMessage(content=node_2_prompt + feedback_text)] + messages
286
+ else:
287
+ print("[Worker] Existing SystemMessage found β†’ updated with new prompt.")
288
+
289
+ msg_list = [HumanMessage(content=node_2_user_prompt)] + messages
290
+ print(f"[Worker] Built msg_list with {len(msg_list)} messages")
291
+
292
+ # Call LLM
293
+ response = agent_llm_with_output.invoke(msg_list)
294
+ print("[Worker] Received response from agent LLM βœ…")
295
+
296
+ new_state = {
297
+ "proposal_text": response.proposal,
298
+ "messages": [AIMessage(content=f"proposal written {response.proposal[:100]}...")]
299
+ }
300
+
301
+ print("[Worker] Returning new state with proposal_text and updated messages.")
302
+ return new_state
303
+
304
+ # ---------------------------
305
+ # Utility Function: Format Conversation
306
+ # ---------------------------
307
+ def format_conversation(messages: List[Any]) -> str:
308
+ """Format the conversation history for display or logging."""
309
+ conversation = "Conversation history:\n\n"
310
+ for message in messages:
311
+ if isinstance(message, HumanMessage):
312
+ conversation += f"User: {message.content}\n"
313
+ elif isinstance(message, AIMessage):
314
+ conversation += f"Assistant: {message.content}\n"
315
+ return conversation
316
+
317
+
318
+ # ---------------------------
319
+ # Evaluator Output & LLM Wrapper
320
+ # ---------------------------
321
+ from pydantic import BaseModel, Field
322
+ from typing import Dict, Any
323
+ from langchain.schema import SystemMessage, HumanMessage
324
+ from langgraph.graph import StateGraph
325
+
326
+ class EvaluatorOutput(BaseModel):
327
+ """Structured evaluation output for proposal quality."""
328
+ user_feedback: str = Field(
329
+ description="Detailed feedback on the assistant's proposal, including strengths and areas to improve"
330
+ )
331
+ evaluation_scores: str = Field(
332
+ description="Scoring or boolean evaluation for each success criterion"
333
+ )
334
+ success_status: str = Field(
335
+ description="Overall status of evaluation: 'passed', 'failed', or 'needs_input'"
336
+ )
337
+
338
+ # System prompt for the evaluator
339
+ evaluator_system_prompt = """You are an evaluator for a professional proposal-writing AI assistant.
340
+ You will be given:
341
+ 1. The job description (client’s posting).
342
+ 2. The template and tone that were used to generate the proposal.
343
+ 3. The structured phases the assistant followed.
344
+ 4. The assistant’s final proposal.
345
+
346
+ Your job is to check whether the proposal aligns with both:
347
+ - The client’s job description.
348
+ - The intended template/phases.
349
+
350
+ Check the proposal for:
351
+ - Relevance β€” Does it clearly address the specific job description and client needs, not just generic text?
352
+ - Profile Use β€” Does it correctly use the freelancer’s profile and portfolio as its own?
353
+ - Tone β€” Does the proposal’s tone match the selected template?
354
+ - Structure β€” Is the structure aligned with the phases and template (clear, professional flow)?
355
+ - Portfolio β€” Are relevant portfolio links included if provided?
356
+ - Authenticity β€” Does it avoid robotic or filler text, and sound human?
357
+
358
+ Respond with:
359
+ 1. A list of feedback points for improvement.
360
+ 2. A score (0–10) for each: relevance, tone, structure.
361
+ 3. Overall status: passed, failed, or needs_input.
362
+
363
+ If status is failed, explicitly explain what must be changed in the proposal to pass.
364
+ """
365
+
366
+ # ---------------------------
367
+ # Evaluator Function
368
+ # ---------------------------
369
+ def evaluator(state: State) -> State:
370
+ """Evaluate the generated proposal for quality, alignment with job description, and template adherence."""
371
+ print("---- Entered Evaluator ----")
372
+
373
+ last_response = state.get("proposal_text", "")
374
+ user_message = f"""Conversation history:
375
+ {format_conversation(state.get('messages', []))}
376
+
377
+ # Job description:
378
+ {state.get('job_desc', '')}
379
+
380
+ # Template used:
381
+ {state.get('selected_template', '')}
382
+
383
+ # Structured phases followed:
384
+ {state.get('phases', '')}
385
+
386
+ Last proposal:
387
+ {last_response}
388
+ """
389
+
390
+ if state.get("user_feedback"):
391
+ user_message += f"\nPrevious feedback: {state['user_feedback']}\n"
392
+ print("[Evaluator] Found user feedback β†’ appended to prompt.")
393
+ else:
394
+ print("[Evaluator] No previous user feedback.")
395
+
396
+ # Build evaluator messages
397
+ evaluator_messages = [
398
+ SystemMessage(content=evaluator_system_prompt),
399
+ HumanMessage(content=user_message)
400
+ ]
401
+ print(f"[Evaluator] Built evaluator_messages with {len(evaluator_messages)} messages")
402
+
403
+ # LLM call with structured output
404
+ evaluator_llm_with_output = agent.with_structured_output(EvaluatorOutput)
405
+ eval_result = evaluator_llm_with_output.invoke(evaluator_messages)
406
+ print("[Evaluator] Got evaluation result from LLM βœ…")
407
+ print(f"[Evaluator] success_status: {eval_result.success_status}")
408
+ print(f"[Evaluator] evaluation_scores: {eval_result.evaluation_scores}")
409
+ print(f"[Evaluator] user_feedback: {eval_result.user_feedback[:100]}...")
410
+
411
+ # Increment loop counter
412
+ state["count_loop"] = state.get("count_loop", 0) + 1
413
+ print(f"[Evaluator] Evaluation loop count β†’ {state['count_loop']}")
414
+
415
+ # Stop after 2 attempts (3rd means needs input)
416
+ success_status = eval_result.success_status
417
+ if state["count_loop"] >= 2:
418
+ print(f"[Evaluator] Maximum limit reached ({state['count_loop']} attempts). Forcing 'needs_input'")
419
+ success_status = "needs_input"
420
+
421
+ new_state = {
422
+ "user_feedback": eval_result.user_feedback,
423
+ "evaluation_scores": eval_result.evaluation_scores,
424
+ "success_status": success_status,
425
+ "proposal_text": last_response,
426
+ "count_loop": state["count_loop"]
427
+ }
428
+
429
+ print("[Evaluator] Returning new state with evaluation results.")
430
+ return new_state
431
+
432
+ # ---------------------------
433
+ # Route Based on Evaluation
434
+ # ---------------------------
435
+ def route_based_on_evaluation(state: dict) -> str:
436
+ """Determine the next step in the workflow based on evaluation status."""
437
+ if state.get("success_status") in ["passed", "needs_input"]:
438
+ return "END"
439
+ return "worker"
440
+
441
+
442
+
443
+ # ---------------------------
444
+ # State Graph Initialization
445
+ # ---------------------------
446
+
447
+
448
+ graph_builder = StateGraph(State)
449
+
450
+
451
+
452
+ # ---------------------------
453
+ # Graph Nodes & Flow Setup
454
+ # ---------------------------
455
+ from langgraph.checkpoint.memory import MemorySaver
456
+ from IPython.display import Image, display
457
+
458
+ # Add nodes
459
+ graph_builder.add_node("phase_maker", phase_maker)
460
+ graph_builder.add_node("worker", worker)
461
+ graph_builder.add_node("evaluator", evaluator)
462
+
463
+ # Add edges
464
+ graph_builder.add_edge("phase_maker", "worker") # phases go into worker
465
+ graph_builder.add_edge("worker", "evaluator") # proposal goes to evaluator
466
+ graph_builder.add_conditional_edges(
467
+ "evaluator",
468
+ route_based_on_evaluation,
469
+ {"worker": "worker", "END": END} # loop back or end
470
+ )
471
+
472
+ # Entry point
473
+ graph_builder.add_edge(START, "phase_maker")
474
+
475
+ # Compile the graph with memory
476
+ memory = MemorySaver()
477
+ compiled_graph = graph_builder.compile(checkpointer=memory)
478
+
479
+ # # Optional: Display graph as PNG in Jupyter
480
+ # display(Image(compiled_graph.get_graph().draw_mermaid_png()))
481
+
482
+ # ---------------------------
483
+ # Thread & Reset Utilities
484
+ # ---------------------------
485
+ import uuid
486
+
487
+ def make_thread_id() -> str:
488
+ """Generate a unique thread ID for new conversation sessions."""
489
+ return str(uuid.uuid4())
490
+
491
+ def reset(thread: str):
492
+ """Reset conversation memory for a given thread and generate a new thread ID."""
493
+ print(f"[Reset] Current thread id: {thread}")
494
+ try:
495
+ memory.delete(thread) # Clear old conversation memory
496
+ except Exception as e:
497
+ print(f"[Warning] Could not delete memory for thread {thread}: {e}")
498
+
499
+ new_thread = make_thread_id()
500
+
501
+ # Return initial state for Gradio interface (matching output order & type)
502
+ return (
503
+ "", # instructions (Textbox)
504
+ "", # job_desc (Textbox)
505
+ [], # conversation (Chatbot messages)
506
+ None, # pdf_uploader (File)
507
+ "Professional & Confident", # tone_selector (Dropdown default value)
508
+ new_thread # thread (State)
509
+ )
510
+
511
+
512
+ # ---------------------------
513
+ # supabase_module.py
514
+ # ---------------------------
515
+
516
+ import os
517
+ from datetime import datetime
518
+ from dotenv import load_dotenv
519
+ from supabase import create_client
520
+ import fitz # PyMuPDF
521
+ from typing import List, Optional
522
+
523
+ # Load env variables
524
+ load_dotenv()
525
+
526
+ SUPABASE_URL = os.getenv("SUPABASE_URL")
527
+ SUPABASE_KEY = os.getenv("SUPABASE_KEY")
528
+ supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
529
+
530
+ MAX_FILES = 2
531
+
532
+ # ---------------------------
533
+ # DB Functions
534
+ # ---------------------------
535
+ def add_file_to_db(file_name: str, file_path: str):
536
+ """Extract text from PDF and insert/update in Supabase."""
537
+ text = ""
538
+ with fitz.open(file_path) as doc:
539
+ for page in doc:
540
+ text += page.get_text()
541
+
542
+ supabase.table("uploaded_files").upsert({
543
+ "file_name": file_name,
544
+ "file_text": text,
545
+ "upload_date": datetime.now().isoformat()
546
+ }, on_conflict="file_name").execute()
547
+
548
+ enforce_max_files()
549
+
550
+
551
+ def enforce_max_files():
552
+ """Ensure only MAX_FILES are stored in DB, delete oldest if needed."""
553
+ try:
554
+ data = supabase.table("uploaded_files").select("id, file_name, upload_date").execute()
555
+ files = data.data
556
+ if len(files) > MAX_FILES:
557
+ for file in sorted(files, key=lambda x: x["upload_date"])[:len(files)-MAX_FILES]:
558
+ supabase.table("uploaded_files").delete().eq("id", file["id"]).execute()
559
+ except Exception as e:
560
+ print("[Supabase] Error enforcing max files:", e)
561
+
562
+
563
+ def get_files_from_db() -> List[dict]:
564
+ """Return all uploaded files, latest first."""
565
+ try:
566
+ data = supabase.table("uploaded_files").select("file_name, file_text, upload_date").execute()
567
+ files = data.data if data.data else []
568
+ files.sort(key=lambda x: x["upload_date"], reverse=True)
569
+ return files
570
+ except Exception as e:
571
+ print("[Supabase] Error fetching files:", e)
572
+ return []
573
+
574
+
575
+ def extract_pdf_data() -> str:
576
+ """Concatenate text from all uploaded PDFs."""
577
+ text = ""
578
+ for file in get_files_from_db():
579
+ text += file['file_text']
580
+ print(f"[PDF Extraction] Preview: {text[:50]}...")
581
+ return text
582
+
583
+
584
+ # ---------------------------
585
+ # Gradio Functions
586
+ # ---------------------------
587
+ def upload_files(files) -> List[str]:
588
+ """Handle uploaded files from Gradio and store in Supabase."""
589
+ if not files:
590
+ return refresh_file_list()
591
+
592
+ for f in files:
593
+ file_name = os.path.basename(f.name)
594
+ add_file_to_db(file_name, f.name)
595
+ return refresh_file_list()
596
+
597
+
598
+ def refresh_file_list() -> List[str]:
599
+ """Return file list for display in UI."""
600
+ files_data = get_files_from_db()
601
+ return [f"{f['file_name']} (Uploaded: {f['upload_date']})" for f in files_data]
602
+
603
+
604
+ async def generate_proposal(job_description: str, instructions: str, tone: str, history: list, thread: str):
605
+ """Main function to generate proposal using compiled graph and PDF data."""
606
+ print(f"[Generate Proposal] thread_id={thread}, tone={tone}")
607
+ user_message = {"role": "user", "content": instructions}
608
+ portfolio_text = extract_pdf_data()
609
+
610
+ state = {
611
+ "proposal_text": "",
612
+ "user_tone": tone,
613
+ "instructions": instructions,
614
+ "messages": user_message,
615
+ "selected_tone": tone,
616
+ "user_portfolio_text": portfolio_text,
617
+ "job_desc": job_description,
618
+ "count_loop": 0
619
+ }
620
+ config = {"configurable": {"thread_id": thread}}
621
+
622
+ result = await compiled_graph.ainvoke(state, config=config)
623
+
624
+ proposal_text = result["proposal_text"]
625
+ new_history = history + [user_message, {"role": "assistant", "content": proposal_text}]
626
+ return new_history, result
627
+
628
+
629
+ def get_summary_from_memory(saved_state: dict) -> str:
630
+ """Generate conversation summary using MemorySaver and ConversationSummaryMemory."""
631
+ if not saved_state or "messages" not in saved_state:
632
+ return ""
633
+
634
+ from langchain.memory import ConversationSummaryMemory
635
+ llm = ChatOpenAI(model="gpt-4o-mini")
636
+ summary_memory = ConversationSummaryMemory(llm=llm)
637
+
638
+ user_msg = None
639
+ for msg in saved_state.get("messages", []):
640
+ if isinstance(msg, HumanMessage):
641
+ user_msg = msg.content
642
+ elif isinstance(msg, AIMessage) and user_msg is not None:
643
+ summary_memory.save_context({"input": user_msg}, {"output": msg.content})
644
+ user_msg = None
645
+
646
+ summary_final = summary_memory.load_memory_variables({})["history"]
647
+ print(f"[Summary] {summary_final[:100]}...")
648
+ return summary_final
649
+
650
+ # ---------------------------
651
+ # Session Finalization
652
+ # ---------------------------
653
+
654
+ def finish_session(thread_id: str, saved_state: dict):
655
+ """
656
+ Finalize a session by generating a conversation summary
657
+ and saving it to Supabase.
658
+ """
659
+ print(f"[Session] Finishing session for thread_id={thread_id}")
660
+
661
+ # Generate summary
662
+ summary = get_summary_from_memory(saved_state)
663
+ print(f"[Session] Generated summary preview: {summary[:100]}...")
664
+
665
+ # Save summary to Supabase
666
+ try:
667
+ supabase.table("summaries").insert({
668
+ "session_id": thread_id,
669
+ "summary": summary,
670
+ "created_at": datetime.now().isoformat()
671
+ }).execute()
672
+ print(f"βœ… Conversation summarized and saved for thread {thread_id}.")
673
+ except Exception as e:
674
+ print(f"[Session] Error saving summary to Supabase: {e}")
675
+
676
+
677
+ #----------------------
678
+ #-------GRADIO APP-----
679
+ #-----------------------
680
+
681
+
682
+ import gradio as gr
683
+
684
+ # -------- Gradio UI --------
685
+ with gr.Blocks(css="""
686
+ #left-panel {width: 200px;}
687
+ #conversation-box {height: 400px; overflow-y: auto;}
688
+ """) as demo:
689
+ thread = gr.State(make_thread_id())
690
+ saved_state=gr.State()
691
+ with gr.Row():
692
+ # Left side panel
693
+ with gr.Column(elem_id="left-panel"):
694
+ gr.Markdown("### πŸ“‚ Session")
695
+ refresh_btn = gr.Button("πŸ”„ New Session")
696
+ finish_btn = gr.Button("🏁 Summary")
697
+
698
+
699
+ # Center conversation + inputs
700
+ with gr.Column(scale=3):
701
+ conversation = gr.Chatbot(label="AI Proposal Conversation", elem_id="conversation-box" ,type="messages")
702
+ job_desc = gr.Textbox(label="Job Description", placeholder="Paste the job description here", lines=4)
703
+ instructions = gr.Textbox(label="Instructions", placeholder="Add any special instructions here", lines=3)
704
+ submit_btn = gr.Button("Generate Proposal")
705
+
706
+ # Right controls
707
+ with gr.Column(scale=1):
708
+ tone_selector = gr.Dropdown(["Professional & Confident","Friendly & Conversational","Persuasive & Client-Focused","Creative & Narrative-Driven","Analytical & Problem-Solver"],value="Professional & Confident",label="Tone")
709
+ uploader = gr.File(label="Upload Files", file_types=[".pdf"], file_count="multiple")
710
+ file_list = gr.List(label="Files in Database", value=refresh_file_list())
711
+ # -------- Event Bindings --------
712
+
713
+ uploader.change(upload_files, inputs=uploader, outputs=file_list)
714
+ submit_btn.click(
715
+ fn=generate_proposal,
716
+ inputs=[job_desc, instructions, tone_selector, conversation, thread],
717
+ outputs=[conversation,saved_state]
718
+ )
719
+ refresh_btn.click(
720
+ fn=reset,
721
+ inputs=[thread],
722
+ outputs=[instructions, job_desc, conversation, uploader, tone_selector, thread]
723
+ )
724
+ finish_btn.click(
725
+ fn=finish_session,
726
+ inputs=[thread,saved_state],
727
+ outputs=[]
728
+ )
729
+
730
+
731
+ if __name__ == "__main__":
732
+ demo.launch(
733
+ server_name="0.0.0.0",
734
+ server_port=int(os.environ.get("PORT", 7860))
735
+ )
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "fastapi>=0.102",
2
+ "uvicorn[standard]>=0.23",
3
+ "python-dotenv>=1.0.0",
4
+ "supabase>=1.0.0",
5
+ "PyMuPDF>=1.22.5",
6
+ "gradio>=3.41",
7
+ "langchain>=0.1.0",
8
+ "langgraph>=0.1.0",
9
+ "typing-extensions>=4.7",
10
+ "pydantic>=2.5",
11
+ "dotenv>=0.9.9",
12
+ "langchain-openai>=0.3.31",
13
+ "ipython>=9.4.0",