rastof9 commited on
Commit
e601f21
·
1 Parent(s): c2c6bd3
Files changed (1) hide show
  1. app/routes/google_ads.py.bak +188 -0
app/routes/google_ads.py.bak ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Blueprint, render_template, request, jsonify, current_app
2
+ from flask_login import login_required, current_user
3
+ from app.services.google_scraper import GoogleAdsScraper
4
+ from app.models.google_ad import GoogleAd
5
+ from app.services.ai_processor import AIPipeline
6
+ from app import db, celery
7
+ import logging
8
+
9
+ logger = logging.getLogger(__name__)
10
+ google_ads_bp = Blueprint('google_ads', __name__, url_prefix='/google-ads')
11
+
12
+ @google_ads_bp.route('/', methods=['GET'])
13
+ @login_required
14
+ def index():
15
+ """Google Ads dashboard page."""
16
+ return render_template('google_ads/index.html')
17
+
18
+ @google_ads_bp.route('/search', methods=['GET', 'POST'])
19
+ @login_required
20
+ def search_ads():
21
+ """Search for Google Ads."""
22
+ if request.method == 'POST':
23
+ search_query = request.form.get('query')
24
+ num_pages = int(request.form.get('num_pages', 3))
25
+
26
+ # Start async task for scraping
27
+ task = scrape_google_search_ads.delay(search_query, num_pages, current_user.id)
28
+
29
+ return jsonify({
30
+ 'status': 'success',
31
+ 'message': 'Google Ads scraping started',
32
+ 'task_id': task.id
33
+ })
34
+
35
+ # GET request - show search form
36
+ return render_template('google_ads/search.html')
37
+
38
+ @google_ads_bp.route('/display', methods=['GET', 'POST'])
39
+ @login_required
40
+ def display_ads():
41
+ """Scrape display ads from a URL."""
42
+ if request.method == 'POST':
43
+ target_url = request.form.get('url')
44
+ scroll_count = int(request.form.get('scroll_count', 5))
45
+
46
+ # Start async task for scraping
47
+ task = scrape_google_display_ads.delay(target_url, scroll_count, current_user.id)
48
+
49
+ return jsonify({
50
+ 'status': 'success',
51
+ 'message': 'Google Display Ads scraping started',
52
+ 'task_id': task.id
53
+ })
54
+
55
+ # GET request - show form
56
+ return render_template('google_ads/display.html')
57
+
58
+ @google_ads_bp.route('/results', methods=['GET'])
59
+ @login_required
60
+ def view_results():
61
+ """View Google Ads results."""
62
+ ad_type = request.args.get('type', 'all')
63
+ query = request.args.get('query', '')
64
+
65
+ # Build query
66
+ ads_query = GoogleAd.query
67
+
68
+ if ad_type != 'all':
69
+ ads_query = ads_query.filter(GoogleAd.ad_type == ad_type)
70
+
71
+ if query:
72
+ ads_query = ads_query.filter(
73
+ (GoogleAd.title.ilike(f'%{query}%')) |
74
+ (GoogleAd.description.ilike(f'%{query}%')) |
75
+ (GoogleAd.search_query.ilike(f'%{query}%'))
76
+ )
77
+
78
+ # Get results
79
+ ads = ads_query.order_by(GoogleAd.created_at.desc()).all()
80
+
81
+ return render_template('google_ads/results.html', ads=ads, ad_type=ad_type, query=query)
82
+
83
+ @google_ads_bp.route('/api/ads', methods=['GET'])
84
+ @login_required
85
+ def api_get_ads():
86
+ """API endpoint to get Google Ads data."""
87
+ ad_type = request.args.get('type', 'all')
88
+ query = request.args.get('query', '')
89
+ limit = int(request.args.get('limit', 50))
90
+
91
+ # Build query
92
+ ads_query = GoogleAd.query
93
+
94
+ if ad_type != 'all':
95
+ ads_query = ads_query.filter(GoogleAd.ad_type == ad_type)
96
+
97
+ if query:
98
+ ads_query = ads_query.filter(
99
+ (GoogleAd.title.ilike(f'%{query}%')) |
100
+ (GoogleAd.description.ilike(f'%{query}%')) |
101
+ (GoogleAd.search_query.ilike(f'%{query}%'))
102
+ )
103
+
104
+ # Get results
105
+ ads = ads_query.order_by(GoogleAd.created_at.desc()).limit(limit).all()
106
+
107
+ # Convert to JSON
108
+ result = []
109
+ for ad in ads:
110
+ ad_data = {
111
+ 'id': ad.id,
112
+ 'ad_type': ad.ad_type,
113
+ 'title': ad.title,
114
+ 'description': ad.description,
115
+ 'display_url': ad.display_url,
116
+ 'target_url': ad.target_url,
117
+ 'image_url': ad.image_url,
118
+ 'position': ad.position,
119
+ 'search_query': ad.search_query,
120
+ 'page_url': ad.page_url,
121
+ 'sentiment': ad.sentiment,
122
+ 'created_at': ad.created_at.isoformat() if ad.created_at else None
123
+ }
124
+ result.append(ad_data)
125
+
126
+ return jsonify(result)
127
+
128
+ @celery.task
129
+ def scrape_google_search_ads(search_query, num_pages, user_id):
130
+ """Celery task to scrape Google search ads."""
131
+ try:
132
+ scraper = GoogleAdsScraper()
133
+ ads_data = scraper.scrape_search_ads(search_query, num_pages)
134
+
135
+ # Process and store ads
136
+ ai_pipeline = AIPipeline()
137
+
138
+ for ad_data in ads_data:
139
+ # Create GoogleAd instance
140
+ ad = GoogleAd.from_search_ad_data(ad_data, search_query, user_id)
141
+
142
+ # Process with AI if there's content
143
+ if ad.title or ad.description:
144
+ try:
145
+ # Create a simple object with content for AI processing
146
+ ad_content = type('obj', (object,), {
147
+ 'content': f"{ad.title} {ad.description}"
148
+ })
149
+
150
+ # Process with AI
151
+ ai_results = ai_pipeline.process_ad(ad_content)
152
+ ad.sentiment = ai_results.get('sentiment')
153
+ except Exception as e:
154
+ logger.error(f"Error processing ad with AI: {e}")
155
+
156
+ # Save to database
157
+ db.session.add(ad)
158
+
159
+ db.session.commit()
160
+ return {'status': 'success', 'count': len(ads_data)}
161
+
162
+ except Exception as e:
163
+ logger.error(f"Error in Google search ads scraping task: {e}")
164
+ db.session.rollback()
165
+ return {'status': 'error', 'message': str(e)}
166
+
167
+ @celery.task
168
+ def scrape_google_display_ads(target_url, scroll_count, user_id):
169
+ """Celery task to scrape Google display ads."""
170
+ try:
171
+ scraper = GoogleAdsScraper()
172
+ ads_data = scraper.scrape_display_ads(target_url, scroll_count)
173
+
174
+ # Process and store ads
175
+ for ad_data in ads_data:
176
+ # Create GoogleAd instance
177
+ ad = GoogleAd.from_display_ad_data(ad_data, user_id)
178
+
179
+ # Save to database
180
+ db.session.add(ad)
181
+
182
+ db.session.commit()
183
+ return {'status': 'success', 'count': len(ads_data)}
184
+
185
+ except Exception as e:
186
+ logger.error(f"Error in Google display ads scraping task: {e}")
187
+ db.session.rollback()
188
+ return {'status': 'error', 'message': str(e)}