metadata_enhancer.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. import re
  2. import json
  3. from typing import Dict, List, Optional
  4. import logging
  5. from .deepseek_client import DeepSeekClient
  6. from .config import config
  7. logger = logging.getLogger(__name__)
  8. class MetadataEnhancer:
  9. """Metadata täiustamine DeepSeeki abil"""
  10. def __init__(self):
  11. self.deepseek_client = DeepSeekClient()
  12. def enhance_metadata_with_ai(self, text: str, current_metadata: Dict) -> Dict:
  13. """
  14. Täiusta metainfot DeepSeeki abil
  15. Args:
  16. text: Artikli tekst (esimesed ~4000 märki)
  17. current_metadata: Olemasolev metadata
  18. Returns:
  19. Täiustatud metadata
  20. """
  21. logger.info("Täiustan metainfot DeepSeeki abil...")
  22. system_prompt = """Sa oled teadusartiklite metainfo spetsialist.
  23. Sinu ülesanne on tuvastada antud teadusartikli õige pealkiri, autorid, avaldamisaasta,
  24. žurnaal ja DOI.
  25. Tagasta vastus JSON formaadis:
  26. {
  27. "title": "õige pealkiri",
  28. "authors": ["autor1", "autor2", ...],
  29. "year": "avaldamisaasta",
  30. "journal": "žurnaal/konverentsi nimetus",
  31. "doi": "DOI identifikaator"
  32. }
  33. Kui mõni väli on tuvastamata, jäta see tühjaks.
  34. Auta valesti tuvastatud väärtusi parandada.
  35. """
  36. user_prompt = f"""Tuvasta järgmise teadusartikli metainfo:
  37. CURRENT METADATA:
  38. - Pealkiri: {current_metadata.get('title', 'Teadmata')}
  39. - Autorid: {current_metadata.get('authors', [])}
  40. - Aasta: {current_metadata.get('year', 'Teadmata')}
  41. - Žurnaal: {current_metadata.get('journal', 'Teadmata')}
  42. - DOI: {current_metadata.get('doi', 'Teadmata')}
  43. ARTIKLI TEKST (esimesed 4000 märki):
  44. {text[:4000]}
  45. Palun analüüsi artiklit ja paranda või täienda metainfot. Tagasta VAID JSON.
  46. """
  47. messages = [
  48. {"role": "system", "content": system_prompt},
  49. {"role": "user", "content": user_prompt}
  50. ]
  51. try:
  52. response = self.deepseek_client.call_api(messages, temperature=0.3)
  53. # Proovi parsida JSON vastust
  54. if response:
  55. # Otsi JSON blokki tekstist
  56. json_match = re.search(r'\{.*\}', response, re.DOTALL)
  57. if json_match:
  58. json_str = json_match.group(0)
  59. try:
  60. enhanced_data = json.loads(json_str)
  61. # Valideeri ja puhasta andmed
  62. enhanced_data = self._clean_enhanced_metadata(enhanced_data, current_metadata)
  63. logger.info(f"Metainfo täiustatud AI-ga")
  64. return enhanced_data
  65. except json.JSONDecodeError as e:
  66. logger.error(f"JSON parsimise viga: {e}")
  67. else:
  68. logger.error(f"Ei leidnud JSON-i vastuses: {response[:200]}")
  69. except Exception as e:
  70. logger.error(f"Viga AI metainfo täiustamisel: {e}")
  71. # Kui AI ei tööta, tagasta algne
  72. return current_metadata
  73. def _clean_enhanced_metadata(self, enhanced_data: Dict, original_data: Dict) -> Dict:
  74. """Puhasta ja valideeri täiustatud metadata"""
  75. cleaned = {}
  76. # Pealkiri
  77. title = enhanced_data.get('title', '').strip()
  78. if (title and
  79. len(title) > 10 and len(title) < 500 and
  80. not any(bad in title.lower() for bad in ['abstract', 'keywords', 'introduction', 'contents'])):
  81. cleaned['title'] = title
  82. else:
  83. cleaned['title'] = original_data.get('title', '')
  84. # Autorid
  85. authors = enhanced_data.get('authors', [])
  86. if isinstance(authors, list):
  87. cleaned_authors = []
  88. for author in authors:
  89. if isinstance(author, str):
  90. author_clean = author.strip()
  91. # Eemalda ebareaalsed autorid
  92. if (len(author_clean) > 2 and len(author_clean) < 100 and
  93. not any(char.isdigit() for char in author_clean) and
  94. not '@' in author_clean and
  95. not 'university' in author_clean.lower() and
  96. not 'institute' in author_clean.lower()):
  97. cleaned_authors.append(author_clean)
  98. if cleaned_authors:
  99. cleaned['authors'] = cleaned_authors
  100. else:
  101. cleaned['authors'] = original_data.get('authors', [])
  102. else:
  103. cleaned['authors'] = original_data.get('authors', [])
  104. # Aasta
  105. year = str(enhanced_data.get('year', '')).strip()
  106. if year.isdigit() and 1900 <= int(year) <= 2025:
  107. cleaned['year'] = year
  108. else:
  109. cleaned['year'] = original_data.get('year', '')
  110. # Žurnaal
  111. journal = enhanced_data.get('journal', '').strip()
  112. if journal and len(journal) < 200:
  113. cleaned['journal'] = journal
  114. else:
  115. cleaned['journal'] = original_data.get('journal', '')
  116. # DOI
  117. doi = enhanced_data.get('doi', '').strip()
  118. if doi and (doi.startswith('10.') or 'doi.org' in doi):
  119. cleaned['doi'] = doi
  120. else:
  121. cleaned['doi'] = original_data.get('doi', '')
  122. return cleaned
  123. def extract_metadata_directly(self, text: str) -> Dict:
  124. """
  125. Otsi metainfot otse tekstist ilma kontekstita
  126. Kasulik, kui algne metadata on täiesti valesti
  127. """
  128. logger.info("Otsin metainfot otse tekstist...")
  129. system_prompt = """Otsi antud teadusartikli tekstist pealkirja, autoreid,
  130. avaldamisaastat, žurnaali ja DOI-d. Tagasta tulemus JSON formaadis.
  131. """
  132. user_prompt = f"""Artikli tekst (esimesed 3000 märki):
  133. {text[:3000]}
  134. Palun otsi metainfot. Tagasta VAID JSON.
  135. """
  136. messages = [
  137. {"role": "system", "content": system_prompt},
  138. {"role": "user", "content": user_prompt}
  139. ]
  140. try:
  141. response = self.deepseek_client.call_api(messages, temperature=0.3)
  142. if response:
  143. json_match = re.search(r'\{.*\}', response, re.DOTALL)
  144. if json_match:
  145. json_str = json_match.group(0)
  146. try:
  147. metadata = json.loads(json_str)
  148. return self._clean_enhanced_metadata(metadata, {})
  149. except:
  150. pass
  151. except Exception as e:
  152. logger.error(f"Viga otse metainfo eraldamisel: {e}")
  153. return {}
  154. def is_metadata_valid(self, metadata: Dict) -> bool:
  155. """Kontrolli, kas metadata on usaldusväärne"""
  156. # Kontrolli pealkirja
  157. title = metadata.get('title', '')
  158. if not title or len(title) < 5 or len(title) > 500:
  159. return False
  160. # Kontrolli autoreid
  161. authors = metadata.get('authors', [])
  162. if not authors:
  163. return False
  164. # Kontrolli, et autorid ei oleks aadressid või muud jama
  165. for author in authors:
  166. if (len(author) > 100 or
  167. any(char.isdigit() for char in author) or
  168. '@' in author or
  169. 'university' in author.lower() or
  170. 'institute' in author.lower()):
  171. return False
  172. # Kontrolli aastat
  173. year = str(metadata.get('year', ''))
  174. if not year.isdigit() or not (1900 <= int(year) <= 2025):
  175. return False
  176. return True