CoolFace
Modelpublic

Prathmesh0001/interview-system

sourceHugging Facemitupdated 8mo agoView on Hugging Face
0likes
document_parser.py148 linesDownload Raw Back to root
1"""
2Document Parser Module
3Extracts text from PDF and DOCX files for resume and job description processing
4"""
5
6import PyPDF2
7import docx
8import os
9from typing import Optional
10
11
12class DocumentParser:
13    """Parse and extract text from various document formats"""
14    
15    def __init__(self):
16        self.supported_formats = ['.pdf', '.docx', '.txt']
17    
18    def parse_document(self, file_path: str) -> Optional[str]:
19        """
20        Parse document and extract text content
21        
22        Args:
23            file_path: Path to the document file
24            
25        Returns:
26            Extracted text or None if parsing fails
27        """
28        if not os.path.exists(file_path):
29            print(f"Error: File not found - {file_path}")
30            return None
31        
32        file_ext = os.path.splitext(file_path)[1].lower()
33        
34        if file_ext not in self.supported_formats:
35            print(f"Error: Unsupported file format - {file_ext}")
36            return None
37        
38        try:
39            if file_ext == '.pdf':
40                return self._parse_pdf(file_path)
41            elif file_ext == '.docx':
42                return self._parse_docx(file_path)
43            elif file_ext == '.txt':
44                return self._parse_txt(file_path)
45        except Exception as e:
46            print(f"Error parsing document: {e}")
47            return None
48    
49    def _parse_pdf(self, file_path: str) -> str:
50        """Extract text from PDF file"""
51        text = ""
52        try:
53            with open(file_path, 'rb') as file:
54                pdf_reader = PyPDF2.PdfReader(file)
55                for page in pdf_reader.pages:
56                    text += page.extract_text() + "\n"
57        except Exception as e:
58            print(f"Error reading PDF: {e}")
59            raise
60        return text.strip()
61    
62    def _parse_docx(self, file_path: str) -> str:
63        """Extract text from DOCX file"""
64        try:
65            doc = docx.Document(file_path)
66            text = "\n".join([paragraph.text for paragraph in doc.paragraphs])
67        except Exception as e:
68            print(f"Error reading DOCX: {e}")
69            raise
70        return text.strip()
71    
72    def _parse_txt(self, file_path: str) -> str:
73        """Extract text from TXT file"""
74        try:
75            with open(file_path, 'r', encoding='utf-8') as file:
76                text = file.read()
77        except Exception as e:
78            print(f"Error reading TXT: {e}")
79            raise
80        return text.strip()
81    
82    def extract_key_information(self, text: str, doc_type: str) -> dict:
83        """
84        Extract key information from document text
85        
86        Args:
87            text: Document text
88            doc_type: 'resume' or 'job_description'
89            
90        Returns:
91            Dictionary with extracted information
92        """
93        info = {
94            'full_text': text,
95            'word_count': len(text.split()),
96            'char_count': len(text)
97        }
98        
99        # Basic keyword extraction (can be enhanced with NLP)
100        if doc_type == 'resume':
101            info['type'] = 'resume'
102            # Look for common resume sections
103            info['has_experience'] = any(keyword in text.lower() for keyword in 
104                                        ['experience', 'work history', 'employment'])
105            info['has_education'] = any(keyword in text.lower() for keyword in 
106                                       ['education', 'degree', 'university'])
107            info['has_skills'] = 'skills' in text.lower()
108            
109        elif doc_type == 'job_description':
110            info['type'] = 'job_description'
111            # Look for common JD sections
112            info['has_requirements'] = any(keyword in text.lower() for keyword in 
113                                          ['requirements', 'qualifications', 'required'])
114            info['has_responsibilities'] = any(keyword in text.lower() for keyword in 
115                                              ['responsibilities', 'duties', 'role'])
116        
117        return info
118
119
120if __name__ == "__main__":
121    # Test the document parser
122    parser = DocumentParser()
123    
124    print("Document Parser Module - Test Mode")
125    print("=" * 50)
126    print("\nSupported formats:", parser.supported_formats)
127    
128    # Example usage
129    test_text = """
130    Senior Software Engineer
131    
132    Experience:
133    - 5 years in Python development
134    - Machine Learning expertise
135    - Full-stack development
136    
137    Education:
138    - BS Computer Science
139    
140    Skills:
141    - Python, TensorFlow, React
142    """
143    
144    info = parser.extract_key_information(test_text, 'resume')
145    print("\nExtracted Information:")
146    for key, value in info.items():
147        if key != 'full_text':
148            print(f"  {key}: {value}")