File size: 11,273 Bytes
1c7cefc
4624af3
5b77884
a9254a4
4624af3
 
5b77884
 
4624af3
 
 
 
1c7cefc
 
 
e9d9741
5b77884
 
a9254a4
 
 
 
 
 
e9d9741
 
 
 
679afad
 
 
 
 
 
 
e9d9741
 
679afad
5b77884
e9d9741
 
4624af3
 
679afad
 
 
4624af3
5b77884
4624af3
5b77884
 
 
 
 
4624af3
 
 
 
a9254a4
5b77884
 
 
 
 
 
 
e9d9741
 
5b77884
679afad
 
1252efa
679afad
 
 
 
e9d9741
 
 
5b77884
 
e9d9741
 
 
 
5b77884
e9d9741
5b77884
e9d9741
 
 
 
679afad
e9d9741
 
 
 
5b77884
679afad
e9d9741
 
5b77884
 
 
 
 
 
 
 
1252efa
 
5b77884
 
1252efa
 
 
 
 
 
 
5b77884
 
1252efa
 
5b77884
1252efa
 
 
 
 
 
 
 
 
5b77884
 
1252efa
5b77884
1252efa
5b77884
 
1252efa
 
 
 
 
 
 
 
 
5b77884
 
 
19e0629
5b77884
1252efa
5b77884
 
 
 
1252efa
5b77884
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1252efa
5b77884
 
 
 
 
 
 
 
 
 
 
1252efa
5b77884
 
 
679afad
 
 
 
 
4624af3
679afad
 
4624af3
679afad
 
 
4624af3
1c7cefc
679afad
5b77884
679afad
4624af3
679afad
 
4624af3
679afad
 
 
 
 
 
 
 
4624af3
 
1252efa
5b77884
679afad
4624af3
 
679afad
 
 
4624af3
 
679afad
 
4624af3
5b77884
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c7cefc
 
5b77884
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import os
import threading
import hashlib
import logging
import time
from datetime import datetime
from flask import Flask, render_template, request, jsonify
from rss_processor import fetch_rss_feeds, process_and_store_articles, download_from_hf_hub, upload_to_hf_hub, LOCAL_DB_DIR
from langchain.vectorstores import Chroma
from langchain.embeddings import HuggingFaceEmbeddings

app = Flask(__name__)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

loading_complete = True
last_update_time = time.time()
last_data_hash = None

def get_embedding_model():
    if not hasattr(get_embedding_model, "model"):
        get_embedding_model.model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
    return get_embedding_model.model

def get_vector_db():
    if not os.path.exists(LOCAL_DB_DIR):
        return None
    try:
        if not hasattr(get_vector_db, "db_instance"):
            get_vector_db.db_instance = Chroma(
                persist_directory=LOCAL_DB_DIR,
                embedding_function=get_embedding_model(),
                collection_name="news_articles"
            )
        return get_vector_db.db_instance
    except Exception as e:
        logger.error(f"Failed to load vector DB: {e}")
        if hasattr(get_vector_db, "db_instance"):
            delattr(get_vector_db, "db_instance")
        return None

def load_feeds_in_background():
    global loading_complete, last_update_time
    if not loading_complete:
        return
    loading_complete = False
    try:
        logger.info("Starting background RSS feed fetch")
        articles = fetch_rss_feeds()
        logger.info(f"Fetched {len(articles)} articles")
        process_and_store_articles(articles)
        last_update_time = time.time()
        logger.info("Background feed processing complete")
        upload_to_hf_hub()
    except Exception as e:
        logger.error(f"Error in background feed loading: {e}")
    finally:
        loading_complete = True

def get_all_docs_from_db():
    vector_db = get_vector_db()
    if not vector_db or vector_db._collection.count() == 0:
        return {'documents': [], 'metadatas': []}
    return vector_db.get(include=['documents', 'metadatas'])

