Spaces:
Sleeping
Sleeping
Download app/services/summarizer.py from HFShishir/tech-updates: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/spaces/HFShishir/tech-updates/resolve/main/app/services/summarizer.py
- Command line
-
hf download hf://spaces/HFShishir/tech-updates/app/services/summarizer.py
-
curl -L -o summarizer.py https://huggingface.co/spaces/HFShishir/tech-updates/resolve/main/app/services/summarizer.py
15.2 kB
| import logging | |
| import json | |
| import re | |
| from typing import List, Dict, Any, Tuple | |
| from langchain_text_splitters import RecursiveCharacterTextSplitter | |
| from app.config import settings | |
| logger = logging.getLogger(__name__) | |
| # Initialize Text Splitter for chunking article content | |
| text_splitter = RecursiveCharacterTextSplitter( | |
| chunk_size=1000, | |
| chunk_overlap=100, | |
| length_function=len | |
| ) | |
| def mock_summarize_item(raw_item: Dict[str, Any]) -> Dict[str, Any]: | |
| """ | |
| Fallback deterministic summarizer when LLM API keys are not provided. | |
| """ | |
| title = raw_item.get("title", "") | |
| source = raw_item.get("source", "Tech") | |
| content = raw_item.get("raw_content", "") | |
| # Split text into chunks using Text Splitter | |
| chunks = text_splitter.split_text(content) | |
| processed_content = " ".join(chunks[:2]) if chunks else content | |
| category = "AI & ML" if any(k in title.lower() or k in processed_content.lower() for k in ["ai", "llm", "gpt", "model", "neural", "agent"]) else \ | |
| "Open Source" if "github" in source.lower() or "repo" in title.lower() else \ | |
| "Developer Tools" if any(k in title.lower() for k in ["tool", "framework", "library", "code", "dev"]) else \ | |
| "Tech News" | |
| summary_en = f"{title}. Key updates reported via {source} highlighting developments in modern software and technology infrastructure." | |
| summary_bn = f"{title}। {source}-এর মাধ্যমে প্রকাশিত সফটওয়্যার ও প্রযুক্তি খাতের গুরুত্বপূর্ণ আপডেট।" | |
| key_takeaway_en = f"Stay informed on {category} shifts and implications for software engineering workflows." | |
| key_takeaway_bn = f"{category} সেক্টরের এই পরিবর্তন সফটওয়্যার ডেভলপমেন্টে গুরুত্বপূর্ণ প্রভাব ফেলবে।" | |
| return { | |
| "title": title, | |
| "url": raw_item.get("url", ""), | |
| "source": source, | |
| "category": category, | |
| "summary": summary_en, | |
| "summary_en": summary_en, | |
| "summary_bn": summary_bn, | |
| "key_takeaway": key_takeaway_en, | |
| "key_takeaway_en": key_takeaway_en, | |
| "key_takeaway_bn": key_takeaway_bn, | |
| "importance_score": 8.0 if category == "AI & ML" else 7.0, | |
| "text_chunks": chunks | |
| } | |
| async def process_and_summarize_updates(raw_items: List[Dict[str, Any]]) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: | |
| """ | |
| Processes a list of raw tech news items using LangChain Text Splitter & Gemini LLM into Dual-Language (EN & BN). | |
| Returns: (overall_digest_metadata, processed_items_list) | |
| """ | |
| processed_items = [] | |
| llm = None | |
| if settings.PREFERRED_LLM_PROVIDER == "gemini" and settings.GOOGLE_API_KEY: | |
| try: | |
| from langchain_google_genai import ChatGoogleGenerativeAI | |
| llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash", google_api_key=settings.GOOGLE_API_KEY, temperature=0.3) | |
| except Exception as e: | |
| logger.warning(f"Could not initialize Gemini LLM: {e}") | |
| elif settings.PREFERRED_LLM_PROVIDER == "openai" and settings.OPENAI_API_KEY: | |
| try: | |
| from langchain_openai import ChatOpenAI | |
| llm = ChatOpenAI(model="gpt-3.5-turbo", openai_api_key=settings.OPENAI_API_KEY, temperature=0.3) | |
| except Exception as e: | |
| logger.warning(f"Could not initialize OpenAI LLM: {e}") | |
| for item in raw_items: | |
| raw_text = item.get("raw_content", "") | |
| chunks = text_splitter.split_text(raw_text) if raw_text else [item.get("title", "")] | |
| context_for_llm = "\n---\n".join(chunks[:3]) | |
| if llm: | |
| try: | |
| from langchain_core.prompts import PromptTemplate | |
| prompt = PromptTemplate.from_template( | |
| """You are an expert Bilingual AI Tech Analyst fluent in English and Bengali. | |
| Given the following tech news update, provide summaries and key takeaways in BOTH English and natural Bengali (বাংলা). | |
| Item Title: {title} | |
| Source: {source} | |
| Article Chunks: | |
| {chunks} | |
| Return ONLY a valid JSON object with keys: | |
| "category": "category string (e.g. AI & ML, Open Source, Developer Tools, CyberSecurity, Cloud, Mobile, Web)", | |
| "summary_en": "concise 2-sentence summary in English", | |
| "summary_bn": "concise 2-sentence summary in natural Bengali (বাংলা)", | |
| "key_takeaway_en": "key takeaway for software engineers in English", | |
| "key_takeaway_bn": "key takeaway for software engineers in natural Bengali (বাংলা)", | |
| "importance_score": float number from 1.0 to 10.0 | |
| """ | |
| ) | |
| chain = prompt | llm | |
| res = await chain.ainvoke({ | |
| "title": item.get("title"), | |
| "source": item.get("source"), | |
| "chunks": context_for_llm | |
| }) | |
| content_text = res.content if hasattr(res, "content") else str(res) | |
| clean_json = re.sub(r'```json\s*|\s*```', '', content_text).strip() | |
| parsed = json.loads(clean_json) | |
| processed_items.append({ | |
| "title": item.get("title"), | |
| "url": item.get("url"), | |
| "source": item.get("source"), | |
| "category": parsed.get("category", "Tech"), | |
| "summary": parsed.get("summary_en", item.get("title")), | |
| "summary_en": parsed.get("summary_en", item.get("title")), | |
| "summary_bn": parsed.get("summary_bn", item.get("title")), | |
| "key_takeaway": parsed.get("key_takeaway_en", ""), | |
| "key_takeaway_en": parsed.get("key_takeaway_en", ""), | |
| "key_takeaway_bn": parsed.get("key_takeaway_bn", ""), | |
| "importance_score": float(parsed.get("importance_score", 7.0)), | |
| "text_chunks": chunks | |
| }) | |
| except Exception as parse_err: | |
| logger.warning(f"LLM processing failed for item '{item.get('title')}': {parse_err}, using fallback") | |
| processed_items.append(mock_summarize_item(item)) | |
| else: | |
| processed_items.append(mock_summarize_item(item)) | |
| # Overall Daily Digest Summary | |
| top_items_titles = [it["title"] for it in sorted(processed_items, key=lambda x: x["importance_score"], reverse=True)[:3]] | |
| overall_digest = { | |
| "title": f"BytePulse AI Digest - Top {len(processed_items)} Updates", | |
| "overall_summary": f"Today's tech roundup highlights top developments across AI & ML, Open Source, and Developer Ecosystems. Today's top AI insights ready in English & Bengali (বাংলা).", | |
| "top_highlights": json.dumps(top_items_titles) | |
| } | |
| return overall_digest, processed_items | |
| async def generate_deep_ai_analysis(title: str, source: str, summary: str, text_chunks: List[str]) -> Dict[str, Any]: | |
| """ | |
| Generates bilingual in-depth AI breakdown for the 'Read More' full article view using Gemini LLM. | |
| """ | |
| llm = None | |
| if settings.PREFERRED_LLM_PROVIDER == "gemini" and settings.GOOGLE_API_KEY: | |
| try: | |
| from langchain_google_genai import ChatGoogleGenerativeAI | |
| llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash", google_api_key=settings.GOOGLE_API_KEY, temperature=0.3) | |
| except Exception as e: | |
| logger.warning(f"Could not initialize Gemini for Deep Analysis: {e}") | |
| context_str = "\n---\n".join(text_chunks) if text_chunks else summary | |
| if llm: | |
| try: | |
| from langchain_core.prompts import PromptTemplate | |
| prompt = PromptTemplate.from_template( | |
| """You are an elite Senior Principal Software Architect and AI Engineer fluent in English and Bengali. | |
| Provide a comprehensive technical deep-dive analysis in BOTH English and Bengali (বাংলা) for this tech article. | |
| Title: {title} | |
| Source: {source} | |
| Summary: {summary} | |
| Content Chunks: | |
| {context} | |
| Return ONLY a valid JSON object with keys: | |
| "architectural_impact_en": "engineering implications in English", | |
| "architectural_impact_bn": "engineering implications in natural Bengali (বাংলা)", | |
| "key_takeaways_en": ["point 1 in EN", "point 2 in EN"], | |
| "key_takeaways_bn": ["point 1 in Bengali", "point 2 in Bengali"], | |
| "pros_en": ["pro 1 in EN", "pro 2 in EN"], | |
| "pros_bn": ["pro 1 in Bengali", "pro 2 in Bengali"], | |
| "cons_en": ["con 1 in EN", "con 2 in EN"], | |
| "cons_bn": ["con 1 in Bengali", "con 2 in Bengali"], | |
| "actionable_advice_en": "developer action item in English", | |
| "actionable_advice_bn": "developer action item in Bengali (বাংলা)" | |
| """ | |
| ) | |
| chain = prompt | llm | |
| res = await chain.ainvoke({"title": title, "source": source, "summary": summary, "context": context_str}) | |
| content_text = res.content if hasattr(res, "content") else str(res) | |
| clean_json = re.sub(r'```json\s*|\s*```', '', content_text).strip() | |
| return json.loads(clean_json) | |
| except Exception as err: | |
| logger.warning(f"Deep AI analysis failed: {err}, falling back to default structured breakdown") | |
| return { | |
| "architectural_impact_en": f"The developments in '{title}' present key considerations for system scalability, modern software design, and API integration workflows.", | |
| "architectural_impact_bn": f"'{title}'-এর এই প্রযুক্তিগত অগ্রগতি সিস্টেমের স্কেলেবিলিটি এবং ডেভলপমেন্ট ওয়ার্কফ্লোতে গুরুত্বপূর্ণ ভূমিকা রাখবে।", | |
| "key_takeaways_en": [ | |
| f"Review current codebase compatibility with {source} updates.", | |
| "Assess team adoption timeline for new tooling and frameworks." | |
| ], | |
| "key_takeaways_bn": [ | |
| f"কোডবেসের সাথে {source}-এর নতুন আপডেটের সামঞ্জস্যতা পরীক্ষা করুন।", | |
| "টিমের নতুন টুলস গ্রহণের সময়সীমা নির্ধারণ করুন।" | |
| ], | |
| "pros_en": ["Enhanced performance & efficiency", "Streamlined developer experience"], | |
| "pros_bn": ["উন্নত পারফরম্যান্স ও দক্ষতা", "সহজ ডেভলপার এক্সপেরিয়েন্স"], | |
| "cons_en": ["Potential migration effort required"], | |
| "cons_bn": ["মাইগ্রেশনের জন্য অতিরিক্ত সময়ের প্রয়োজন হতে পারে"], | |
| "actionable_advice_en": "Evaluate this update in a staging environment before rolling out to production systems.", | |
| "actionable_advice_bn": "প্রোডাকশন সিস্টেমে ব্যবহারের আগে স্টেজিং এনভাইরনমেন্টে পরীক্ষা করে দেখুন।" | |
| } | |
| async def generate_social_media_posts(title: str, source: str, summary: str, key_takeaway: str = "") -> Dict[str, Any]: | |
| """ | |
| Generates ready-to-share social media post ideas in both English and Bengali using Gemini LLM. | |
| """ | |
| llm = None | |
| if settings.PREFERRED_LLM_PROVIDER == "gemini" and settings.GOOGLE_API_KEY: | |
| try: | |
| from langchain_google_genai import ChatGoogleGenerativeAI | |
| llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash", google_api_key=settings.GOOGLE_API_KEY, temperature=0.5) | |
| except Exception as e: | |
| logger.warning(f"Could not initialize Gemini for Social Post generation: {e}") | |
| if llm: | |
| try: | |
| from langchain_core.prompts import PromptTemplate | |
| prompt = PromptTemplate.from_template( | |
| """You are a top 1% Tech Influencer, Developer Advocate, and Technical Content Strategist fluent in English and Bengali. | |
| Create high-engagement social media posts in BOTH English and Bengali based on this tech update: | |
| Title: {title} | |
| Source: {source} | |
| Summary: {summary} | |
| Takeaway: {takeaway} | |
| Return ONLY a valid JSON object with keys: | |
| "linkedin_en": "LinkedIn post in English with hook, bullet points, CTA and hashtags", | |
| "linkedin_bn": "LinkedIn post in natural Bengali (বাংলা) for developers with hook, bullets, CTA and hashtags", | |
| "twitter_en": "3-tweet Twitter/X thread in English", | |
| "twitter_bn": "3-tweet Twitter/X thread in Bengali (বাংলা)", | |
| "newsletter_en": "1-paragraph tech newsletter summary in English", | |
| "newsletter_bn": "1-paragraph tech newsletter summary in Bengali (বাংলা)", | |
| "reddit_en": "Reddit discussion post in English", | |
| "reddit_bn": "Reddit discussion post in Bengali (বাংলা)" | |
| """ | |
| ) | |
| chain = prompt | llm | |
| res = await chain.ainvoke({"title": title, "source": source, "summary": summary, "takeaway": key_takeaway or summary}) | |
| content_text = res.content if hasattr(res, "content") else str(res) | |
| clean_json = re.sub(r'```json\s*|\s*```', '', content_text).strip() | |
| parsed = json.loads(clean_json) | |
| # Backwards compatibility keys | |
| parsed["linkedin"] = parsed.get("linkedin_en") | |
| parsed["twitter"] = parsed.get("twitter_en") | |
| parsed["newsletter"] = parsed.get("newsletter_en") | |
| parsed["reddit"] = parsed.get("reddit_en") | |
| return parsed | |
| except Exception as err: | |
| logger.warning(f"Social post generation failed: {err}, using fallback post templates") | |
| return { | |
| "linkedin_en": f"🚀 Huge update in Tech! {title}\n\nKey Highlights:\n• {summary}\n\n#SoftwareEngineering #TechNews #DevCommunity", | |
| "linkedin_bn": f"🚀 টেক ওয়ার্ল্ডে বিশাল আপডেট! {title}\n\nমূল পয়েন্ট:\n• {summary}\n\nআপনার মতামত কি? কমেন্টে জানান! 👇\n\n#TechNewsBangla #SoftwareEngineering #DevCommunity", | |
| "twitter_en": f"1/3 🚨 Tech Update: {title}\n\nSummary: {summary[:120]}...\n\n2/3 💡 Takeaway: {key_takeaway[:120]}\n\n3/3 What do you think?", | |
| "twitter_bn": f"1/3 🚨 টেক আপডেট: {title}\n\nসামারি: {summary[:120]}...\n\n2/3 💡 টেকঅ্যাওয়ে: {key_takeaway[:120]}\n\n3/3 আপনার কি মতামত?", | |
| "newsletter_en": f"📌 **{title}**: {summary} {key_takeaway}", | |
| "newsletter_bn": f"📌 **{title}**: {summary} {key_takeaway}", | |
| "reddit_en": f"**[Discussion] {title}**\n\n{summary}", | |
| "reddit_bn": f"**[আলোচনা] {title}**\n\n{summary}", | |
| "linkedin": f"🚀 Huge update in Tech! {title}\n\nKey Highlights:\n• {summary}", | |
| "twitter": f"1/3 🚨 Tech Update: {title}", | |
| "newsletter": f"📌 **{title}**: {summary}", | |
| "reddit": f"**[Discussion] {title}**\n\n{summary}" | |
| } | |