perplexity-hackathon-LawMitra / perplexity_hackathon / src / services / simplificationService.ts
simplificationService.ts
Raw
import OpenAI from 'openai';

export interface SimplifiedResponse {
  text: string;
  readingLevel: string;
  originalLength: number;
  simplifiedLength: number;
}

export class SimplificationService {
  private readonly openai: OpenAI;

  constructor() {
    const apiKey = process.env.OPENAI_API_KEY;
    if (!apiKey) {
      throw new Error('OPENAI_API_KEY environment variable is not set');
    }
    this.openai = new OpenAI({ apiKey });
  }

  async simplifyText(text: string): Promise<SimplifiedResponse> {
    try {
      const response = await this.openai.chat.completions.create({
        model: 'gpt-4',
        messages: [
          {
            role: 'system',
            content: 'You are a text simplification expert. Your task is to simplify complex text while maintaining its core meaning. Aim for a 6th-grade reading level.'
          },
          {
            role: 'user',
            content: `Please simplify this text: ${text}`
          }
        ],
        temperature: 0.7,
      });

      const simplifiedText = response.choices[0].message.content || '';
      const readingLevel = this.estimateReadingLevel(simplifiedText);

      return {
        text: simplifiedText,
        readingLevel,
        originalLength: text.length,
        simplifiedLength: simplifiedText.length
      };
    } catch (error) {
      console.error('Error simplifying text:', error);
      throw new Error('Failed to simplify text');
    }
  }

  private estimateReadingLevel(text: string): string {
    // Simple estimation based on average word length and sentence length
    const words = text.split(/\s+/);
    const sentences = text.split(/[.!?]+/);
    
    const avgWordLength = words.join('').length / words.length;
    const avgSentenceLength = words.length / sentences.length;
    
    if (avgWordLength > 5.5 || avgSentenceLength > 20) {
      return 'High School';
    } else if (avgWordLength > 4.5 || avgSentenceLength > 15) {
      return 'Middle School';
    } else {
      return 'Elementary';
    }
  }
}