Update main.py
This commit is contained in:
@@ -1,37 +1,63 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Simple utility to convert a raw text file into a flat JSON card.
|
||||
The input format is assumed to be a plain text where each line contains a key and value separated by a colon.
|
||||
Example:
|
||||
title: My Card
|
||||
description: This is a test.
|
||||
tags: python, example
|
||||
Simple module that converts informal assignment description into a structured data card.
|
||||
|
||||
The output will be a JSON object with the extracted fields.
|
||||
Usage:
|
||||
from main import parse_assignment
|
||||
card = parse_assignment("Write an essay on climate change by next Friday")
|
||||
"""
|
||||
import json
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any
|
||||
|
||||
def parse_raw_text(text: str) -> dict:
|
||||
card = {}
|
||||
for line in text.splitlines():
|
||||
if not line.strip() or ':' not in line:
|
||||
continue
|
||||
key, value = line.split(':', 1)
|
||||
card[key.strip()] = value.strip()
|
||||
return card
|
||||
from langchain.output_parsers import PydanticOutputParser
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Convert raw text to flat JSON card")
|
||||
parser.add_argument("input", type=Path, help="Input raw text file")
|
||||
parser.add_argument("output", type=Path, help="Output JSON file")
|
||||
args = parser.parse_args()
|
||||
class AssignmentCard(BaseModel):
|
||||
title: str = Field(..., description="Short title of the assignment")
|
||||
subject: str | None = Field(None, description="Subject or topic of the assignment")
|
||||
deadline_hint: str | None = Field(
|
||||
None,
|
||||
description="Human‑readable hint about when the assignment is due",
|
||||
)
|
||||
deliverable_type: str | None = Field(
|
||||
None,
|
||||
description="What kind of work should be submitted (essay, report, code, etc.)",
|
||||
)
|
||||
grading_hints: str | None = Field(
|
||||
None,
|
||||
description="Any hints about how the assignment will be graded",
|
||||
)
|
||||
|
||||
input_text = args.input.read_text(encoding='utf-8')
|
||||
card = parse_raw_text(input_text)
|
||||
args.output.write_text(json.dumps(card, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
print(f"Card written to {args.output}")
|
||||
parser = PydanticOutputParser(pydantic_object=AssignmentCard)
|
||||
|
||||
# Prompt template that asks the model to output JSON matching AssignmentCard
|
||||
PROMPT_TEMPLATE = (
|
||||
"You are an assistant that converts a short informal description of a study assignment into a structured data card."
|
||||
" Return only valid JSON that matches the following schema:\n{schema}\n"
|
||||
" Description: {description}"
|
||||
)
|
||||
|
||||
def parse_assignment(description: str) -> AssignmentCard:
|
||||
"""Return an AssignmentCard parsed from the given description.
|
||||
|
||||
The function uses LangChain's PydanticOutputParser to enforce type safety.
|
||||
"""
|
||||
from langchain import PromptTemplate, LLMChain
|
||||
from langchain.chat_models import ChatOpenAI
|
||||
|
||||
# Use a small model for demonstration; replace with your own key if needed.
|
||||
llm = ChatOpenAI(temperature=0.2)
|
||||
prompt = PromptTemplate(
|
||||
input_variables=["description", "schema"],
|
||||
template=PROMPT_TEMPLATE,
|
||||
)
|
||||
chain = LLMChain(llm=llm, prompt=prompt, output_parser=parser)
|
||||
result = chain.run(description=description, schema=parser.get_format_instructions())
|
||||
return result
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
import sys
|
||||
if len(sys.argv) < 2:
|
||||
print("Usage: python main.py '<assignment description>'")
|
||||
sys.exit(1)
|
||||
desc = sys.argv[1]
|
||||
card = parse_assignment(desc)
|
||||
print(card.json(indent=4))
|
||||
|
||||
Reference in New Issue
Block a user