def format_articles_from_db_results(docs):
    enriched_articles = []
    seen_keys = set()

    items = []
    if isinstance(docs, dict) and 'metadatas' in docs:
        items = zip(docs.get('documents', []), docs.get('metadatas', []))
    elif isinstance(docs, list):
        items = [(doc.page_content, doc.metadata) for doc, score in docs]

    for doc_content, meta in items:
        if not meta: continue
        title = meta.get("title", "No Title")
        link = meta.get("link", "")
        published = meta.get("published", "Unknown Date").strip()
        key = f"{title}|{link}|{published}"

        if key not in seen_keys:
            seen_keys.add(key)
            try:
                published_iso = datetime.strptime(published, "%Y-%m-%d %H:%M:%S").isoformat()
            except (ValueError, TypeError):
                published_iso = "1970-01-01T00:00:00"
            
            enriched_articles.append({
                "title": title,
                "link": link,
                "description": meta.get("original_description", "No Description"),
                "category": meta.get("category", "Uncategorized"),
                "published": published_iso,
                "image": meta.get("image", "svg"),
            })
    
    enriched_articles.sort(key=lambda x: x["published"], reverse=True)
    return enriched_articles

def compute_data_hash(categorized_articles):
    if not categorized_articles: return ""
    data_str = ""
    for cat, articles in sorted(categorized_articles.items()):
        for article in sorted(articles, key=lambda x: x["published"]):
            data_str += f"{cat}|{article['title']}|{article['link']}|{article['published']}|"
    return hashlib.sha256(data_str.encode('utf-8')).hexdigest()

@app.route('/')
def index():
    global loading_complete, last_update_time, last_data_hash

    if not os.path.exists(LOCAL_DB_DIR):
        logger.info(f"No Chroma DB found at '{LOCAL_DB_DIR}', downloading from Hugging Face Hub...")
        download_from_hf_hub()

    threading.Thread(target=load_feeds_in_background, daemon=True).start()

    try:
        all_docs = get_all_docs_from_db()
        if not all_docs['metadatas']:
            return render_template("index.html", categorized_articles={}, has_articles=False, loading=True)

        enriched_articles = format_articles_from_db_results(all_docs)
        
        categorized_articles = {}
        for article in enriched_articles:
            cat = article["category"]
            categorized_articles.setdefault(cat, []).append(article)
        
        categorized_articles = dict(sorted(categorized_articles.items()))
        for cat in categorized_articles:
            categorized_articles[cat] = categorized_articles[cat][:10]

        last_data_hash = compute_data_hash(categorized_articles)
        
        return render_template("index.html", categorized_articles=categorized_articles, has_articles=True, loading=not loading_complete)
    except Exception as e:
        logger.error(f"Error retrieving articles at startup: {e}", exc_info=True)
        return render_template("index.html", categorized_articles={}, has_articles=False, loading=True)

@app.route('/search', methods=['POST'])
def search():
    query = request.form.get('search')
    if not query:
        return jsonify({"categorized_articles": {}, "has_articles": False, "loading": False})

    vector_db = get_vector_db()
    if not vector_db:
        return jsonify({"categorized_articles": {}, "has_articles": False, "loading": False})
    
    try:
        results = vector_db.similarity_search_with_relevance_scores(query, k=50, score_threshold=0.5)
        enriched_articles = format_articles_from_db_results(results)

        categorized_articles = {}
        for article in enriched_articles:
            cat = article["category"]
            categorized_articles.setdefault(cat, []).append(article)

        return jsonify({
            "categorized_articles": categorized_articles,
            "has_articles": bool(enriched_articles),
            "loading": False
        })
    except Exception as e:
        logger.error(f"Semantic search error: {e}", exc_info=True)
        return jsonify({"categorized_articles": {}, "has_articles": False, "loading": False}), 500

