sandylolpotty commited on
Commit
ac68caa
·
verified ·
1 Parent(s): c9d4d70

Create granite_model.py

Browse files
Files changed (1) hide show
  1. granite_model.py +124 -0
granite_model.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Example of how to integrate the granite_model.py into your main app.py
2
+
3
+ # At the top of your app.py, add this import:
4
+ # Use a pipeline as a high-level helper
5
+ from transformers import pipeline
6
+
7
+ pipe = pipeline("text-generation", model="ibm-granite/granite-3.3-8b-instruct")
8
+ messages = [
9
+ {"role": "user", "content": "Who are you?"},
10
+ ]
11
+ pipe(messages)
12
+ try:
13
+ from granite_model import GraniteModelIntegration
14
+ GRANITE_AVAILABLE = True
15
+ except ImportError:
16
+ GRANITE_AVAILABLE = False
17
+ logger.warning("granite_model.py not found. Granite features will be disabled.")
18
+
19
+ # In your AdvancedDocumentSummarizer.__init__ method, add:
20
+ def __init__(self):
21
+ self.summarizer = None
22
+ self.sentiment_analyzer = None
23
+ self.granite_integration = None # Add this line
24
+ self.cache = {}
25
+
26
+ # Initialize AI models
27
+ if TRANSFORMERS_AVAILABLE:
28
+ self._initialize_ai_models()
29
+
30
+ # Initialize Granite integration
31
+ if GRANITE_AVAILABLE:
32
+ try:
33
+ self.granite_integration = GraniteModelIntegration()
34
+ logger.info(f"Granite integration status: {'Available' if self.granite_integration.is_available() else 'Not Available'}")
35
+ except Exception as e:
36
+ logger.warning(f"Failed to initialize Granite integration: {e}")
37
+
38
+ # Initialize sentiment analyzer
39
+ if NLTK_AVAILABLE:
40
+ try:
41
+ self.sentiment_analyzer = SentimentIntensityAnalyzer()
42
+ except Exception as e:
43
+ logger.warning(f"Failed to initialize sentiment analyzer: {e}")
44
+
45
+ # Add these methods to your AdvancedDocumentSummarizer class:
46
+ def granite_enhanced_summary(self, text: str, summary_type: str = "medium") -> str:
47
+ """Generate enhanced summary using Granite model"""
48
+ if not (self.granite_integration and self.granite_integration.is_available()):
49
+ return self.advanced_extractive_summary(text)
50
+
51
+ return self.granite_integration.generate_summary(text, summary_type)
52
+
53
+ def granite_analyze_document(self, text: str) -> Dict:
54
+ """Use Granite model for advanced document analysis"""
55
+ if not (self.granite_integration and self.granite_integration.is_available()):
56
+ return {'analysis_available': False}
57
+
58
+ result = self.granite_integration.analyze_document(text)
59
+ return {
60
+ 'granite_analysis': result.get('analysis', 'Analysis failed'),
61
+ 'analysis_available': result.get('success', False),
62
+ 'model_used': result.get('model_used', 'Unknown')
63
+ }
64
+
65
+ def granite_generate_questions(self, text: str, num_questions: int = 5) -> list:
66
+ """Generate comprehension questions using Granite"""
67
+ if not (self.granite_integration and self.granite_integration.is_available()):
68
+ return []
69
+
70
+ return self.granite_integration.generate_questions(text, num_questions)
71
+
72
+ # In your process_document method, update the summary generation part:
73
+ # Generate summary - prioritize Granite if available for AI mode
74
+ if summary_type == "ai":
75
+ if self.granite_integration and self.granite_integration.is_available():
76
+ summary = self.granite_enhanced_summary(text, summary_length)
77
+ elif self.summarizer:
78
+ summary = self.ai_summary(text, params["max_length"], params["min_length"])
79
+ else:
80
+ summary = self.advanced_extractive_summary(text, params["sentences"])
81
+ else:
82
+ summary = self.advanced_extractive_summary(text, params["sentences"])
83
+
84
+ # Get Granite analysis and questions if available
85
+ granite_analysis = self.granite_analyze_document(text)
86
+ granite_questions = self.granite_generate_questions(text, 5)
87
+
88
+ # Add to result dictionary:
89
+ result = {
90
+ 'original_text': text[:2000] + "..." if len(text) > 2000 else text,
91
+ 'full_text_length': len(text),
92
+ 'summary': summary,
93
+ 'key_points': key_points,
94
+ 'outline': outline,
95
+ 'stats': stats,
96
+ 'granite_analysis': granite_analysis,
97
+ 'granite_questions': granite_questions, # Add this
98
+ 'readability_score': readability_score,
99
+ 'file_name': Path(file_path).name,
100
+ 'file_size': os.path.getsize(file_path),
101
+ 'processing_time': datetime.now().isoformat(),
102
+ 'summary_type': summary_type,
103
+ 'summary_length': summary_length,
104
+ 'model_used': 'Granite 3.2 8B' if (summary_type == "ai" and self.granite_integration and self.granite_integration.is_available()) else ('AI (BART/T5)' if self.summarizer else 'Extractive')
105
+ }
106
+
107
+ # In your UI section, add the questions display:
108
+ # Add Granite questions if available
109
+ granite_questions_html = ""
110
+ if result.get("granite_questions"):
111
+ questions_list = "".join([f"<li style='margin-bottom: 10px; padding: 8px; background: rgba(255,255,255,0.1); border-radius: 6px;'>{q}</li>"
112
+ for q in result["granite_questions"]])
113
+ granite_questions_html = f'''
114
+ <div style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; padding: 20px; border-radius: 12px; margin: 15px 0; box-shadow: 0 6px 20px rgba(0,0,0,0.1);">
115
+ <h3>AI-Generated Questions</h3>
116
+ <p style="margin-bottom: 15px; opacity: 0.9;">Test your understanding with these Granite-generated questions:</p>
117
+ <ol style="padding-left: 20px; line-height: 1.6;">
118
+ {questions_list}
119
+ </ol>
120
+ </div>
121
+ '''
122
+
123
+ # Update your system status display:
124
+ **Granite 3.2 8B:** {"✅ Available" if (GRANITE_AVAILABLE and hasattr(summarizer, 'granite_integration') and summarizer.granite_integration and summarizer.granite_integration.is_available()) else "❌ Not Available"}