@app.route('/get_all_articles/<category>')
def get_all_articles(category):
    try:
        all_docs = get_all_docs_from_db()
        enriched_articles = format_articles_from_db_results(all_docs)
        category_articles = [article for article in enriched_articles if article["category"] == category]
        return jsonify({"articles": category_articles, "category": category})
    except Exception as e:
        logger.error(f"Error fetching all articles for category {category}: {e}")
        return jsonify({"articles": [], "category": category}), 500

@app.route('/check_loading')
def check_loading():
    return jsonify({"status": "complete" if loading_complete else "loading", "last_update": last_update_time})

@app.route('/get_updates')
def get_updates():
    global last_update_time, last_data_hash
    try:
        all_docs = get_all_docs_from_db()
        if not all_docs['metadatas']:
            return jsonify({"articles": {}, "last_update": last_update_time, "has_updates": False})
        
        enriched_articles = format_articles_from_db_results(all_docs)
        categorized_articles = {}
        for article in enriched_articles:
            cat = article["category"]
            categorized_articles.setdefault(cat, []).append(article)
        
        for cat in categorized_articles:
            categorized_articles[cat] = categorized_articles[cat][:10]

        current_data_hash = compute_data_hash(categorized_articles)
        has_updates = last_data_hash != current_data_hash
        
        if has_updates:
            last_data_hash = current_data_hash
            return jsonify({"articles": categorized_articles, "last_update": last_update_time, "has_updates": True})
        else:
            return jsonify({"articles": {}, "last_update": last_update_time, "has_updates": False})
    except Exception as e:
        logger.error(f"Error fetching updates: {e}")
        return jsonify({"articles": {}, "last_update": last_update_time, "has_updates": False}), 500

@app.route('/card')
def card_load():
    return render_template("card.html")

@app.route('/api/v1/search', methods=['GET'])
def api_search():
    query = request.args.get('q')
    limit = request.args.get('limit', default=20, type=int)

    if not query:
        return jsonify({"error": "Query parameter 'q' is required."}), 400

    vector_db = get_vector_db()
    if not vector_db:
        return jsonify({"error": "Database not available."}), 503

    try:
        results = vector_db.similarity_search_with_relevance_scores(query, k=limit)
        formatted_articles = format_articles_from_db_results(results)
        return jsonify(formatted_articles)
    except Exception as e:
        logger.error(f"API Search error: {e}", exc_info=True)
        return jsonify({"error": "An internal error occurred during search."}), 500

@app.route('/api/v1/articles/category/<string:category_name>', methods=['GET'])
def api_get_articles_by_category(category_name):
    limit = request.args.get('limit', default=20, type=int)
    offset = request.args.get('offset', default=0, type=int)

    vector_db = get_vector_db()
    if not vector_db:
        return jsonify({"error": "Database not available."}), 503

    try:
        results = vector_db.get(where={"category": category_name}, include=['documents', 'metadatas'])
        formatted_articles = format_articles_from_db_results(results)
        paginated_results = formatted_articles[offset : offset + limit]
        
        return jsonify({
            "category": category_name,
            "total_articles": len(formatted_articles),
            "articles": paginated_results
        })
    except Exception as e:
        logger.error(f"API Category fetch error: {e}", exc_info=True)
        return jsonify({"error": "An internal error occurred."}), 500

@app.route('/api/v1/categories', methods=['GET'])
def api_get_categories():
    vector_db = get_vector_db()
    if not vector_db:
        return jsonify({"error": "Database not available."}), 503
        
    try:
        all_metadata = vector_db.get(include=['metadatas'])['metadatas']
        if not all_metadata:
            return jsonify([])
            
        unique_categories = sorted(list({meta['category'] for meta in all_metadata if 'category' in meta}))
        return jsonify(unique_categories)
    except Exception as e:
        logger.error(f"API Categories fetch error: {e}", exc_info=True)
        return jsonify({"error": "An internal error occurred."}), 500

@app.route('/api/v1/status', methods=['GET'])
def api_get_status():
    return jsonify({
        "status": "complete" if loading_complete else "loading",
        "last_update_time": last_update_time
    })

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=7860)